how to extract source code from code objects ?

Michele Simionato mis6 at pitt.edu
Fri Jan 3 13:26:59 EST 2003


Thanks for the kind replies. Here is my motivation.
I was experimenting with symbolic manipulations in Python (see a
thread on this
subject I started few weeks ago). In that thread I asked for a
function able
to perform nontrivial substitutions in Python expression. For instance
I
wanted a function that could transform the expression

"square(square(x+y)+z)+square(x+w)"

in

"((x+y)**2+z)**2+(x+w)**2"

when square is the function that sends x -> x**2.

For this simple problem Bengt Richter provided me with a nice solution
involving the tokenize module. However that solution is not general.
In the case of complicate arguments (involving nested lists for
instance) it is not enough to scan the Python code,  one needs to
parse it. Therefore, I wanted to use the parser module to extract the
AST of the original expression, modify it, and go back to source code
for the modified AST. However, I haven't seen a builtin mechanism to
convert AST -> source. One can convert AST -> bytecode and for this
reason I wanted to convert bytecode to source. It would be much better
for me to convert directly AST -> source. How easy/difficult is it ?

I haven't in mind a project involving symbolic manipulations, I am
considering
this problem with the only aim of better understanding how Python
works
under the hood (incidentally, notice that this kind of manipulations
on the source code are very close to having macros in Python).

                                    Michele




More information about the Python-list mailing list