Skip to content

Commit e45528e

Browse files
committed
Corrected the parent of function type comment nodes
These nodes used to be parented to their original ast.FunctionDef parent but are now correctly parented to their astroid.FunctionDef parent. Closes #851
1 parent 5f67396 commit e45528e

File tree

3 files changed

+22
-4
lines changed

3 files changed

+22
-4
lines changed

ChangeLog

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,13 @@ Release Date: TBA
119119

120120
Close PyCQA/pylint#3904
121121

122+
* Corrected the parent of function type comment nodes.
123+
124+
These nodes used to be parented to their original ast.FunctionDef parent
125+
but are now correctly parented to their astroid.FunctionDef parent.
126+
127+
Close PyCQA/astroid#851
128+
122129

123130
What's New in astroid 2.4.2?
124131
============================

astroid/rebuilder.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,7 @@ def check_type_comment(self, node, parent):
238238

239239
return type_object.value
240240

241-
def check_function_type_comment(self, node):
241+
def check_function_type_comment(self, node, parent):
242242
type_comment = getattr(node, "type_comment", None)
243243
if not type_comment:
244244
return None
@@ -251,10 +251,10 @@ def check_function_type_comment(self, node):
251251

252252
returns = None
253253
argtypes = [
254-
self.visit(elem, node) for elem in (type_comment_ast.argtypes or [])
254+
self.visit(elem, parent) for elem in (type_comment_ast.argtypes or [])
255255
]
256256
if type_comment_ast.returns:
257-
returns = self.visit(type_comment_ast.returns, node)
257+
returns = self.visit(type_comment_ast.returns, parent)
258258

259259
return returns, argtypes
260260

@@ -615,7 +615,7 @@ def _visit_functiondef(self, cls, node, parent):
615615
returns = None
616616

617617
type_comment_args = type_comment_returns = None
618-
type_comment_annotation = self.check_function_type_comment(node)
618+
type_comment_annotation = self.check_function_type_comment(node, newnode)
619619
if type_comment_annotation:
620620
type_comment_returns, type_comment_args = type_comment_annotation
621621
newnode.postinit(

tests/unittest_builder.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -544,6 +544,17 @@ def test_not_implemented(self):
544544
self.assertIsInstance(inferred, nodes.Const)
545545
self.assertEqual(inferred.value, NotImplemented)
546546

547+
def test_correct_function_type_comment_parent(self):
548+
data = """
549+
def f(a):
550+
# type: (A) -> A
551+
pass
552+
"""
553+
astroid = builder.parse(data)
554+
f = astroid.body[0]
555+
self.assertIs(f.type_comment_args[0].parent, f)
556+
self.assertIs(f.type_comment_returns.parent, f)
557+
547558

548559
class FileBuildTest(unittest.TestCase):
549560
def setUp(self):

0 commit comments

Comments
 (0)