Skip to content

Commit 9d97d07

Browse files
[Backport maintenance/4.3.x] Fix crash when inferring Class.__bases__ without a parent (#3326)
Fix crash when inferring Class.__bases__ without a parent (#3319) ClassModel.attr___bases__ returned a Tuple with no parent, so NodeNG.root() raised AssertionError (e.g. pylint stdlib checker on C.__bases__()). Parent the Tuple to the class, matching __mro__. Refs pylint-dev/pylint#11491 (cherry picked from commit 8580761) Co-authored-by: 00200200 <[email protected]>
1 parent 0698518 commit 9d97d07

3 files changed

Lines changed: 24 additions & 1 deletion

File tree

‎astroid/interpreter/objectmodel.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -596,7 +596,7 @@ def infer_call_result(
596596

597597
@property
598598
def attr___bases__(self):
599-
obj = node_classes.Tuple()
599+
obj = node_classes.Tuple(parent=self._instance)
600600
context = InferenceContext()
601601
elts = list(self._instance._inferred_bases(context))
602602
obj.postinit(elts=elts)
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix ``AssertionError`` in ``NodeNG.root()`` when inferring ``Class.__bases__``, which previously returned a parentless ``Tuple``.
2+
3+
Closes pylint-dev/pylint#11491

‎tests/test_object_model.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,8 @@ class C(A): pass
239239
base_nodes = next(ast_nodes[6].infer())
240240
self.assertIsInstance(base_nodes, nodes.Tuple)
241241
self.assertEqual([cls.name for cls in base_nodes.elts], ["object"])
242+
self.assertIsInstance(base_nodes.parent, nodes.ClassDef)
243+
self.assertEqual(base_nodes.root().name, "fake_module")
242244

243245
cls = next(ast_nodes[7].infer())
244246
self.assertIsInstance(cls, nodes.ClassDef)
@@ -251,6 +253,24 @@ class C(A): pass
251253
self.assertIsInstance(subclasses, nodes.List)
252254
self.assertEqual([cls.name for cls in subclasses.elts], ["B", "C"])
253255

256+
def test_class_bases_has_module_root(self) -> None:
257+
"""Regression test for pylint-dev/pylint#11491.
258+
259+
Inferring ``Class.__bases__`` must return a Tuple parented to the class so
260+
callers can safely use ``.root()`` (e.g. pylint's stdlib checker).
261+
"""
262+
node = builder.extract_node("""
263+
class C:
264+
pass
265+
C.__bases__ #@
266+
""")
267+
inferred = next(node.infer())
268+
self.assertIsInstance(inferred, nodes.Tuple)
269+
self.assertIsInstance(inferred.parent, nodes.ClassDef)
270+
self.assertEqual(inferred.parent.name, "C")
271+
# Must not raise AssertionError from NodeNG.root().
272+
self.assertIsInstance(inferred.root(), nodes.Module)
273+
254274

255275
class ModuleModelTest(unittest.TestCase):
256276
def test_priority_to_local_defined_values(self) -> None:

0 commit comments

Comments
 (0)