[Tutor] printing out the definition of a func [dis/inspect]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 21 Dec 2001 11:57:56 -0800 (PST)


On Thu, 20 Dec 2001, lonetwin wrote:

>      A quick question, can I print out the definition of a func/class
> *after* I have defined it, in the python intepreter ??? ....it'd be
> nice to be able to do this 'cos I seem to need it pretty often (for
> debugging stuff)....and no, I do not use IDLE, 'cos I work at command
> prompt (under linux) and fire-up the intepreter there (X *crawls* on
> my system).

I don't think this will be easy to do.  Python does give us access to a
"code" object for a function:

###
>>> def hello(): print "Hello world"
... 
>>> hello.func_code
<code object hello at 80c9390, file "<stdin>", line 1>
###

but this func_code is something that's already been digested by Python's
byte compiler.

We can take a look at it more closely by using the 'dis' module:

    http://www.python.org/doc/lib/module-dis.html

###
>>> dis.dis(hello)     
          0 SET_LINENO          1

          3 SET_LINENO          1
          6 LOAD_CONST          1 ('Hello world')
          9 PRINT_ITEM     
         10 PRINT_NEWLINE  
         11 LOAD_CONST          0 (None)
         14 RETURN_VALUE 
###

but by then, it's already a bit uglified.

Wait, wait, I spoke too soon.  It is possible!  Take a look at:

    http://www.python.org/doc/lib/inspect-source.html

Hope this helps!