summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBryce Guinta <bryce.paul.guinta@gmail.com>2018-06-20 21:59:47 -0600
committerBryce Guinta <bryce.guinta@protonmail.com>2018-07-05 23:17:06 -0600
commitaea774e9554877871045f7f5d0a2f6e063a7c756 (patch)
tree4da5ffea7c605082a54874fdb685256bd3bd4ca5
parent904734c383be4a7e11c8ed16e130d0dff5f56526 (diff)
downloadastroid-git-aea774e9554877871045f7f5d0a2f6e063a7c756.tar.gz
Fix inference for nested calls
Add context_lookup to the context class as extra_context. Deliver the correct context with the correct boundnode for function argument nodes. Close #177
-rw-r--r--ChangeLog2
-rw-r--r--astroid/arguments.py10
-rw-r--r--astroid/bases.py17
-rw-r--r--astroid/brain/brain_functools.py7
-rw-r--r--astroid/context.py10
-rw-r--r--astroid/inference.py6
-rw-r--r--astroid/interpreter/objectmodel.py8
-rw-r--r--astroid/node_classes.py2
-rw-r--r--astroid/protocols.py3
-rw-r--r--astroid/scoped_nodes.py8
-rw-r--r--astroid/tests/unittest_inference.py36
11 files changed, 78 insertions, 31 deletions
diff --git a/ChangeLog b/ChangeLog
index 53359eb0..cd4d76ee 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -216,6 +216,8 @@ Release Date: 2017-12-15
Close PyCQA/pylint#1530
+ * Fix inference for nested calls
+
* Dunder class at method level is now inferred as the class of the method
Close PyCQA/pylint#1328
diff --git a/astroid/arguments.py b/astroid/arguments.py
index ebf581d6..08620644 100644
--- a/astroid/arguments.py
+++ b/astroid/arguments.py
@@ -22,7 +22,10 @@ class CallSite:
and the argument name.
"""
- def __init__(self, callcontext):
+ def __init__(self, callcontext, argument_context_map=None):
+ if argument_context_map is None:
+ argument_context_map = {}
+ self.argument_context_map = argument_context_map
args = callcontext.args
keywords = callcontext.keywords
self.duplicated_keywords = set()
@@ -68,6 +71,7 @@ class CallSite:
def _unpack_keywords(self, keywords):
values = {}
context = contextmod.InferenceContext()
+ context.extra_context = self.argument_context_map
for name, value in keywords:
if name is None:
# Then it's an unpacking operation (**)
@@ -104,10 +108,10 @@ class CallSite:
values[name] = value
return values
- @staticmethod
- def _unpack_args(args):
+ def _unpack_args(self, args):
values = []
context = contextmod.InferenceContext()
+ context.extra_context = self.argument_context_map
for arg in args:
if isinstance(arg, nodes.Starred):
try:
diff --git a/astroid/bases.py b/astroid/bases.py
index 800e048c..4401c8a2 100644
--- a/astroid/bases.py
+++ b/astroid/bases.py
@@ -226,7 +226,7 @@ class BaseInstance(Proxy):
else:
yield attr
- def infer_call_result(self, caller, context=None, context_lookup=None):
+ def infer_call_result(self, caller, context=None):
"""infer what a class instance is returning when called"""
context = contextmod.bind_context_to_node(context, self)
inferred = False
@@ -328,11 +328,8 @@ class UnboundMethod(Proxy):
return iter((self.special_attributes.lookup(name), ))
return self._proxied.igetattr(name, context)
- def infer_call_result(self, caller, context, context_lookup=None):
+ def infer_call_result(self, caller, context):
"""
- The context_lookup argument is used to correctly infer
- arguments to object.__new__(cls) calls inside classmethods
-
The boundnode of the regular context with a function called
on ``object.__new__`` will be of type ``object``,
which is incorrect for the argument in general.
@@ -347,14 +344,12 @@ class UnboundMethod(Proxy):
if (self._proxied.name == '__new__' and
self._proxied.parent.frame().qname() == '%s.object' % BUILTINS):
if caller.args:
- if context_lookup is None:
- context_lookup = {}
- node_context = context_lookup.get(caller.args[0])
+ node_context = context.extra_context.get(caller.args[0])
infer = caller.args[0].infer(context=node_context)
else:
infer = []
return (Instance(x) if x is not util.Uninferable else x for x in infer)
- return self._proxied.infer_call_result(caller, context, context_lookup)
+ return self._proxied.infer_call_result(caller, context)
def bool_value(self):
return True
@@ -442,7 +437,7 @@ class BoundMethod(UnboundMethod):
cls.locals = cls_locals
return cls
- def infer_call_result(self, caller, context=None, context_lookup=None):
+ def infer_call_result(self, caller, context=None):
context = contextmod.bind_context_to_node(context, self.bound)
if (self.bound.__class__.__name__ == 'ClassDef'
and self.bound.name == 'type'
@@ -456,7 +451,7 @@ class BoundMethod(UnboundMethod):
if new_cls:
return iter((new_cls, ))
- return super(BoundMethod, self).infer_call_result(caller, context, context_lookup)
+ return super(BoundMethod, self).infer_call_result(caller, context)
def bool_value(self):
return True
diff --git a/astroid/brain/brain_functools.py b/astroid/brain/brain_functools.py
index a021b405..fa5ab9c3 100644
--- a/astroid/brain/brain_functools.py
+++ b/astroid/brain/brain_functools.py
@@ -33,7 +33,7 @@ class LruWrappedModel(objectmodel.FunctionModel):
_CacheInfo(0, 0, 0, 0)
''')
class CacheInfoBoundMethod(BoundMethod):
- def infer_call_result(self, caller, context=None, context_lookup=None):
+ def infer_call_result(self, caller, context=None):
yield helpers.safe_infer(cache_info)
return CacheInfoBoundMethod(proxy=self._instance, bound=self._instance)
@@ -94,7 +94,7 @@ def _functools_partial_inference(node, context=None):
filled_positionals = len(call.positional_arguments[1:])
filled_keywords = list(call.keyword_arguments)
- def infer_call_result(self, caller=None, context=None, context_lookup=None):
+ def infer_call_result(self, caller=None, context=None):
nonlocal call
filled_args = call.positional_arguments[1:]
filled_keywords = call.keyword_arguments
@@ -113,7 +113,6 @@ def _functools_partial_inference(node, context=None):
return super().infer_call_result(
caller=caller,
context=context,
- context_lookup=context_lookup,
)
partial_function = PartialFunction(
@@ -173,4 +172,4 @@ MANAGER.register_transform(
astroid.Call,
astroid.inference_tip(_functools_partial_inference),
_looks_like_functools_partial,
-) \ No newline at end of file
+)
diff --git a/astroid/context.py b/astroid/context.py
index 75cab636..a6ca9b7c 100644
--- a/astroid/context.py
+++ b/astroid/context.py
@@ -18,7 +18,7 @@ class InferenceContext:
Account for already visited nodes to infinite stop infinite recursion
"""
- __slots__ = ('path', 'lookupname', 'callcontext', 'boundnode', 'inferred')
+ __slots__ = ('path', 'lookupname', 'callcontext', 'boundnode', 'inferred', 'extra_context')
def __init__(self, path=None, inferred=None):
self.path = path or set()
@@ -61,6 +61,13 @@ class InferenceContext:
Currently the key is ``(node, lookupname, callcontext, boundnode)``
and the value is tuple of the inferred results
"""
+ self.extra_context = {}
+ """
+ :type: dict(NodeNG, Context)
+
+ Context that needs to be passed down through call stacks
+ for call arguments
+ """
def push(self, node):
"""Push node into inference path
@@ -87,6 +94,7 @@ class InferenceContext:
clone = InferenceContext(copy.copy(self.path), inferred=self.inferred)
clone.callcontext = self.callcontext
clone.boundnode = self.boundnode
+ clone.extra_context = copy.copy(self.extra_context)
return clone
def cache_generator(self, key, generator):
diff --git a/astroid/inference.py b/astroid/inference.py
index b9e098b4..a6cd0d3c 100644
--- a/astroid/inference.py
+++ b/astroid/inference.py
@@ -186,9 +186,10 @@ def infer_call(self, context=None):
callcontext.callcontext = contextmod.CallContext(args=self.args,
keywords=self.keywords)
callcontext.boundnode = None
- context_lookup = None
+ extra_context = {}
if context is not None:
- context_lookup = _populate_context_lookup(self, context.clone())
+ extra_context = _populate_context_lookup(self, context.clone())
+ callcontext.extra_context = extra_context
for callee in self.func.infer(context):
if callee is util.Uninferable:
yield callee
@@ -198,7 +199,6 @@ def infer_call(self, context=None):
yield from callee.infer_call_result(
caller=self,
context=callcontext,
- context_lookup=context_lookup,
)
except exceptions.InferenceError:
## XXX log error ?
diff --git a/astroid/interpreter/objectmodel.py b/astroid/interpreter/objectmodel.py
index 1ac1a8cd..f6a53e34 100644
--- a/astroid/interpreter/objectmodel.py
+++ b/astroid/interpreter/objectmodel.py
@@ -294,7 +294,7 @@ class FunctionModel(ObjectModel):
# is different.
return 0
- def infer_call_result(self, caller, context=None, context_lookup=None):
+ def infer_call_result(self, caller, context=None):
if len(caller.args) != 2:
raise exceptions.InferenceError(
"Invalid arguments for descriptor binding",
@@ -418,7 +418,7 @@ class ClassModel(ObjectModel):
# Cls.mro is a method and we need to return one in order to have a proper inference.
# The method we're returning is capable of inferring the underlying MRO though.
class MroBoundMethod(bases.BoundMethod):
- def infer_call_result(self, caller, context=None, context_lookup=None):
+ def infer_call_result(self, caller, context=None):
yield other_self.py__mro__
implicit_metaclass = self._instance.implicit_metaclass()
@@ -461,7 +461,7 @@ class ClassModel(ObjectModel):
obj.postinit(classes)
class SubclassesBoundMethod(bases.BoundMethod):
- def infer_call_result(self, caller, context=None, context_lookup=None):
+ def infer_call_result(self, caller, context=None):
yield obj
implicit_metaclass = self._instance.implicit_metaclass()
@@ -594,7 +594,7 @@ class DictModel(ObjectModel):
"""Generate a bound method that can infer the given *obj*."""
class DictMethodBoundMethod(astroid.BoundMethod):
- def infer_call_result(self, caller, context=None, context_lookup=None):
+ def infer_call_result(self, caller, context=None):
yield obj
meth = next(self._instance._proxied.igetattr(name))
diff --git a/astroid/node_classes.py b/astroid/node_classes.py
index 483a2c1e..a17af1a2 100644
--- a/astroid/node_classes.py
+++ b/astroid/node_classes.py
@@ -305,6 +305,8 @@ class NodeNG:
:returns: The inferred values.
:rtype: iterable
"""
+ if context is not None:
+ context = context.extra_context.get(self, context)
if self._explicit_inference is not None:
# explicit_inference is not bound, give it self explicitly
try:
diff --git a/astroid/protocols.py b/astroid/protocols.py
index 2cd1e9d8..8d0a3dcb 100644
--- a/astroid/protocols.py
+++ b/astroid/protocols.py
@@ -306,7 +306,8 @@ def _arguments_infer_argname(self, name, context):
return
if context and context.callcontext:
- call_site = arguments.CallSite(context.callcontext)
+ call_site = arguments.CallSite(context.callcontext,
+ context.extra_context)
for value in call_site.infer_argument(self.parent, name, context):
yield value
return
diff --git a/astroid/scoped_nodes.py b/astroid/scoped_nodes.py
index dd9cfd44..1eef1416 100644
--- a/astroid/scoped_nodes.py
+++ b/astroid/scoped_nodes.py
@@ -1150,7 +1150,7 @@ class Lambda(mixins.FilterStmtsMixin, LocalsDictNodeNG):
names.append(self.args.kwarg)
return names
- def infer_call_result(self, caller, context=None, context_lookup=None):
+ def infer_call_result(self, caller, context=None):
"""Infer what the function returns when called.
:param caller: Unused
@@ -1567,7 +1567,7 @@ class FunctionDef(mixins.MultiLineBlockMixin, node_classes.Statement, Lambda):
"""
return next(self._get_yield_nodes_skip_lambdas(), False)
- def infer_call_result(self, caller=None, context=None, context_lookup=None):
+ def infer_call_result(self, caller=None, context=None):
"""Infer what the function returns when called.
:returns: What the function returns.
@@ -2030,7 +2030,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
result.parent = caller.parent
return result
- def infer_call_result(self, caller, context=None, context_lookup=None):
+ def infer_call_result(self, caller, context=None):
"""infer what a class is returning when called"""
if (self.is_subtype_of('%s.type' % (BUILTINS,), context)
and len(caller.args) == 3):
@@ -2049,7 +2049,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG,
dunder_call.qname() != "builtins.type.__call__"):
context = contextmod.bind_context_to_node(context, self)
yield from dunder_call.infer_call_result(
- caller, context, context_lookup)
+ caller, context)
else:
# Call type.__call__ if not set metaclass
# (since type is the default metaclass)
diff --git a/astroid/tests/unittest_inference.py b/astroid/tests/unittest_inference.py
index d08cc0d9..5820de17 100644
--- a/astroid/tests/unittest_inference.py
+++ b/astroid/tests/unittest_inference.py
@@ -4611,5 +4611,41 @@ def test_call_on_instance_with_inherited_dunder_call_method():
assert val.name == "Sub"
+class TestInferencePropagation:
+ """Make sure function argument values are properly
+ propagated to sub functions"""
+ def test_call_context_propagation(self):
+ n = extract_node("""
+ def chest(a):
+ return a * a
+ def best(a, b):
+ return chest(a)
+ def test(a, b, c):
+ return best(a, b)
+ test(4, 5, 6) #@
+ """)
+ assert next(n.infer()).as_string() == "16"
+
+ def test_call_starargs_propagation(self):
+ code = """
+ def foo(*args):
+ return args
+ def bar(*args):
+ return foo(*args)
+ bar(4, 5, 6, 7) #@
+ """
+ assert next(extract_node(code).infer()).as_string() == "(4, 5, 6, 7)"
+
+ def test_call_kwargs_propagation(self):
+ code = """
+ def b(**kwargs):
+ return kwargs
+ def f(**kwargs):
+ return b(**kwargs)
+ f(**{'f': 1}) #@
+ """
+ assert next(extract_node(code).infer()).as_string() == "{'f': 1}"
+
+
if __name__ == '__main__':
unittest.main()