summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorClaudiu Popa <pcmanticore@gmail.com>2019-11-28 09:55:05 +0100
committerClaudiu Popa <pcmanticore@gmail.com>2019-12-04 13:31:38 +0100
commit55b43f6755d4839cefaf010eb2ced747d014d459 (patch)
tree423bce7071ee07f5e3ffb9d983b38296f5c9acc2
parent4952320cda79c79f6868e4fb59f09e188cd9cafc (diff)
downloadastroid-git-55b43f6755d4839cefaf010eb2ced747d014d459.tar.gz
Add support for inferring properties
These new capabilities will allow inferring both the `property` builtin as well as property attributes such as `.deleter` and `.setter`.
-rw-r--r--ChangeLog2
-rw-r--r--astroid/bases.py11
-rw-r--r--astroid/brain/brain_builtin_inference.py30
-rw-r--r--astroid/inference.py39
-rw-r--r--astroid/interpreter/objectmodel.py45
-rw-r--r--astroid/objects.py26
-rw-r--r--astroid/protocols.py2
-rw-r--r--astroid/scoped_nodes.py32
-rw-r--r--tests/unittest_inference.py62
-rw-r--r--tests/unittest_regrtest.py2
-rw-r--r--tests/unittest_scoped_nodes.py4
11 files changed, 233 insertions, 22 deletions
diff --git a/ChangeLog b/ChangeLog
index b1b533a5..1f63044c 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -12,6 +12,8 @@ Release Date: TBA
* Added transform for ``scipy.gaussian``
+* Add suport for inferring properties.
+
* Added a brain for ``responses``
* Allow inferring positional only arguments.
diff --git a/astroid/bases.py b/astroid/bases.py
index 27bb803f..0c6cb9b2 100644
--- a/astroid/bases.py
+++ b/astroid/bases.py
@@ -58,13 +58,12 @@ POSSIBLE_PROPERTIES = {
}
-def _is_property(meth):
- if PROPERTIES.intersection(meth.decoratornames()):
+def _is_property(meth, context=None):
+ decoratornames = meth.decoratornames(context=context)
+ if PROPERTIES.intersection(decoratornames):
return True
stripped = {
- name.split(".")[-1]
- for name in meth.decoratornames()
- if name is not util.Uninferable
+ name.split(".")[-1] for name in decoratornames if name is not util.Uninferable
}
if any(name in stripped for name in POSSIBLE_PROPERTIES):
return True
@@ -73,7 +72,7 @@ def _is_property(meth):
if not meth.decorators:
return False
for decorator in meth.decorators.nodes or ():
- inferred = helpers.safe_infer(decorator)
+ inferred = helpers.safe_infer(decorator, context=context)
if inferred is None or inferred is util.Uninferable:
continue
if inferred.__class__.__name__ == "ClassDef":
diff --git a/astroid/brain/brain_builtin_inference.py b/astroid/brain/brain_builtin_inference.py
index 2dd7cc54..a74d01fe 100644
--- a/astroid/brain/brain_builtin_inference.py
+++ b/astroid/brain/brain_builtin_inference.py
@@ -478,6 +478,35 @@ def infer_callable(node, context=None):
return nodes.Const(inferred.callable())
+def infer_property(node, context=None):
+ """Understand `property` class
+
+ This only infers the output of `property`
+ call, not the arguments themselves.
+ """
+ if len(node.args) < 1:
+ # Invalid property call.
+ raise UseInferenceDefault
+
+ getter = node.args[0]
+ try:
+ inferred = next(getter.infer(context=context))
+ except InferenceError:
+ raise UseInferenceDefault
+
+ if not isinstance(inferred, (nodes.FunctionDef, nodes.Lambda)):
+ raise UseInferenceDefault
+
+ return objects.Property(
+ function=inferred,
+ name=inferred.name,
+ doc=getattr(inferred, "doc", None),
+ lineno=node.lineno,
+ parent=node,
+ col_offset=node.col_offset,
+ )
+
+
def infer_bool(node, context=None):
"""Understand bool calls."""
if len(node.args) > 1:
@@ -804,6 +833,7 @@ def infer_dict_fromkeys(node, context=None):
register_builtin_transform(infer_bool, "bool")
register_builtin_transform(infer_super, "super")
register_builtin_transform(infer_callable, "callable")
+register_builtin_transform(infer_property, "property")
register_builtin_transform(infer_getattr, "getattr")
register_builtin_transform(infer_hasattr, "hasattr")
register_builtin_transform(infer_tuple, "tuple")
diff --git a/astroid/inference.py b/astroid/inference.py
index 77c6b1d0..64e79df7 100644
--- a/astroid/inference.py
+++ b/astroid/inference.py
@@ -38,22 +38,24 @@ from astroid import util
MANAGER = manager.AstroidManager()
+# Prevents circular imports
+objects = util.lazy_import("objects")
# .infer method ###############################################################
def infer_end(self, context=None):
- """inference's end for node such as Module, ClassDef, FunctionDef,
- Const...
+ """Inference's end for nodes that yield themselves on inference
+ These are objects for which inference does not have any semantic,
+ such as Module or Consts.
"""
yield self
nodes.Module._infer = infer_end
nodes.ClassDef._infer = infer_end
-nodes.FunctionDef._infer = infer_end
nodes.Lambda._infer = infer_end
nodes.Const._infer = infer_end
nodes.Slice._infer = infer_end
@@ -309,11 +311,13 @@ def infer_attribute(self, context=None):
try:
context.boundnode = owner
yield from owner.igetattr(self.attrname, context)
- context.boundnode = None
- except (exceptions.AttributeInferenceError, exceptions.InferenceError):
- context.boundnode = None
- except AttributeError:
- # XXX method / function
+ except (
+ exceptions.AttributeInferenceError,
+ exceptions.InferenceError,
+ AttributeError,
+ ):
+ pass
+ finally:
context.boundnode = None
return dict(node=self, context=context)
@@ -941,3 +945,22 @@ def infer_ifexp(self, context=None):
nodes.IfExp._infer = infer_ifexp
+
+
+def infer_functiondef(self, context=None):
+ if not self.decorators or not bases._is_property(self):
+ yield self
+ return
+
+ prop_func = objects.Property(
+ function=self,
+ name=self.name,
+ doc=self.doc,
+ lineno=self.lineno,
+ parent=self.parent,
+ col_offset=self.col_offset,
+ )
+ yield prop_func
+
+
+nodes.FunctionDef._infer = infer_functiondef
diff --git a/astroid/interpreter/objectmodel.py b/astroid/interpreter/objectmodel.py
index f37ae973..c7b5c16d 100644
--- a/astroid/interpreter/objectmodel.py
+++ b/astroid/interpreter/objectmodel.py
@@ -735,3 +735,48 @@ class DictModel(ObjectModel):
obj = objects.DictValues(obj)
return self._generic_dict_attribute(obj, "values")
+
+
+class PropertyModel(ObjectModel):
+ """Model for a builtin property"""
+
+ # pylint: disable=import-outside-toplevel
+ @property
+ def attr_fget(self):
+ from astroid.scoped_nodes import FunctionDef
+
+ func = self._instance
+
+ class PropertyFuncAccessor(FunctionDef):
+ def infer_call_result(self, caller=None, context=None):
+ nonlocal func
+ if caller and len(caller.args) != 1:
+ raise exceptions.InferenceError(
+ "fget() needs a single argument", target=self, context=context
+ )
+
+ yield from func.function.infer_call_result(
+ caller=caller, context=context
+ )
+
+ return PropertyFuncAccessor(name="fget", parent=self._instance)
+
+ @property
+ def attr_setter(self):
+ from astroid.scoped_nodes import FunctionDef
+
+ return FunctionDef(name="setter", parent=self._instance)
+
+ @property
+ def attr_deleter(self):
+ from astroid.scoped_nodes import FunctionDef
+
+ return FunctionDef(name="deleter", parent=self._instance)
+
+ @property
+ def attr_getter(self):
+ from astroid.scoped_nodes import FunctionDef
+
+ return FunctionDef(name="getter", parent=self._instance)
+
+ # pylint: enable=import-outside-toplevel
diff --git a/astroid/objects.py b/astroid/objects.py
index 888ca36e..93c5f406 100644
--- a/astroid/objects.py
+++ b/astroid/objects.py
@@ -184,6 +184,9 @@ class Super(node_classes.NodeNG):
yield inferred
elif self._class_based or inferred.type == "staticmethod":
yield inferred
+ elif isinstance(inferred, Property):
+ function = inferred.function
+ yield from function.infer_call_result(caller=self, context=context)
elif bases._is_property(inferred):
# TODO: support other descriptors as well.
try:
@@ -280,3 +283,26 @@ class PartialFunction(scoped_nodes.FunctionDef):
# TODO: Hack to solve the circular import problem between node_classes and objects
# This is not needed in 2.0, which has a cleaner design overall
node_classes.Dict.__bases__ = (node_classes.NodeNG, DictInstance)
+
+
+class Property(scoped_nodes.FunctionDef):
+ """Class representing a Python property"""
+
+ def __init__(
+ self, function, name=None, doc=None, lineno=None, col_offset=None, parent=None
+ ):
+ super().__init__(name, doc, lineno, col_offset, parent)
+ self.function = function
+
+ # pylint: disable=unnecessary-lambda
+ special_attributes = util.lazy_descriptor(lambda: objectmodel.PropertyModel())
+ type = "property"
+
+ def pytype(self):
+ return "%s.property" % BUILTINS
+
+ def infer_call_result(self, caller=None, context=None):
+ raise exceptions.InferenceError("Properties are not callable")
+
+ def infer(self, context=None, **kwargs):
+ return iter((self,))
diff --git a/astroid/protocols.py b/astroid/protocols.py
index bd1fede1..09301511 100644
--- a/astroid/protocols.py
+++ b/astroid/protocols.py
@@ -464,7 +464,7 @@ def _infer_context_manager(self, mgr, context):
)
for decorator_node in func.decorators.nodes:
- decorator = next(decorator_node.infer(context))
+ decorator = next(decorator_node.infer(context=context))
if isinstance(decorator, nodes.FunctionDef):
if decorator.qname() == _CONTEXTLIB_MGR:
break
diff --git a/astroid/scoped_nodes.py b/astroid/scoped_nodes.py
index e2f79481..440984e4 100644
--- a/astroid/scoped_nodes.py
+++ b/astroid/scoped_nodes.py
@@ -114,6 +114,8 @@ def function_to_method(n, klass):
if isinstance(n, FunctionDef):
if n.type == "classmethod":
return bases.BoundMethod(n, klass)
+ if n.type == "property":
+ return n
if n.type != "staticmethod":
return bases.UnboundMethod(n)
return n
@@ -1550,9 +1552,11 @@ class FunctionDef(mixins.MultiLineBlockMixin, node_classes.Statement, Lambda):
return self.type != "function" and isinstance(self.parent.frame(), ClassDef)
@decorators_mod.cached
- def decoratornames(self):
+ def decoratornames(self, context=None):
"""Get the qualified names of each of the decorators on this function.
+ :param context:
+ An inference context that can be passed to inference functions
:returns: The names of the decorators.
:rtype: set(str)
"""
@@ -1563,7 +1567,7 @@ class FunctionDef(mixins.MultiLineBlockMixin, node_classes.Statement, Lambda):
decoratornodes += self.extra_decorators
for decnode in decoratornodes:
try:
- for infnode in decnode.infer():
+ for infnode in decnode.infer(context=context):
result.add(infnode.qname())
except exceptions.InferenceError:
continue
@@ -2431,8 +2435,8 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement
yield attr
continue
- if bases._is_property(attr):
- yield from attr.infer_call_result(self, context)
+ if isinstance(attr, objects.Property):
+ yield attr
continue
if attr.type == "classmethod":
# If the method is a classmethod, then it will
@@ -2460,6 +2464,8 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement
# instance
context = contextmod.copy_context(context)
context.lookupname = name
+
+ metaclass = self.declared_metaclass(context=context)
try:
attr = self.getattr(name, context, class_context=class_context)[0]
for inferred in bases._infer_stmts([attr], context, frame=self):
@@ -2473,6 +2479,24 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement
yield inferred
else:
yield util.Uninferable
+ elif isinstance(inferred, objects.Property):
+ function = inferred.function
+ if not class_context:
+ # Through an instance so we can solve the property
+ yield from function.infer_call_result(
+ caller=self, context=context
+ )
+ else:
+ # If we have a metaclass, we're accessing this attribute through
+ # the class itself, which means we can solve the property
+ if metaclass:
+ # Resolve a property as long as it is not accessed through
+ # the class itself.
+ yield from function.infer_call_result(
+ caller=self, context=context
+ )
+ else:
+ yield inferred
else:
yield function_to_method(inferred, self)
except exceptions.AttributeInferenceError as error:
diff --git a/tests/unittest_inference.py b/tests/unittest_inference.py
index 7d0e10b9..df0ea200 100644
--- a/tests/unittest_inference.py
+++ b/tests/unittest_inference.py
@@ -5422,5 +5422,67 @@ def test_inference_is_limited_to_the_boundnode(code, instance_name):
assert inferred.name == instance_name
+def test_property_inference():
+ code = """
+ class A:
+ @property
+ def test(self):
+ return 42
+
+ A.test #@
+ A().test #@
+ A.test.fget(A) #@
+ A.test.setter #@
+ A.test.getter #@
+ A.test.deleter #@
+ """
+ prop, prop_result, prop_fget_result, prop_setter, prop_getter, prop_deleter = extract_node(
+ code
+ )
+
+ inferred = next(prop.infer())
+ assert isinstance(inferred, objects.Property)
+ assert inferred.pytype() == "builtins.property"
+ assert inferred.type == "property"
+
+ inferred = next(prop_result.infer())
+ print(prop_result.as_string())
+ assert isinstance(inferred, nodes.Const)
+ assert inferred.value == 42
+
+ inferred = next(prop_fget_result.infer())
+ assert isinstance(inferred, nodes.Const)
+ assert inferred.value == 42
+
+ for prop_func in prop_setter, prop_getter, prop_deleter:
+ inferred = next(prop_func.infer())
+ assert isinstance(inferred, nodes.FunctionDef)
+
+
+def test_property_callable_inference():
+ code = """
+ class A:
+ def func(self):
+ return 42
+ p = property(func)
+ A().p
+ """
+ property_call = extract_node(code)
+ inferred = next(property_call.infer())
+ assert isinstance(inferred, nodes.Const)
+ assert inferred.value == 42
+
+ # Try with lambda as well
+ code = """
+ class A:
+ p = property(lambda self: 42)
+ A().p
+ """
+ property_call = extract_node(code)
+ inferred = next(property_call.infer())
+ assert isinstance(inferred, nodes.Const)
+ assert inferred.value == 42
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/unittest_regrtest.py b/tests/unittest_regrtest.py
index 317a0567..8224494b 100644
--- a/tests/unittest_regrtest.py
+++ b/tests/unittest_regrtest.py
@@ -273,7 +273,7 @@ def test():
"""
)
inferred = next(node.infer())
- self.assertEqual(inferred.decoratornames(), set())
+ self.assertEqual(inferred.decoratornames(), {".Parent.foo.getter"})
def test_ssl_protocol(self):
node = extract_node(
diff --git a/tests/unittest_scoped_nodes.py b/tests/unittest_scoped_nodes.py
index 17f609d7..d70b7351 100644
--- a/tests/unittest_scoped_nodes.py
+++ b/tests/unittest_scoped_nodes.py
@@ -29,7 +29,7 @@ from functools import partial
import unittest
import pytest
-from astroid import builder
+from astroid import builder, objects
from astroid import nodes
from astroid import scoped_nodes
from astroid import util
@@ -1730,7 +1730,7 @@ class ClassNodeTest(ModuleLoader, unittest.TestCase):
# from the class that uses the metaclass, the value
# of the property
property_meta = next(module["Metaclass"].igetattr("meta_property"))
- self.assertIsInstance(property_meta, UnboundMethod)
+ self.assertIsInstance(property_meta, objects.Property)
wrapping = scoped_nodes.get_wrapping_class(property_meta)
self.assertEqual(wrapping, module["Metaclass"])