summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDaniƫl van Noord <13665637+DanielNoord@users.noreply.github.com>2022-07-03 18:15:51 +0200
committerGitHub <noreply@github.com>2022-07-03 18:15:51 +0200
commita6fdf0b92af0190dfc8334a69548919cc7130204 (patch)
treec33a18d2a6708573c974741d132cfb5804d7e667
parentdd80a68fc93d507c3a8182ea5b94f6cbe0e348a7 (diff)
downloadastroid-git-a6fdf0b92af0190dfc8334a69548919cc7130204.tar.gz
Add ``__new__`` and ``__call__`` to``ObjectModel`` and ``ClassModel`` (#1606)
-rw-r--r--ChangeLog2
-rw-r--r--astroid/bases.py22
-rw-r--r--astroid/interpreter/objectmodel.py19
-rw-r--r--astroid/nodes/scoped_nodes/scoped_nodes.py18
-rw-r--r--tests/unittest_objects.py18
5 files changed, 62 insertions, 17 deletions
diff --git a/ChangeLog b/ChangeLog
index 85dd9c85..07b42539 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -67,6 +67,8 @@ Release date: TBA
* Rename ``ModuleSpec`` -> ``module_type`` constructor parameter to match attribute
name and improve typing. Use ``type`` instead.
+* ``ObjectModel`` and ``ClassModel`` now know about their ``__new__`` and ``__call__`` attributes.
+
* Fixed pylint ``not-callable`` false positive with nested-tuple assignment in a for-loop.
Refs PyCQA/pylint#5113
diff --git a/astroid/bases.py b/astroid/bases.py
index c1607260..8ac03505 100644
--- a/astroid/bases.py
+++ b/astroid/bases.py
@@ -10,9 +10,9 @@ from __future__ import annotations
import collections
import collections.abc
from collections.abc import Sequence
-from typing import TYPE_CHECKING, Any
+from typing import Any
-from astroid import decorators
+from astroid import decorators, nodes
from astroid.const import PY310_PLUS
from astroid.context import (
CallContext,
@@ -33,9 +33,6 @@ objectmodel = lazy_import("interpreter.objectmodel")
helpers = lazy_import("helpers")
manager = lazy_import("manager")
-if TYPE_CHECKING:
- from astroid import nodes
-
# TODO: check if needs special treatment
BOOL_SPECIAL_METHOD = "__bool__"
@@ -271,10 +268,20 @@ class BaseInstance(Proxy):
else:
yield attr
- def infer_call_result(self, caller, context=None):
+ def infer_call_result(
+ self, caller: nodes.Call | Proxy, context: InferenceContext | None = None
+ ):
"""infer what a class instance is returning when called"""
context = bind_context_to_node(context, self)
inferred = False
+
+ # If the call is an attribute on the instance, we infer the attribute itself
+ if isinstance(caller, nodes.Call) and isinstance(caller.func, nodes.Attribute):
+ for res in self.igetattr(caller.func.attrname, context):
+ inferred = True
+ yield res
+
+ # Otherwise we infer the call to the __call__ dunder normally
for node in self._proxied.igetattr("__call__", context):
if node is Uninferable or not node.callable():
continue
@@ -418,9 +425,6 @@ class UnboundMethod(Proxy):
) -> collections.abc.Generator[
nodes.Const | Instance | type[Uninferable], None, None
]:
- # pylint: disable-next=import-outside-toplevel; circular import
- from astroid import nodes
-
if not caller.args:
return
# Attempt to create a constant
diff --git a/astroid/interpreter/objectmodel.py b/astroid/interpreter/objectmodel.py
index 90085d7d..d120895a 100644
--- a/astroid/interpreter/objectmodel.py
+++ b/astroid/interpreter/objectmodel.py
@@ -118,6 +118,19 @@ class ObjectModel:
return getattr(self, IMPL_PREFIX + name)
raise AttributeInferenceError(target=self._instance, attribute=name)
+ @property
+ def attr___new__(self):
+ """Calling cls.__new__(cls) on an object returns an instance of that object.
+
+ Instance is either an instance or a class definition of the instance to be
+ created.
+ """
+ # TODO: Use isinstance instead of try ... except after _instance has typing
+ try:
+ return self._instance._proxied.instantiate_class()
+ except AttributeError:
+ return self._instance.instantiate_class()
+
class ModuleModel(ObjectModel):
def _builtins(self):
@@ -389,7 +402,6 @@ class FunctionModel(ObjectModel):
attr___repr__ = attr___ne__
attr___reduce__ = attr___ne__
attr___reduce_ex__ = attr___ne__
- attr___new__ = attr___ne__
attr___lt__ = attr___ne__
attr___eq__ = attr___ne__
attr___gt__ = attr___ne__
@@ -512,6 +524,11 @@ class ClassModel(ObjectModel):
def attr___dict__(self):
return node_classes.Dict(parent=self._instance)
+ @property
+ def attr___call__(self):
+ """Calling a class A() returns an instance of A."""
+ return self._instance.instantiate_class()
+
class SuperModel(ObjectModel):
@property
diff --git a/astroid/nodes/scoped_nodes/scoped_nodes.py b/astroid/nodes/scoped_nodes/scoped_nodes.py
index 8ccb2d35..f6cfed68 100644
--- a/astroid/nodes/scoped_nodes/scoped_nodes.py
+++ b/astroid/nodes/scoped_nodes/scoped_nodes.py
@@ -2298,7 +2298,12 @@ class ClassDef(
try:
metaclass = self.metaclass(context=context)
if metaclass is not None:
- dunder_call = next(metaclass.igetattr("__call__", context))
+ # Only get __call__ if it's defined locally for the metaclass.
+ # Otherwise we will find ObjectModel.__call__ which will
+ # return an instance of the metaclass. Instantiating the class is
+ # handled later.
+ if "__call__" in metaclass.locals:
+ dunder_call = next(metaclass.igetattr("__call__", context))
except (AttributeInferenceError, StopIteration):
pass
@@ -2550,7 +2555,11 @@ class ClassDef(
if not name:
raise AttributeInferenceError(target=self, attribute=name, context=context)
- values = self.locals.get(name, [])
+ # don't modify the list in self.locals!
+ values = list(self.locals.get(name, []))
+ for classnode in self.ancestors(recurs=True, context=context):
+ values += classnode.locals.get(name, [])
+
if name in self.special_attributes and class_context and not values:
result = [self.special_attributes.lookup(name)]
if name == "__bases__":
@@ -2559,11 +2568,6 @@ class ClassDef(
result += values
return result
- # don't modify the list in self.locals!
- values = list(values)
- for classnode in self.ancestors(recurs=True, context=context):
- values += classnode.locals.get(name, [])
-
if class_context:
values += self._metaclass_lookup_attribute(name, context)
diff --git a/tests/unittest_objects.py b/tests/unittest_objects.py
index 1b8f3119..ff6963b2 100644
--- a/tests/unittest_objects.py
+++ b/tests/unittest_objects.py
@@ -32,6 +32,24 @@ class ObjectsTest(unittest.TestCase):
self.assertEqual(inferred.qname(), "builtins.frozenset")
self.assertIsInstance(proxied, nodes.ClassDef)
+ def test_lookup_regression_slots(self) -> None:
+ """Regression test for attr__new__ of ObjectModel.
+
+ ObjectModel._instance is not always an bases.Instance, so we can't
+ rely on the ._proxied attribute of an Instance.
+ """
+
+ node = builder.extract_node(
+ """
+ class ClassHavingUnknownAncestors(Unknown):
+ __slots__ = ["yo"]
+
+ def test(self):
+ self.not_yo = 42
+ """
+ )
+ assert node.getattr("__new__")
+
class SuperTests(unittest.TestCase):
def test_inferring_super_outside_methods(self) -> None: