source code of a function object

POYEN OP Olivier (DCL) Olivier.POYEN at clf-dexia.com
Fri Nov 14 03:01:15 EST 2003


>>> import pickle, inspect
>>> print inspect.getsource(pickle.dumps)
def dumps(obj, protocol=None, bin=None):
    file = StringIO()
    Pickler(file, protocol, bin).dump(obj)
    return file.getvalue()



By the way, this does not work with 'live' object, like the one you've just created, without disk backend:
ActivePython 2.3.2 Build 230 (ActiveState Corp.) based on
Python 2.3.2 (#49, Oct 24 2003, 13:37:57) [MSC v.1200 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import inspect
>>> def f():print 'toto'
...
>>> inspect.getsource(f)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "C:\Program Files\Python23\lib\inspect.py", line 549, in getsource
    lines, lnum = getsourcelines(object)
  File "C:\Program Files\Python23\lib\inspect.py", line 538, in getsourcelines
    lines, lnum = findsource(object)
  File "C:\Program Files\Python23\lib\inspect.py", line 408, in findsource
    raise IOError('could not get source code')
IOError: could not get source code

The only way I found for that is to use decompyle on 'live' object. 
For python <2.3 it does the job


---OPQ
Long signature following


---------------------
An electronic message is not binding on its sender.  
Any message referring to a binding engagement must be confirmed in writing and duly signed.
---------------------






More information about the Python-list mailing list