how to extract source code from code objects ?

Pieter Nagel pnagel at nagel.co.za
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 = callFunc.node.name # or however this is done
       if funcName == 'square':
          print callFunc.args, '**2',
       else:
          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
     http://www.nagel.co.za





More information about the Python-list mailing list