parsing - Visiting nodes in a syntax tree with Python ast module -


i'm playing python ast (abstract syntax tree).

i wrote following , visited nodes of ast.

import ast  class py2neko(ast.nodevisitor):     def generic_visit(self, node):               print type(node).__name__               ast.nodevisitor.generic_visit(self, node)         def visit_name(self, node):               print 'name :', node.id         def visit_num(self, node):               print 'num :', node.__dict__['n']         def visit_str(self, node):               print "str :", node.s  if __name__ == '__main__':      node = ast.parse("a = 1 + 2")      print ast.dump(node)      v = py2neko()     v.visit(node) 

then added methods py2neko class

def visit_print(self, node):     print "print :"  def visit_assign(self, node):     print "assign :"  def visit_expr(self, node):     print "expr :" 

but when encounters "print" statement or assignement or expression seems stops , isn't going further.

it outputs:

module(body=[assign(targets=[name(id='a', ctx=store())], value=binop(left=num(n=1), op=add(),       right=num(n=2)))]) module assign : 

can tell me did wrong.

i'm using python 2.6.6

since visit_assign method not explicitly process child nodes of assign node, traversal of syntax tree stops there.

if have @ nodevisitor.generic_visit method in implementation of ast.py, you'll see loops through children of current node. so, can explicitly call base class generic_visit method each of methods needs process children:

import ast  class py2neko(ast.nodevisitor):     def generic_visit(self, node):         print type(node).__name__         ast.nodevisitor.generic_visit(self, node)      def visit_name(self, node):         print 'name :', node.id      def visit_num(self, node):         print 'num :', node.__dict__['n']      def visit_str(self, node):         print "str :", node.s      def visit_print(self, node):         print "print :"         ast.nodevisitor.generic_visit(self, node)      def visit_assign(self, node):         print "assign :"         ast.nodevisitor.generic_visit(self, node)      def visit_expr(self, node):         print "expr :"         ast.nodevisitor.generic_visit(self, node)  if __name__ == '__main__':     node = ast.parse("a = 1 + 2")      print ast.dump(node)      v = py2neko()     v.visit(node) 

Comments

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -