Skip to content

bpo-3530: Use fix_missing_locations when node transformer adds nodes #17172

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jan 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion Doc/library/ast.rst
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ and classes for traversing abstract syntax trees:
class RewriteName(NodeTransformer):

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

If :class:`NodeTransformer` introduces new nodes (that weren't part of
original tree) without giving them location information (such as
:attr:`lineno`), :func:`fix_missing_locations` should be called with
the new sub-tree to recalculate the location information::

tree = ast.parse('foo', mode='eval')
new_tree = fix_missing_locations(RewriteName().visit(tree))

Usually you use the transformer like this::

node = YourTransformer().visit(node)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
In the :mod:`ast` module documentation, fix a misleading ``NodeTransformer`` example and add
advice on when to use the ``fix_missing_locations`` function.