Skip to content

Commit e222b4c

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]> (cherry picked from commit 6680f4a) Co-authored-by: Batuhan Taşkaya <[email protected]>
1 parent 4be9726 commit e222b4c

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
@@ -240,7 +240,7 @@ and classes for traversing abstract syntax trees:
240240
class RewriteName(NodeTransformer):
241241

242242
def visit_Name(self, node):
243-
return copy_location(Subscript(
243+
return Subscript(
244244
value=Name(id='data', ctx=Load()),
245245
slice=Index(value=Str(s=node.id)),
246246
ctx=node.ctx
@@ -254,6 +254,14 @@ and classes for traversing abstract syntax trees:
254254
statement nodes), the visitor may also return a list of nodes rather than
255255
just a single node.
256256

257+
If :class:`NodeTransformer` introduces new nodes (that weren't part of
258+
original tree) without giving them location information (such as
259+
:attr:`lineno`), :func:`fix_missing_locations` should be called with
260+
the new sub-tree to recalculate the location information::
261+
262+
tree = ast.parse('foo', mode='eval')
263+
new_tree = fix_missing_locations(RewriteName().visit(tree))
264+
257265
Usually you use the transformer like this::
258266

259267
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)