Skip to content

[3.11] gh-99341: Cover type ignore nodes when incrementing line numbers (GH-99422) #99683

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 1 commit into from
Nov 22, 2022
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
6 changes: 6 additions & 0 deletions Lib/ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
12 changes: 12 additions & 0 deletions Lib/test/test_ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -1026,6 +1026,18 @@ def test_increment_lineno(self):
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))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix :func:`ast.increment_lineno` to also cover :class:`ast.TypeIgnore` when
changing line numbers.