What is ast.NodeTransformer in Python?
ast.NodeTransformer is a subclass of ast.NodeVisitor that walks through an ast tree and can apply transformations to any node in the tree.
NodeTransformer allows you to override the visit methods, and modifying the method’s return value allows you to transform the node as the programmer wishes. If the return value is set to None, then that node is removed from the tree. If no replacement is done to the return value, the return value will be the original node.
Example
import astfrom pprint import pprintclass TransformName(ast.NodeTransformer):def visit_Name(self, node):return ast.Subscript(value=ast.Name(id='data', ctx=ast.Load()),slice=ast.Constant(value=node.id),ctx=node.ctx)tree = ast.parse('foo', mode='eval')print("Before transformation:")pprint(ast.dump(tree))print("After transformation:")ast.fix_missing_locations(TransformName().visit(tree))pprint(ast.dump(tree))
Explanation
The above program modifies any Name node, like variable names, to data[<variable_name>]. Specifically, the above code transforms the node lookup of foo to data['foo'].
- We define a
TransformNameclass that extends theast.NodeTransformerclass and overrides thevisit_Namemethod. - We set the return value to a
Subscriptnode with the namedataand the contents of thesliceas aConstantnode with the value as the variable name.node.idrepresents the raw string of the variable name. - We can observe before the transformation that a
Namenode is printed in the tree. - We call the constructor of our
TransformNameclass to create an object of that class and use thevisitmethod, which invokes thevisit_Namemethod to transform theNamenode to aSubscriptnode. - The
ast.fix_missing_locations()method is called on the new tree to relocate all the nodes in the tree, since ourTransformNameclass introduced a new node that was not part of the original tree. - We observe that
foois now transformed todata['foo'].