Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postorder traversal on a ast.nodevisitor in Python

Is it possible to do a postorder traversal on an instance of ast.NodeVisitor in Python just by manipulating the ast.NodeVisitor.generic_visit()? I did this:

class ExpParser(ast.NodeVisitor):

    def generic_visit(self, node):
        for x in ast.iter_child_nodes(node):
            ast.NodeVisitor.generic_visit(self, x)
        ast.NodeVisitor.generic_visit(self, node)

    def visit_BinOp(self, node):
        print type(node.op).__name__ 

    def visit_Name(self, node):
        print node.id

if __name__ == '__main__':
    node = ast.parse("T1+T2*T3")
    v = ExpParser()
    v.visit(node)

this gave me:

T1
T2
T3
Mult
Add

I want it to give me:

T2
T3
Mult
T1
Add

How can I do it? please I'm stuck.

like image 300
Academia Avatar asked Jul 31 '26 07:07

Academia


1 Answers

try something like this

import ast

class ExpParser(ast.NodeVisitor):

    def generic_visit(self, node):
        for field, value in reversed(list(ast.iter_fields(node))):
            if isinstance(value, list):
                for item in value:
                    if isinstance(item, ast.AST):
                        self.visit(item)
            elif isinstance(value, ast.AST):
                self.visit(value)

    def visit_BinOp(self, node):
        self.generic_visit(node)
        print type(node.op).__name__ 

    def visit_Name(self, node):
        self.generic_visit(node)
        print node.id

if __name__ == '__main__':
    node = ast.parse("T1+T2*T3")
    v = ExpParser()
    v.visit(node)

don't forget to call generic_visit on each visit method, or alternatively reimplement visit method to take care of it automatically.

like image 105
Edu Avatar answered Aug 01 '26 21:08

Edu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!