Python's Abstract Syntax Trees: Parsing and Transforming Code with ast
This article explains how Python represents source code as an abstract syntax tree, and how the ast module parses, inspects, transforms and recompiles code, evaluates literals and changes between versions, together with its common pitfalls.
Before Python executes a single instruction of a program, it reads the source text and builds a tree that describes its grammatical structure: which statements it contains, which expressions form each statement and how those expressions nest. The present article addresses that tree, the abstract syntax tree, and the module ast, which exposes it to Python code. It shows how a program can parse source code, inspect it without running it, transform it and compile the result, and it examines the limits of these operations, from lost comments to node classes that change between versions. Reading and rewriting code as a data structure, with the same tools that the interpreter uses, is the secret weapon of this module.
From Source Text to Tree
CPython processes source code in stages: the parser turns the text into an abstract syntax tree, and the compiler turns the tree into the bytecode described in the article devoted to bytecode. The function ast.parse performs the first stage and returns the root of the tree, an ast.Module whose attribute body lists the statements.
import ast
tree = ast.parse("result = 10 + 5")
statement = tree.body[0]
print(ast.dump(statement))
# Output: Assign(targets=[Name(id='result', ctx=Store())], value=BinOp(left=Constant(value=10), op=Add(), right=Constant(value=5)))
print(type(statement.value).__name__, statement.value.left.value) # Output: BinOp 10
print(ast.unparse(tree)) # Output: result = 10 + 5
The assignment is an Assign node whose target is the name result, marked with the context Store, and whose value is a binary operation, BinOp, with two Constant operands and the operator Add. Every node is an ordinary Python object, so its fields can be read as attributes. The function ast.unparse, available since Python 3.9, performs the inverse operation and produces source text from a tree. The output of ast.dump for a whole module differs between versions: up to Python 3.12 it ends with type_ignores=[], whereas since Python 3.13 empty lists are omitted by default, which is why the example dumps a single statement.
Inspecting Code Without Running It
The class ast.NodeVisitor walks a tree and calls a method named visit_ followed by the class of each node, for example visit_Call for every function call. This is how linters examine code without executing it, as the following example shows with two common risks: calls to eval and exec, and except clauses without an exception type.
import ast
source = """
def load(path):
try:
return eval(open(path).read())
except:
return None
"""
class RiskFinder(ast.NodeVisitor):
def __init__(self):
self.findings = []
def visit_Call(self, node):
if isinstance(node.func, ast.Name) and node.func.id in {"eval", "exec"}:
self.findings.append((node.lineno, f"call to {node.func.id}"))
self.generic_visit(node)
def visit_ExceptHandler(self, node):
if node.type is None:
self.findings.append((node.lineno, "bare except"))
self.generic_visit(node)
finder = RiskFinder()
finder.visit(ast.parse(source))
print(finder.findings) # Output: [(4, 'call to eval'), (5, 'bare except')]
names = sorted({node.id for node in ast.walk(ast.parse(source)) if isinstance(node, ast.Name)})
print(names) # Output: ['eval', 'open', 'path']
Each node keeps the line on which it starts, lineno, so a finding can point to its exact location; the source begins with an empty line, which is why the call appears on line 4. The call to generic_visit continues the walk into the children of the node, and without it the calls nested inside the arguments of eval, such as open, would never be visited. When the order of the walk does not matter, ast.walk yields every node of the tree and replaces the class with a one-line comprehension.
Transforming Code: Subclasses of NodeTransformer
Map editors of strategy games offer a precise image of a transformation: the designer opens the structured description of a map, moves units and changes terrain, and the game builds the playable level from the edited description, never from the original. This means that ast.NodeTransformer receives the tree produced by the parser, lets each visit_ method return a modified or a new node, and leaves the compiler to build the program from the edited tree. The analogy, however, stops at this point, because a map editor preserves every detail of the map, whereas a syntax tree has already discarded comments and formatting, as the pitfalls section shows.
import ast
class ShallowSwap(ast.NodeTransformer):
def visit_BinOp(self, node):
if isinstance(node.op, ast.Add):
node.op = ast.Sub()
return node
class DeepSwap(ast.NodeTransformer):
def visit_BinOp(self, node):
self.generic_visit(node)
if isinstance(node.op, ast.Add):
node.op = ast.Sub()
return node
source = "total = 10 + 5 + 1"
print(ast.unparse(ShallowSwap().visit(ast.parse(source)))) # Output: total = 10 + 5 - 1
print(ast.unparse(DeepSwap().visit(ast.parse(source)))) # Output: total = 10 - 5 - 1
tree = ast.fix_missing_locations(DeepSwap().visit(ast.parse(source)))
namespace = {}
exec(compile(tree, "<transformed>", "exec"), namespace)
print(namespace["total"]) # Output: 4
The expression 10 + 5 + 1 is a BinOp whose left operand is another BinOp, 10 + 5. The shallow transformer returns the outer node without visiting its children, so only the last addition changes, a mistake that many tutorials repeat; the documentation states that a transformer must either handle the children itself or call generic_visit. The deep version visits the children first and changes both operators, and the edited tree compiles and runs like any other module, giving 10 - 5 - 1, that is, 4. The same technique, applied by a custom loader before exec_module, transforms whole modules at import time, as described in the article devoted to import hooks.
Evaluating Literals with literal_eval
The function ast.literal_eval evaluates a string that contains only a Python literal (numbers, strings, bytes, tuples, lists, dictionaries, sets, booleans and None) and rejects anything else, including names and calls.
import ast
config = ast.literal_eval("{'retries': 3, 'hosts': ('a', 'b'), 'debug': False}")
print(config["hosts"]) # Output: ('a', 'b')
try:
ast.literal_eval("__import__('os').getcwd()")
except ValueError as error:
print(type(error).__name__) # Output: ValueError
The dictionary is rebuilt without executing any code, and the expression that tries to import a module is rejected. The function is nevertheless not a sandbox: the documentation calls its former description as "safe" misleading and advises against using it on untrusted data, because a crafted literal can still exhaust memory or the stack of the interpreter. For data received from outside a program, json remains the appropriate format.
Pitfalls of Working with Syntax Trees
A syntax tree is a faithful image of the meaning of the code, but not of its text, and it is tied to the version of the interpreter. Six pitfalls are distinguished, which are the following:
- Forgetting
generic_visit. A visitor or transformer that does not continue into the children silently ignores nested code. - Missing locations. A node created by hand has no line numbers, and compiling the tree fails until
ast.fix_missing_locationsfills them in. - Lost comments and formatting. The tree keeps no comments, blank lines or quotation style, so
ast.unparsedoes not reproduce the original text; formatters and refactoring tools that must preserve the text use concrete syntax trees instead. - Version-dependent node classes. Node classes change between versions:
ast.Num,ast.Strand theirvisit_Num-style methods were deprecated in Python 3.8 and removed in Python 3.14, so older visitors must useast.Constant. - Trusting
literal_eval. It rejects code, not hostile input, and must not process untrusted data. - Executing transformed code. A transformation that compiles and runs code inherits every risk of
exec, and errors in the edited tree point to lines that do not exist in any file.
The second and third pitfalls are reproduced in the following example.
import ast
call = ast.Expr(ast.Call(func=ast.Name("print", ast.Load()), args=[ast.Constant("added")], keywords=[]))
tree = ast.parse("x = 1 # a comment")
tree.body.append(call)
try:
compile(tree, "<generated>", "exec")
except TypeError as error:
print(error) # Output (CPython 3.12): required field "lineno" missing from stmt
compile(ast.fix_missing_locations(tree), "<generated>", "exec")
print(ast.unparse(tree))
# Output: x = 1
# Output: print('added')
The new statement could be compiled only after fix_missing_locations copied the positions of its parent, and the comment of the original line is absent from the regenerated source.
Choosing a Tool for Analysing Code
Consequently, the module ast is the right level for questions about the structure of code, whereas other tools address its text or its execution, as the following table summarizes.
| Situation | Recommended approach |
|---|---|
| Finding patterns in code without running it | ast.parse with a NodeVisitor or ast.walk |
| Rewriting code before it is compiled or imported | ast.NodeTransformer, fix_missing_locations and compile |
| Reformatting code while keeping comments | A concrete syntax tree library, not ast.unparse |
| Reading Python literals from a trusted string | ast.literal_eval |
| Reading data from untrusted sources | json or another data format |
| Studying what the interpreter will execute | dis, on the compiled bytecode |
Conclusion
It is concluded that the abstract syntax tree is the structure that CPython builds between the source text and the bytecode, and that the module ast lets a program parse, inspect, transform and recompile code with the same representation that the interpreter uses. This magic requires walking every child, restoring locations, accepting the loss of comments and following the node classes of each version. Analysing code that is already loaded first requires obtaining its source, which is the task of the module inspect, developed in a future article of this series.