all Python 3astterm
ast.NodeTransformer
helper functions
A NodeVisitor subclass for changing a tree: the value returned by visit_* replaces the node, and None removes it.
Syntax
class T(ast.NodeTransformer):
def visit_Name(self, node): return node
tree = T().visit(tree)
A forgotten return in a visit_* method is a common bug: the method returns None and the node silently disappears from the tree. For statements you may return a list of nodes to replace a single one. New nodes have no lineno, so compile() fails with TypeError until you call ast.fix_missing_locations(tree). As with NodeVisitor, you must visit children yourself via generic_visit.
Examples
import ast
class Oops(ast.NodeTransformer):
def visit_Expr(self, node):
node.value = ast.Constant(0)
tree = Oops().visit(ast.parse('print(1)\nx = 2'))
print(ast.unparse(tree)) # → x = 2 — print исчез
import ast
class Upper(ast.NodeTransformer):
def visit_Constant(self, node):
if isinstance(node.value, str):
return ast.Constant(node.value.upper())
return node
tree = Upper().visit(ast.parse("print('hi')"))
try:
compile(tree, '<ast>', 'exec')
except TypeError:
print('нет lineno') # → нет lineno
exec(compile(ast.fix_missing_locations(tree), '<ast>', 'exec')) # → HI
See also
Open in the full glossarydocs.python.orgReport an inaccuracy