all Python 3astfunction
ast.fix_missing_locations()
helper functions
Fills in lineno and col_offset for every node of a tree that lacks them, copying them from the parent. A required step before compile() of a tree with new nodes.
Syntax
tree = ast.fix_missing_locations(tree)
Nodes built by hand or by a NodeTransformer have no positions, and compile() fails with TypeError: required field "lineno" missing. unparse and dump work fine meanwhile, so the error only appears at compile time. Call it on the whole transformed tree: tree = ast.fix_missing_locations(tree); it edits the tree in place and returns it. Positions already set are left alone.
Examples
import ast
tree = ast.parse('print(x)')
call = tree.body[0].value
call.args[0] = ast.BinOp(left=ast.Name(id='x', ctx=ast.Load()), op=ast.Mult(),
right=ast.Constant(value=2))
try:
compile(tree, '<ast>', 'exec')
except TypeError as e:
print(e) # → required field "lineno" missing from expr
tree = ast.fix_missing_locations(tree)
exec(compile(tree, '<ast>', 'exec'), {'x': 21}) # → 42
print(call.args[0].lineno) # → 1
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy