how to extract source code from code objects ?

Skip Montanaro skip at pobox.com
Fri Jan 3 10:47:17 EST 2003


    Michele> decompyle works and it is easy to install and to use. However,
    Michele> it is not in the standard library and this implies two
    Michele> disadvantages:
    Michele> i) it is not universally available;
    Michele> ii) for any new version of Python I must download a new version
    Michele> of decompyle. 

    Michele> I was hoping for a more built-in solution, as for instance an
    Michele> attribute .co_source in code objects. I guess this would be
    Michele> inefficient for memory consumption or for other technical
    Michele> reasons.

Inefficient, perhaps, but not hugely, I wouldn't think, since code objects
are relatively rare beasts in the Python object landscape.  The source code
isn't normally needed, because in most cases it can be looked up in the
source file (check out the inspect.getsource function).  If you can provide
a convincing use case why the source for manually compiled code should be
retained in a feature request on SourceForge, it's possible that someone
will add a co_source field to code objects.  It would help if you supplied a
patch that implemented the feature request.  (Note that simply extending
code objects with a co_source slot won't be enough.  The compiler will have
to be modified to stuff the code in there.)

An alternative is to simply maintain a dictionary that maps code objects to
source code, e.g.,:

    >>> def f(): pass
    ... 
    >>> f
    <function f at 0x3ba538>
    >>> d = {}
    >>> d[f.func_code] = 'pass'

Since code objects are immutable, they can be used as dictionary keys.
Would that be sufficient for your needs?

Skip





More information about the Python-list mailing list