source code of a function object

F

Fernando Rodriguez

Hi,

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

TIA
 
E

Erno Kuusela

Fernando Rodriguez said:
Hi,

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

TIA
def dumps(obj, protocol=None, bin=None):
file = StringIO()
Pickler(file, protocol, bin).dump(obj)
return file.getvalue()

-- erno
 
A

anton muhin

Fernando said:
Hi,

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

TIA

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

def foo():
pass

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)

Python2.3:
def foo():
pass

Traceback (most recent call last):
File "source.py", line 13, in ?
print inspect.getsource(bar)
File "D:\Python23\lib\inspect.py", line 549, in getsource
lines, lnum = getsourcelines(object)
File "D:\Python23\lib\inspect.py", line 538, in getsourcelines
lines, lnum = findsource(object)
File "D:\Python23\lib\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).

regards,
anton.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,169
Messages
2,570,920
Members
47,464
Latest member
Bobbylenly

Latest Threads

Top