From 96ca4dc75aacaba4d1f4e9a66a72699c9fc93349 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dani=C3=ABl=20van=20Noord?= <13665637+DanielNoord@users.noreply.github.com> Date: Fri, 19 Nov 2021 08:26:41 +0100 Subject: Add ``InferenceContext`` to ``ClassModel`` (#1257) --- ChangeLog | 4 ++++ astroid/interpreter/objectmodel.py | 8 +++++++- tests/unittest_regrtest.py | 22 +++++++++++++++++++++- 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/ChangeLog b/ChangeLog index db5f5ee9..13cc9b56 100644 --- a/ChangeLog +++ b/ChangeLog @@ -12,6 +12,10 @@ What's New in astroid 2.8.6? ============================ Release date: TBA +* Fix crash on inference of subclasses created from ``Class().__subclasses__`` + + Closes PyCQA/pylint#4982 + * Fix bug with Python 3.7.0 / 3.7.1 and ``typing.NoReturn``. Closes #1239 diff --git a/astroid/interpreter/objectmodel.py b/astroid/interpreter/objectmodel.py index e6133342..8e09f866 100644 --- a/astroid/interpreter/objectmodel.py +++ b/astroid/interpreter/objectmodel.py @@ -403,6 +403,12 @@ class FunctionModel(ObjectModel): class ClassModel(ObjectModel): + def __init__(self): + # Add a context so that inferences called from an instance don't recurse endlessly + self.context = InferenceContext() + + super().__init__() + @property def attr___module__(self): return node_classes.Const(self._instance.root().qname()) @@ -485,7 +491,7 @@ class ClassModel(ObjectModel): classes = [ cls for cls in root.nodes_of_class(scoped_nodes.ClassDef) - if cls != self._instance and cls.is_subtype_of(qname) + if cls != self._instance and cls.is_subtype_of(qname, context=self.context) ] obj = node_classes.List(parent=self._instance) diff --git a/tests/unittest_regrtest.py b/tests/unittest_regrtest.py index f3300411..c7321dc1 100644 --- a/tests/unittest_regrtest.py +++ b/tests/unittest_regrtest.py @@ -24,7 +24,7 @@ import unittest import pytest -from astroid import MANAGER, Instance, nodes, test_utils +from astroid import MANAGER, Instance, nodes, parse, test_utils from astroid.builder import AstroidBuilder, extract_node from astroid.const import PY38_PLUS from astroid.exceptions import InferenceError @@ -379,5 +379,25 @@ def test_crash_in_dunder_inference_prevented() -> None: assert inferred.qname() == "builtins.dict.__delitem__" +def test_regression_crash_classmethod() -> None: + """Regression test for a crash reported in https://github.com/PyCQA/pylint/issues/4982""" + code = """ + class Base: + @classmethod + def get_first_subclass(cls): + for subclass in cls.__subclasses__(): + return subclass + return object + + + subclass = Base.get_first_subclass() + + + class Another(subclass): + pass + """ + parse(code) + + if __name__ == "__main__": unittest.main() -- cgit v1.2.1