How to see the code definiton in the shell ?

J. Cliff Dyer jcd at sdf.lonestar.org
Wed May 13 13:26:18 EDT 2009


On Wed, 2009-05-13 at 09:40 -0700, Mohan Parthasarathy wrote:
> Hi,
> 
> I am new to Python. I tried searching this but could not find an
> answer. In the interactive shell, I write a new function and I want to
> be able to see all the code that I wrote at a later time. Just typing
> the function name only shows 
> 
> >>> allmethods
> <function allmethods at 0x822b0>
> 
> How do I see the actual code ?
> 
> thanks
> mohan
> 

The function definition itself has been compiled down to bytecode.  You
can see the bytecode as follows:

>>> def one():
...     return 1
...
>>> print one.func_code.co_code  # not very readable
'd\x01\x00S'
>>> import dis # python disassembler
>>> dis.dis(one.func_code.co_code)
          0 LOAD_CONST          1 (1)
          3 RETURN_VALUE   

or just run dis.dis on the function itself

>>> def two():
...     import math
...     return (math.e ** (0+1J*math.pi)) + 3
... 
>>> two()
(2+1.2246063538223773e-16j)
>>> two.func_code.co_code
'd\x01\x00d\x00\x00k\x00\x00}\x00\x00|\x00\x00i\x01\x00d\x02\x00d\x03
\x00|\x00\x00i\x02\x00\x14\x17\x13d\x04\x00\x17S'
>>> dis.dis(two)
  2           0 LOAD_CONST               1 (-1)
              3 LOAD_CONST               0 (None)
              6 IMPORT_NAME              0 (math)
              9 STORE_FAST               0 (math)

  3          12 LOAD_FAST                0 (math)
             15 LOAD_ATTR                1 (e)
             18 LOAD_CONST               2 (0)
             21 LOAD_CONST               3 (1j)
             24 LOAD_FAST                0 (math)
             27 LOAD_ATTR                2 (pi)
             30 BINARY_MULTIPLY     
             31 BINARY_ADD          
             32 BINARY_POWER        
             33 LOAD_CONST               4 (3)
             36 BINARY_ADD          
             37 RETURN_VALUE        






More information about the Python-list mailing list