source code of a function object

anton muhin antonmuhin.REMOVE.ME.FOR.REAL.MAIL at
Thu Nov 13 16:25:14 CET 2003

Fernando Rodriguez wrote:

> Hi,
> Is ti possible to get the source code of a given function object? O:-)

I'm not an expert, but I'd say that mostly yes, however:

def foo():

bar_code_block = compile('def bar(): pass', '<string>', 'exec')
exec bar_code_block

import inspect

assert 'foo' in locals()
print inspect.getsource(foo)

assert 'bar' in locals()
print inspect.getsource(bar)

def foo():

Traceback (most recent call last):
   File "", line 13, in ?
     print inspect.getsource(bar)
   File "D:\Python23\lib\", line 549, in getsource
     lines, lnum = getsourcelines(object)
   File "D:\Python23\lib\", line 538, in getsourcelines
     lines, lnum = findsource(object)
   File "D:\Python23\lib\", line 408, in findsource
     raise IOError('could not get source code')
IOError: could not get source code

Therefore, I'd suggest that you can get source code of functions that 
are not created with eval/exec etc.

of course, you cannot get source code of C functions (e.g. most of 
builtins, I suppose).


More information about the Python-list mailing list