how to extract source code from code objects ?
"Martin v. Löwis"
martin at v.loewis.de
Fri Jan 3 11:03:02 EST 2003
Michele Simionato wrote:
> 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.
Can you please explain why you are hoping for a builtin solution?
> 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).
Generating source from an AST object is much simpler than generating
source from byte code. However, I still wonder where the need comes from
in the first place: If you have just created the AST, you surely still
have a copy of the source code around.
> 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 ?
No. There is no way to do that because nobody ever wanted to do it (or
atleast no frequently enough to contribute a solution to the standard
library). If such a thing would be contributed then you are right: there
would be a maintenance issue. So any volunteer to contribute that
feature would also need to volunteer to maintain it.
In Python itself, this entire issue is solved more pragmatically: When
you need the source (e.g. for a traceback), you look at the line number,
locate the source file, and print the relevant lines.
Regards,
Martin
More information about the Python-list
mailing list