how to extract source code from code objects ?

Pieter Nagel pnagel at
Sat Jan 4 12:32:24 CET 2003

In the short term, you could solve your problem by using the 
compiler.visitor module to walk the AST.

Something like:

   class MathExpressionASTVisitor:
     def visitCallFunc(self, callFunc):
       funcName = # or however this is done
       if funcName == 'square':
          print callFunc.args, '**2',
          print funcName, '(', callFunc.args, ')',

   visitor = MathExpressionASTVisitor()
   import compiler
   compiler.visitor.ASTVisitor().preorder(ast, visitor)

But this is only crude pseudocode.      	

In the long term, I would suggest that you use your own type of abstract 
syntax tree to represent the parsed expressions, instead of Python's 
AST. When you do more complex manipulations, you are going to need more 
and more code on the ast tree that Python does not offer.

Of course, as long as the syntax of your expressions is sufficiently 
Pythonesque, you can use the Python compiler module to parse it for you; 
and then use the visitor pattern above to transform the Python AST into 
your AST.

      /_)              /| /
     /   i e t e r    / |/ a g e l

More information about the Python-list mailing list