Python Glossary Русский

all Python 3astfunction

ast.copy_location()

helper functions

Copies the position (lineno, col_offset and the end positions) from an old node to a new one and returns the new node. Used when replacing one node with another.

Syntax

new_node = ast.copy_location(new_node, old_node)

It copies only the node's own position, not its children: nested new nodes stay without lineno, so fix_missing_locations is still needed after the replacement. In return, tracebacks of the compiled code point to the original node's line rather than the parent's. The usual idiom in a transformer is return ast.copy_location(new, node).

Examples

import ast
tree = ast.parse('x = 1 + 2')
old = tree.body[0].value
new = ast.copy_location(ast.Constant(value=3), old)
print(new.lineno, new.col_offset, new.end_col_offset)  # → 1 4 9
tree.body[0].value = new
print(ast.unparse(tree))  # → x = 3

See also

Open in the full glossarydocs.python.orgReport an inaccuracy