Search code examples
pythonvisitor-pattern

Python 'ast' module with Visitor pattern - get node's group, not concrete class


I'm using ast python library and want to traverse through my ast nodes.

Visitor pattern is supported in the library pretty well, but if I use it, I will have to implement methods for visiting items of concrete classes, e.g. def visit_Load. In my case, concrete classes are not so important - I'd like to know whether the node is an operator or an expr according to the structure given here.

Of course, I can add generic_visit method and then check all the conditions here, but that looks like a wrong way to use the pattern.

Is there any other pretty way to implement this idea without massive code duplication?


Solution

  • This probably isn't pretty, but you can dynamically create all the methods by introspection:

    def visit_expr(self, node):
        """Do something in here!"""
        self.generic_visit(node)
    
    ExprVisitor = type('ExprVisitor', (ast.NodeVisitor,), {
        'visit_' % cls.__name__: visit_expr for cls in ast.expr.__subclasses__()})
    

    Of course, you can keep doing this for whatever ast node types you need to deal with. . .