[Python-checkins] bpo-3530: Add advice on when to correctly use fix_missing_locations in the AST docs (GH-17172)

Miss Islington (bot) webhook-mailer at python.org
Sun Jan 12 15:44:38 EST 2020


https://github.com/python/cpython/commit/ef0af30e507a29dae03aae40459b9c44c96f260d
commit: ef0af30e507a29dae03aae40459b9c44c96f260d
branch: 3.8
author: Miss Islington (bot) <31488909+miss-islington at users.noreply.github.com>
committer: GitHub <noreply at github.com>
date: 2020-01-12T12:44:33-08:00
summary:

bpo-3530: Add advice on when to correctly use fix_missing_locations in the AST docs (GH-17172)


Co-authored-by: Pablo Galindo <Pablogsal at gmail.com>
(cherry picked from commit 6680f4a9f5d15ab82b2ab6266c6f917cb78c919a)

Co-authored-by: Batuhan Taşkaya <47358913+isidentical at users.noreply.github.com>

files:
A Misc/NEWS.d/next/Documentation/2019-11-17-11-53-10.bpo-3530.8zFUMc.rst
M Doc/library/ast.rst

diff --git a/Doc/library/ast.rst b/Doc/library/ast.rst
index 92bf8912eb53d..a5dd0e1cc70dd 100644
--- a/Doc/library/ast.rst
+++ b/Doc/library/ast.rst
@@ -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
@@ -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)
diff --git a/Misc/NEWS.d/next/Documentation/2019-11-17-11-53-10.bpo-3530.8zFUMc.rst b/Misc/NEWS.d/next/Documentation/2019-11-17-11-53-10.bpo-3530.8zFUMc.rst
new file mode 100644
index 0000000000000..65f1a6d156a12
--- /dev/null
+++ b/Misc/NEWS.d/next/Documentation/2019-11-17-11-53-10.bpo-3530.8zFUMc.rst
@@ -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.



More information about the Python-checkins mailing list