]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-99341: Cover type ignore nodes when incrementing line numbers (GH-99422)
authorBatuhan Taskaya <isidentical@gmail.com>
Tue, 22 Nov 2022 10:41:14 +0000 (13:41 +0300)
committerGitHub <noreply@github.com>
Tue, 22 Nov 2022 10:41:14 +0000 (02:41 -0800)
Lib/ast.py
Lib/test/test_ast.py
Misc/NEWS.d/next/Library/2022-11-13-02-06-56.gh-issue-99341.8-OlwB.rst [new file with mode: 0644]

index 1a94e9368c161a07272abba7e767f80efa1b726b..2cbc80a9835aa56d8c793f220e8f46069d35902b 100644 (file)
@@ -237,6 +237,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 (
index b34644118d281532507cec62cc7b797955781972..773fba87632b0a38a7d715bd66531a2013b92ee9 100644 (file)
@@ -1036,6 +1036,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 (file)
index 0000000..451561c
--- /dev/null
@@ -0,0 +1,2 @@
+Fix :func:`ast.increment_lineno` to also cover :class:`ast.TypeIgnore` when
+changing line numbers.