class documentation

class NodeTransformer(NodeVisitor):

View In Hierarchy

Walks the abstract syntax tree and allows modifications of nodes.

The NodeTransformer will walk the AST and use the return value of the visitor functions to replace or remove the old node. If the return value of the visitor function is None the node will be removed from the previous location otherwise it's replaced with the return value. The return value may be the original node in which case no replacement takes place.

Here an example transformer that rewrites all foo to data['foo']:

class RewriteName(NodeTransformer):

    def visit_Name(self, node):
        return copy_location(Subscript(
            value=Name(id='data', ctx=Load()),
            slice=Index(value=Str(s=node.id)),
            ctx=node.ctx
        ), node)

Keep in mind that if the node you're operating on has child nodes you must either transform the child nodes yourself or call the generic visit function for the node first.

Nodes that were part of a collection of statements (that applies to all statement nodes) may also return a list of nodes rather than just a single node.

Usually you use the transformer like this:

node = YourTransformer().visit(node)
Method generic​_visit Called if no explicit visitor function exists for a node.

Inherited from NodeVisitor:

Method get​_visitor Return the visitor function for this node or None if no visitor exists for this node. In that case the generic visit function is used instead.
Method visit Visit a node.
def generic_visit(self, node):
Called if no explicit visitor function exists for a node.