all Python 3astfunction
ast.increment_lineno()
helper functions
Shifts the line numbers (lineno and end_lineno) of every node in a tree by n. Used when a parsed fragment is placed elsewhere in a file.
Syntax
ast.increment_lineno(node, n=1)
The typical case: a fragment is parsed on its own but starts at line 10 of the file; without the shift, errors and tracebacks point at lines 1, 2, 3. Columns are unchanged; the tree is edited in place and returned. When compiling from a string you could just prepend blank lines, but for an existing tree this function is the way.
Examples
import ast
tree = ast.parse('a = 1\nb = 2')
ast.increment_lineno(tree, 9)
print([(s.lineno, s.end_lineno) for s in tree.body]) # → [(10, 10), (11, 11)]
import ast
tree = ast.parse('x = 1\n1 / 0')
ast.increment_lineno(tree, 9)
try:
exec(compile(tree, 'part.py', 'exec'))
except ZeroDivisionError as e:
print(e.__traceback__.tb_next.tb_lineno) # → 11
See also
Open in the full glossarydocs.python.orgReport an inaccuracy