Back
+20 XP
Concept

Rewriting Code at Runtime with `ast.NodeTransformer`

While `NodeVisitor` is read-only, `ast.NodeTransformer` mutates or swaps nodes in-place. Returning a transformed node replaces it in the AST; returning `None` completely eliminates the node from the tree 🔄.

python
import ast

class SquareToCube(ast.NodeTransformer):
    def visit_BinOp(self, node):
        self.generic_visit(node)
        if isinstance(node.op, ast.Pow) and isinstance(node.right, ast.Constant):
            if node.right.value == 2:
                node.right.value = 3
        return node

tree = ast.parse("val = x ** 2")
new_tree = SquareToCube().visit(tree)
ast.fix_missing_locations(new_tree)
print(f"Transformed: {ast.unparse(new_tree)} 🔄")

# 65. Rewriting Code at Runtime with `ast.NodeTransformer` While `NodeVisitor` is read-only, `ast.NodeTransformer` mutates or swaps nodes in-place. Returning a transformed node replaces it in the AST; returning `None` completely eliminates the node from the tree 🔄. ```python import ast class SquareToCube(ast.NodeTransformer): def visit_BinOp(self, node): self.generic_visit(node) if isinstance(node.op, ast.Pow) and isinstance(node.right, ast.Constant): if node.right.value == 2: node.right.value = 3 return node tree = ast.parse("val = x ** 2") new_tree = SquareToCube().visit(tree) ast.fix_missing_locations(new_tree) print(f"Transformed: {ast.unparse(new_tree)} 🔄") ``` Whenever you synthesize or modify AST nodes, always invoke `ast.fix_missing_locations(new_tree)` so the compiler backfills required line and column numbers before compiling to bytecode ⚡! --- ### Question What happens when a custom method in `ast.NodeTransformer` returns `None` for a visited node? 🧠 - [ ] a. The visited node is purged/removed completely from the syntax tree 🔄 - [ ] b. It raises a FatalSyntaxException halting the compiler run - [ ] c. The node is automatically serialized into an inline comment token - [ ] d. The node is replaced by a constant literal node containing None --- ### Challenge Build an `ast.NodeTransformer` called `DoubleConstants` that multiplies every integer `ast.Constant` value by 2. Transform `'x = 5 + 10'`. Print `ast.unparse(new_tree)`. 🎯 <details> <summary>Solution</summary> ```python import ast class DoubleConstants(ast.NodeTransformer): def visit_Constant(self, node): if isinstance(node.value, int): node.value *= 2 return node tree = ast.parse('x = 5 + 10') new_tree = DoubleConstants().visit(tree) ast.fix_missing_locations(new_tree) print(ast.unparse(new_tree)) ``` </details>

Checkpoint

What happens when a custom method in `ast.NodeTransformer` returns `None` for a visited node? 🧠

Practice

Build an `ast.NodeTransformer` called `DoubleConstants` that multiplies every integer `ast.Constant` value by 2. Transform `'x = 5 + 10'`. Print `ast.unparse(new_tree)`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks