Skip to content

Commit 85dbd2d

Browse files
gh-99341: Cover type ignore nodes when incrementing line numbers (GH-99422)
(cherry picked from commit 1acdfec) Co-authored-by: Batuhan Taskaya <[email protected]>
1 parent e26aa24 commit 85dbd2d

File tree

3 files changed

+20
-0
lines changed

3 files changed

+20
-0
lines changed

Lib/ast.py

+6
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,12 @@ def increment_lineno(node, n=1):
236236
location in a file.
237237
"""
238238
for child in walk(node):
239+
# TypeIgnore is a special case where lineno is not an attribute
240+
# but rather a field of the node itself.
241+
if isinstance(child, TypeIgnore):
242+
child.lineno = getattr(child, 'lineno', 0) + n
243+
continue
244+
239245
if 'lineno' in child._attributes:
240246
child.lineno = getattr(child, 'lineno', 0) + n
241247
if (

Lib/test/test_ast.py

+12
Original file line numberDiff line numberDiff line change
@@ -1026,6 +1026,18 @@ def test_increment_lineno(self):
10261026
self.assertEqual(ast.increment_lineno(src).lineno, 2)
10271027
self.assertIsNone(ast.increment_lineno(src).end_lineno)
10281028

1029+
def test_increment_lineno_on_module(self):
1030+
src = ast.parse(dedent("""\
1031+
a = 1
1032+
b = 2 # type: ignore
1033+
c = 3
1034+
d = 4 # type: ignore@tag
1035+
"""), type_comments=True)
1036+
ast.increment_lineno(src, n=5)
1037+
self.assertEqual(src.type_ignores[0].lineno, 7)
1038+
self.assertEqual(src.type_ignores[1].lineno, 9)
1039+
self.assertEqual(src.type_ignores[1].tag, '@tag')
1040+
10291041
def test_iter_fields(self):
10301042
node = ast.parse('foo()', mode='eval')
10311043
d = dict(ast.iter_fields(node.body))
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix :func:`ast.increment_lineno` to also cover :class:`ast.TypeIgnore` when
2+
changing line numbers.

0 commit comments

Comments
 (0)