QA
Senior LevelPython

How do you write custom AST transformers by subclassing ast.NodeTransformer to rewrite Python source code programmatically before compilation?

❓ Interview Prompt: Explain Abstract Syntax Trees (AST), `ast.parse()`, `ast.NodeTransformer`, mutating syntax nodes, and code generation.

Python exposes its compiler Abstract Syntax Tree (AST) via the 'ast' module:

AST Metaprogramming Workflow:

1
Parse source text into AST syntax nodes using 'ast.parse(code)'.
2
Subclass 'ast.NodeTransformer' to intercept and rewrite specific syntax nodes (used by 'pytest' for assertion rewriting!).
3
Compile modified AST back into bytecode using 'compile(tree, filename, 'exec')'.

Code Implementation Example

python
import ast

class ConstantRewriter(ast.NodeTransformer):
    def visit_Constant(self, node):
        if isinstance(node.value, int):
            return ast.copy_location(ast.Constant(value=node.value * 10), node)
        return node

code = 'x = 5'
tree = ast.parse(code)
rewritten_tree = ConstantRewriter().visit(tree)
ast.fix_missing_locations(rewritten_tree)

exec(compile(rewritten_tree, '<string>', 'exec'))
# x is now 50!
💡Rewriting integer constants programmatically using ast.NodeTransformer.
🎯 Interview Key Takeaway

Use ast.NodeTransformer to inspect, rewrite, and optimize Python Abstract Syntax Trees programmatically.

#AST#ast.NodeTransformer#Metaprogramming#Compilers#Senior
Back to all Python Questions→

More Python Interview Questions

Beginner LevelPython

What is the Python Global Interpreter Lock (GIL) and how does it affect multi-threading?

Beginner LevelPython

What is the difference between a List, Tuple, Set, and Dictionary in Python?

Beginner LevelPython

Why are mutable default arguments (like def func(items=[])) dangerous in Python and how do you fix them?