Skip to content

Commit 6680f4a

Browse files
bpo-3530: Add advice on when to correctly use fix_missing_locations in the AST docs (GH-17172)
Co-authored-by: Pablo Galindo <[email protected]>
1 parent 9f3fc6c commit 6680f4a

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

Doc/library/ast.rst

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -316,7 +316,7 @@ and classes for traversing abstract syntax trees:
316316
class RewriteName(NodeTransformer):
317317

318318
def visit_Name(self, node):
319-
return copy_location(Subscript(
319+
return Subscript(
320320
value=Name(id='data', ctx=Load()),
321321
slice=Index(value=Constant(value=node.id)),
322322
ctx=node.ctx
@@ -330,6 +330,14 @@ and classes for traversing abstract syntax trees:
330330
statement nodes), the visitor may also return a list of nodes rather than
331331
just a single node.
332332

333+
If :class:`NodeTransformer` introduces new nodes (that weren't part of
334+
original tree) without giving them location information (such as
335+
:attr:`lineno`), :func:`fix_missing_locations` should be called with
336+
the new sub-tree to recalculate the location information::
337+
338+
tree = ast.parse('foo', mode='eval')
339+
new_tree = fix_missing_locations(RewriteName().visit(tree))
340+
333341
Usually you use the transformer like this::
334342

335343
node = YourTransformer().visit(node)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
In the :mod:`ast` module documentation, fix a misleading ``NodeTransformer`` example and add
2+
advice on when to use the ``fix_missing_locations`` function.

0 commit comments

Comments
 (0)