aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>2022-11-22 03:03:26 -0800
committerGitHub <noreply@github.com>2022-11-22 03:03:26 -0800
commit85dbd2d767418799c5238e4a16a6afcdf7dcaf46 (patch)
treeffbd9fb9f7ed781385e317325a5c2864bed9396d
parentgh-99659: Use correct exceptions in sqlite3 bigmem tests (GH-99660) (diff)
downloadcpython-85dbd2d767418799c5238e4a16a6afcdf7dcaf46.tar.gz
cpython-85dbd2d767418799c5238e4a16a6afcdf7dcaf46.tar.bz2
cpython-85dbd2d767418799c5238e4a16a6afcdf7dcaf46.zip
gh-99341: Cover type ignore nodes when incrementing line numbers (GH-99422)
(cherry picked from commit 1acdfec359fdf3db936168480be0f4157273c200) Co-authored-by: Batuhan Taskaya <isidentical@gmail.com>
-rw-r--r--Lib/ast.py6
-rw-r--r--Lib/test/test_ast.py12
-rw-r--r--Misc/NEWS.d/next/Library/2022-11-13-02-06-56.gh-issue-99341.8-OlwB.rst2
3 files changed, 20 insertions, 0 deletions
diff --git a/Lib/ast.py b/Lib/ast.py
index 8c10d080022..623b9a1b805 100644
--- a/Lib/ast.py
+++ b/Lib/ast.py
@@ -236,6 +236,12 @@ def increment_lineno(node, n=1):
location in a file.
"""
for child in walk(node):
+ # TypeIgnore is a special case where lineno is not an attribute
+ # but rather a field of the node itself.
+ if isinstance(child, TypeIgnore):
+ child.lineno = getattr(child, 'lineno', 0) + n
+ continue
+
if 'lineno' in child._attributes:
child.lineno = getattr(child, 'lineno', 0) + n
if (
diff --git a/Lib/test/test_ast.py b/Lib/test/test_ast.py
index 90ad6af56fd..7581adc8fc2 100644
--- a/Lib/test/test_ast.py
+++ b/Lib/test/test_ast.py
@@ -1026,6 +1026,18 @@ Module(
self.assertEqual(ast.increment_lineno(src).lineno, 2)
self.assertIsNone(ast.increment_lineno(src).end_lineno)
+ def test_increment_lineno_on_module(self):
+ src = ast.parse(dedent("""\
+ a = 1
+ b = 2 # type: ignore
+ c = 3
+ d = 4 # type: ignore@tag
+ """), type_comments=True)
+ ast.increment_lineno(src, n=5)
+ self.assertEqual(src.type_ignores[0].lineno, 7)
+ self.assertEqual(src.type_ignores[1].lineno, 9)
+ self.assertEqual(src.type_ignores[1].tag, '@tag')
+
def test_iter_fields(self):
node = ast.parse('foo()', mode='eval')
d = dict(ast.iter_fields(node.body))
diff --git a/Misc/NEWS.d/next/Library/2022-11-13-02-06-56.gh-issue-99341.8-OlwB.rst b/Misc/NEWS.d/next/Library/2022-11-13-02-06-56.gh-issue-99341.8-OlwB.rst
new file mode 100644
index 00000000000..451561c579d
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2022-11-13-02-06-56.gh-issue-99341.8-OlwB.rst
@@ -0,0 +1,2 @@
+Fix :func:`ast.increment_lineno` to also cover :class:`ast.TypeIgnore` when
+changing line numbers.