how to extract source code from code objects ?

Michele Simionato mis6 at pitt.edu
Fri Jan 3 10:25:43 EST 2003


Jp Calderone <exarkun at intarweb.us> wrote in message news:<mailman.1041525363.20935.python-list at python.org>...
> On Thu, Jan 02, 2003 at 08:14:52AM -0800, Michele Simionato wrote:
> > I can compile a string in a code object:
> > 
> > >>> code object=compile('x=1','<string>','exec')
> > 
> > now the code object.co code attribute contains the bytecode corresponding
> > to the statement x=1:
> > 
> > >>> code object.co code
> > '\x7f\x00\x00\x7f\x01\x00d\x00\x00Z\x00\x00d\x01\x00S'
> > 
> > Is there a way to have back the source code, i.e. the string 'x=1'
> > instead of the bytecode ?
> > TIA,
>  
> >>> import decompyle
> >>> decompyle.decompyle(compile('x=1', '<string>', 'exec'))
> x = 1
> 
>   http://www.crazy-compilers.com/decompyle/
> 
>   Jp
> 
> 

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

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

My original problem was to convert back to source an AST object
generated with the parser module. Since parser.st objects can be converted 
to code objects, I asked how to extract source code from code objects.
It seems that there is no simple built-in way of doing that (decompyle
is a few thousands of lines of not so simple Python code).

I guess the reason why there is no standard way to extract the source
from AST objects is that their implementation (can) change with new
version of Python, therefore there would be a maintanance issue
(as it happens with decompyle). Am I correct ?

Cheers,


                                             Michele




More information about the Python-list mailing list