Fernando Rodriguez <frr@easyjob.ne t> writes:
[color=blue]
> Hi,
>
> Is ti possible to get the source code of a given function object? O:-)
>
> TIA[/color]
[color=blue][color=green][color=darkred]
>>> import pickle, inspect
>>> print inspect.getsour ce(pickle.dumps )[/color][/color][/color]
def dumps(obj, protocol=None, bin=None):
file = StringIO()
Pickler(file, protocol, bin).dump(obj)
return file.getvalue()
[color=blue][color=green][color=darkred]
>>>[/color][/color][/color]
assert 'foo' in locals()
print inspect.getsour ce(foo)
assert 'bar' in locals()
print inspect.getsour ce(bar)
Python2.3:
def foo():
pass
Traceback (most recent call last):
File "source.py" , line 13, in ?
print inspect.getsour ce(bar)
File "D:\Python23\li b\inspect.py", line 549, in getsource
lines, lnum = getsourcelines( object)
File "D:\Python23\li b\inspect.py", line 538, in getsourcelines
lines, lnum = findsource(obje ct)
File "D:\Python23\li b\inspect.py", 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).
Comment