diff options
| author | Claudiu Popa <pcmanticore@gmail.com> | 2019-01-14 15:18:36 +0100 |
|---|---|---|
| committer | Claudiu Popa <pcmanticore@gmail.com> | 2019-01-14 15:18:36 +0100 |
| commit | 09505a0412d944ecdd8e679afe6b6e9baa165075 (patch) | |
| tree | ec002877f30daaf2dd4b080411f4909a5cc5f66d | |
| parent | e6ffd3379dea81a598f08819f498d1172d9cdcf7 (diff) | |
| download | astroid-git-09505a0412d944ecdd8e679afe6b6e9baa165075.tar.gz | |
Switch to a global context by default
| -rw-r--r-- | astroid/arguments.py | 4 | ||||
| -rw-r--r-- | astroid/bases.py | 26 | ||||
| -rw-r--r-- | astroid/brain/brain_builtin_inference.py | 37 | ||||
| -rw-r--r-- | astroid/brain/brain_functools.py | 4 | ||||
| -rw-r--r-- | astroid/builder.py | 10 | ||||
| -rw-r--r-- | astroid/context.py | 5 | ||||
| -rw-r--r-- | astroid/helpers.py | 20 | ||||
| -rw-r--r-- | astroid/inference.py | 107 | ||||
| -rw-r--r-- | astroid/interpreter/objectmodel.py | 11 | ||||
| -rw-r--r-- | astroid/node_classes.py | 40 | ||||
| -rw-r--r-- | astroid/objects.py | 9 | ||||
| -rw-r--r-- | astroid/protocols.py | 39 | ||||
| -rw-r--r-- | astroid/scoped_nodes.py | 58 |
13 files changed, 204 insertions, 166 deletions
diff --git a/astroid/arguments.py b/astroid/arguments.py index c4bdc6d9..6a8952e8 100644 --- a/astroid/arguments.py +++ b/astroid/arguments.py @@ -72,7 +72,7 @@ class CallSite: def _unpack_keywords(self, keywords): values = {} - context = contextmod.InferenceContext() + context = contextmod.global_context context.extra_context = self.argument_context_map for name, value in keywords: if name is None: @@ -112,7 +112,7 @@ class CallSite: def _unpack_args(self, args): values = [] - context = contextmod.InferenceContext() + context = contextmod.global_context context.extra_context = self.argument_context_map for arg in args: if isinstance(arg, nodes.Starred): diff --git a/astroid/bases.py b/astroid/bases.py index a5ffb470..714c2422 100644 --- a/astroid/bases.py +++ b/astroid/bases.py @@ -113,7 +113,7 @@ class Proxy: return self.__dict__[name] return getattr(self._proxied, name) - def infer(self, context=None): + def infer(self, context=contextmod.global_context): yield self @@ -125,7 +125,7 @@ def _infer_stmts(stmts, context, frame=None): context = context.clone(branch_path=False) else: name = None - context = contextmod.InferenceContext() + context = contextmod.global_context for stmt in stmts: if stmt is util.Uninferable: @@ -178,7 +178,7 @@ class BaseInstance(Proxy): def display_type(self): return "Instance of" - def getattr(self, name, context=None, lookupclass=True): + def getattr(self, name, context=contextmod.global_context, lookupclass=True): try: values = self._proxied.instance_attr(name, context) except exceptions.AttributeInferenceError as exc: @@ -230,7 +230,7 @@ class BaseInstance(Proxy): except exceptions.AttributeInferenceError as error: raise exceptions.InferenceError(**vars(error)) from error - def _wrap_attr(self, attrs, context=None): + def _wrap_attr(self, attrs, context=contextmod.global_context): """wrap bound methods of attrs in a InstanceMethod proxies""" for attr in attrs: if isinstance(attr, UnboundMethod): @@ -252,9 +252,9 @@ class BaseInstance(Proxy): else: yield attr - def infer_call_result(self, caller, context=None): + def infer_call_result(self, caller, context=contextmod.global_context): """infer what a class instance is returning when called""" - context = contextmod.bind_context_to_node(context, self, False) + context = contextmod.bind_context_to_node(context, self, branch_path=False) inferred = False for node in self._proxied.igetattr("__call__", context): if node is util.Uninferable or not node.callable(): @@ -308,7 +308,7 @@ class Instance(BaseInstance): nonzero. If a class defines neither __len__() nor __bool__(), all its instances are considered true. """ - context = contextmod.InferenceContext() + context = contextmod.global_context context.callcontext = contextmod.CallContext(args=[]) context.boundnode = self @@ -323,7 +323,7 @@ class Instance(BaseInstance): return result # This is set in inference.py. - def getitem(self, index, context=None): + def getitem(self, index, context=contextmod.global_context): pass @@ -348,12 +348,12 @@ class UnboundMethod(Proxy): def is_bound(self): return False - def getattr(self, name, context=None): + def getattr(self, name, context=contextmod.global_context): if name in self.special_attributes: return [self.special_attributes.lookup(name)] return self._proxied.getattr(name, context) - def igetattr(self, name, context=None): + def igetattr(self, name, context=contextmod.global_context): if name in self.special_attributes: return iter((self.special_attributes.lookup(name),)) return self._proxied.igetattr(name, context) @@ -472,8 +472,10 @@ class BoundMethod(UnboundMethod): cls.locals = cls_locals return cls - def infer_call_result(self, caller, context=None): - context = contextmod.bind_context_to_node(context, self.bound, False) + def infer_call_result(self, caller, context=contextmod.global_context): + context = contextmod.bind_context_to_node( + context, self.bound, branch_path=False + ) if ( self.bound.__class__.__name__ == "ClassDef" and self.bound.name == "type" diff --git a/astroid/brain/brain_builtin_inference.py b/astroid/brain/brain_builtin_inference.py index 2655095a..47fd3b3c 100644 --- a/astroid/brain/brain_builtin_inference.py +++ b/astroid/brain/brain_builtin_inference.py @@ -25,6 +25,7 @@ from astroid import ( MroError, ) from astroid import arguments +from astroid import context as contextmod from astroid.builder import AstroidBuilder from astroid import helpers from astroid import nodes @@ -128,7 +129,7 @@ def register_builtin_transform(transform, builtin_name): an optional context. """ - def _transform_wrapper(node, context=None): + def _transform_wrapper(node, context=contextmod.global_context): result = transform(node, context=context) if result: if not result.parent: @@ -162,7 +163,7 @@ def _generic_inference(node, context, node_type, transform): if not transformed: try: inferred = next(arg.infer(context=context)) - except (InferenceError, StopIteration): + except InferenceError: raise UseInferenceDefault() if inferred is util.Uninferable: raise UseInferenceDefault() @@ -271,7 +272,7 @@ def _get_elts(arg, context): return items -def infer_dict(node, context=None): +def infer_dict(node, context=contextmod.global_context): """Try to infer a dict call to a Dict node. The function treats the following cases: @@ -315,7 +316,7 @@ def infer_dict(node, context=None): return value -def infer_super(node, context=None): +def infer_super(node, context=contextmod.global_context): """Understand super calls. There are some restrictions for what can be understood: @@ -396,7 +397,7 @@ def _infer_getattr_args(node, context): return obj, attr.value -def infer_getattr(node, context=None): +def infer_getattr(node, context=contextmod.global_context): """Understand getattr calls If one of the arguments is an Uninferable object, then the @@ -424,7 +425,7 @@ def infer_getattr(node, context=None): raise UseInferenceDefault -def infer_hasattr(node, context=None): +def infer_hasattr(node, context=contextmod.global_context): """Understand hasattr calls This always guarantees three possible outcomes for calling @@ -451,7 +452,7 @@ def infer_hasattr(node, context=None): return nodes.Const(True) -def infer_callable(node, context=None): +def infer_callable(node, context=contextmod.global_context): """Understand callable calls This follows Python's semantics, where an object @@ -473,7 +474,7 @@ def infer_callable(node, context=None): return nodes.Const(inferred.callable()) -def infer_bool(node, context=None): +def infer_bool(node, context=contextmod.global_context): """Understand bool calls.""" if len(node.args) > 1: # Invalid bool call. @@ -496,7 +497,7 @@ def infer_bool(node, context=None): return nodes.Const(bool_value) -def infer_type(node, context=None): +def infer_type(node, context=contextmod.global_context): """Understand the one-argument form of *type*.""" if len(node.args) != 1: raise UseInferenceDefault @@ -504,7 +505,7 @@ def infer_type(node, context=None): return helpers.object_type(node.args[0], context) -def infer_slice(node, context=None): +def infer_slice(node, context=contextmod.global_context): """Understand `slice` calls.""" args = node.args if not 0 < len(args) <= 3: @@ -530,7 +531,7 @@ def infer_slice(node, context=None): return slice_node -def _infer_object__new__decorator(node, context=None): +def _infer_object__new__decorator(node, context=contextmod.global_context): # Instantiate class immediately # since that's what @object.__new__ does return iter((node.instantiate_class(),)) @@ -551,7 +552,7 @@ def _infer_object__new__decorator_check(node): return False -def infer_issubclass(callnode, context=None): +def infer_issubclass(callnode, context=contextmod.global_context): """Infer issubclass() calls :param nodes.Call callnode: an `issubclass` call @@ -596,7 +597,7 @@ def infer_issubclass(callnode, context=None): return nodes.Const(issubclass_bool) -def infer_isinstance(callnode, context=None): +def infer_isinstance(callnode, context=contextmod.global_context): """Infer isinstance calls :param nodes.Call callnode: an isinstance call @@ -637,7 +638,7 @@ def infer_isinstance(callnode, context=None): return nodes.Const(isinstance_bool) -def _class_or_tuple_to_container(node, context=None): +def _class_or_tuple_to_container(node, context=contextmod.global_context): # Move inferences results into container # to simplify later logic # raises InferenceError if any of the inferences fall through @@ -656,7 +657,7 @@ def _class_or_tuple_to_container(node, context=None): return class_container -def infer_len(node, context=None): +def infer_len(node, context=contextmod.global_context): """Infer length calls :param nodes.Call node: len call to infer @@ -678,7 +679,7 @@ def infer_len(node, context=None): raise UseInferenceDefault(str(exc)) from exc -def infer_str(node, context=None): +def infer_str(node, context=contextmod.global_context): """Infer str() calls :param nodes.Call node: str() call to infer @@ -694,7 +695,7 @@ def infer_str(node, context=None): raise UseInferenceDefault(str(exc)) from exc -def infer_int(node, context=None): +def infer_int(node, context=contextmod.global_context): """Infer int() calls :param nodes.Call node: int() call to infer @@ -726,7 +727,7 @@ def infer_int(node, context=None): return nodes.Const(0) -def infer_dict_fromkeys(node, context=None): +def infer_dict_fromkeys(node, context=contextmod.global_context): """Infer dict.fromkeys :param nodes.Call node: dict.fromkeys() call to infer diff --git a/astroid/brain/brain_functools.py b/astroid/brain/brain_functools.py index 93bc9d3f..56a55ff9 100644 --- a/astroid/brain/brain_functools.py +++ b/astroid/brain/brain_functools.py @@ -7,6 +7,7 @@ from itertools import chain import astroid from astroid import arguments +from astroid import context as contextmod from astroid import BoundMethod from astroid import extract_node from astroid import helpers @@ -60,7 +61,7 @@ def _transform_lru_cache(node, context=None): return -def _functools_partial_inference(node, context=None): +def _functools_partial_inference(node, context=contextmod.global_context): call = arguments.CallSite.from_call(node) number_of_positional = len(call.positional_arguments) if number_of_positional < 1: @@ -106,6 +107,7 @@ def _functools_partial_inference(node, context=None): def infer_call_result(self, caller=None, context=None): nonlocal call + context = contextmod.copy_context(context, branch_path=False) filled_args = call.positional_arguments[1:] filled_keywords = call.keyword_arguments diff --git a/astroid/builder.py b/astroid/builder.py index 4fff6c8c..ccec20dc 100644 --- a/astroid/builder.py +++ b/astroid/builder.py @@ -153,14 +153,14 @@ class AstroidBuilder(raw_building.InspectBuilder): module.future_imports.add(symbol) self.add_from_names_to_locals(from_node) - # handle delayed assattr nodes - context_obj = context.InferenceContext() - for delayed in module._delayed_assattr: - self.delayed_assattr(delayed, context_obj) - # Visit the transforms if self._apply_transforms: module = self._manager.visit_transforms(module) + + # handle delayed assattr nodes + for delayed in module._delayed_assattr: + self.delayed_assattr(delayed, context.global_context) + return module def _data_build(self, data, modname, path): diff --git a/astroid/context.py b/astroid/context.py index 34d6d424..c55faa20 100644 --- a/astroid/context.py +++ b/astroid/context.py @@ -166,7 +166,7 @@ def copy_context( if context is not None: return context.clone(branch_path=branch_path) - return InferenceContext() + return global_context def bind_context_to_node(context, node, branch_path=True): @@ -191,3 +191,6 @@ def bind_context_to_node(context, node, branch_path=True): context = copy_context(context, branch_path=branch_path) context.boundnode = node return context + + +global_context = InferenceContext() diff --git a/astroid/helpers.py b/astroid/helpers.py index fe2757d9..94019131 100644 --- a/astroid/helpers.py +++ b/astroid/helpers.py @@ -44,10 +44,10 @@ def _function_type(function, builtins): return _build_proxy_class(cls_name, builtins) -def _object_type(node, context=None): +def _object_type(node, context=contextmod.global_context): astroid_manager = manager.AstroidManager() builtins = astroid_manager.astroid_cache[BUILTINS] - context = context or contextmod.InferenceContext() + context = context or contextmod.global_context for inferred in node.infer(context=context): if isinstance(inferred, scoped_nodes.ClassDef): @@ -65,7 +65,7 @@ def _object_type(node, context=None): yield inferred._proxied -def object_type(node, context=None): +def object_type(node, context=contextmod.global_context): """Obtain the type of the given node This is used to implement the ``type`` builtin, which means that it's @@ -84,7 +84,7 @@ def object_type(node, context=None): return list(types)[0] -def _object_type_is_subclass(obj_type, class_or_seq, context=None): +def _object_type_is_subclass(obj_type, class_or_seq, context=contextmod.global_context): if not isinstance(class_or_seq, (tuple, list)): class_seq = (class_or_seq,) else: @@ -111,7 +111,7 @@ def _object_type_is_subclass(obj_type, class_or_seq, context=None): return False -def object_isinstance(node, class_or_seq, context=None): +def object_isinstance(node, class_or_seq, context=contextmod.global_context): """Check if a node 'isinstance' any node in class_or_seq :param node: A given node @@ -126,7 +126,7 @@ def object_isinstance(node, class_or_seq, context=None): return _object_type_is_subclass(obj_type, class_or_seq, context=context) -def object_issubclass(node, class_or_seq, context=None): +def object_issubclass(node, class_or_seq, context=contextmod.global_context): """Check if a type is a subclass of any node in class_or_seq :param node: A given node @@ -142,7 +142,7 @@ def object_issubclass(node, class_or_seq, context=None): return _object_type_is_subclass(node, class_or_seq, context=context) -def safe_infer(node, context=None): +def safe_infer(node, context=contextmod.global_context): """Return the inferred value for the given node. Return None if inference failed or if there is some ambiguity (more than @@ -162,7 +162,7 @@ def safe_infer(node, context=None): return value -def has_known_bases(klass, context=None): +def has_known_bases(klass, context=contextmod.global_context): """Return true if all base classes of a class could be inferred.""" try: return klass._all_bases_known @@ -205,7 +205,7 @@ def is_supertype(type1, type2): return _type_check(type1, type2) -def class_instance_as_index(node, context=None): +def class_instance_as_index(node, context=contextmod.global_context): """Get the value as an index for the given instance. If an instance provides an __index__ method, then it can @@ -228,7 +228,7 @@ def class_instance_as_index(node, context=None): return None -def object_len(node, context=None): +def object_len(node, context=contextmod.global_context): """Infer length of given node object :param Union[nodes.ClassDef, nodes.Instance] node: diff --git a/astroid/inference.py b/astroid/inference.py index 32b41e8c..0d7358d5 100644 --- a/astroid/inference.py +++ b/astroid/inference.py @@ -43,7 +43,7 @@ MANAGER = manager.AstroidManager() # .infer method ############################################################### -def infer_end(self, context=None): +def infer_end(self, context=contextmod.global_context): """inference's end for node such as Module, ClassDef, FunctionDef, Const... @@ -59,7 +59,7 @@ nodes.Const._infer = infer_end nodes.Slice._infer = infer_end -def _infer_sequence_helper(node, context=None): +def _infer_sequence_helper(node, context=contextmod.global_context): """Infer all values based on _BaseContainer.elts""" values = [] @@ -77,8 +77,8 @@ def _infer_sequence_helper(node, context=None): @decorators.raise_if_nothing_inferred -# @decorators.path_wrapper -def infer_sequence(self, context=None): +@decorators.path_wrapper +def infer_sequence(self, context=contextmod.global_context): if not any(isinstance(e, nodes.Starred) for e in self.elts): yield self else: @@ -96,16 +96,6 @@ nodes.Tuple._infer = infer_sequence nodes.Set._infer = infer_sequence -def infer_map(self, context=None): - if not any(isinstance(k, nodes.DictUnpack) for k, _ in self.items): - yield self - else: - items = _infer_map(self, context) - new_seq = type(self)(self.lineno, self.col_offset, self.parent) - new_seq.postinit(list(items.items())) - yield new_seq - - def _update_with_replacement(lhs_dict, rhs_dict): """Delete nodes that equate to duplicate keys @@ -150,6 +140,18 @@ def _infer_map(node, context): return values +@decorators.raise_if_nothing_inferred +@decorators.path_wrapper +def infer_map(self, context=None): + if not any(isinstance(k, nodes.DictUnpack) for k, _ in self.items): + yield self + else: + items = _infer_map(self, context) + new_seq = type(self)(self.lineno, self.col_offset, self.parent) + new_seq.postinit(list(items.items())) + yield new_seq + + nodes.Dict._infer = infer_map @@ -173,7 +175,9 @@ def _higher_function_scope(node): return None -def infer_name(self, context=None): +@decorators.raise_if_nothing_inferred +@decorators.path_wrapper +def infer_name(self, context=contextmod.global_context): """infer a Name: use name lookup rules""" frame, stmts = self.lookup(self.name) if not stmts: @@ -192,14 +196,13 @@ def infer_name(self, context=None): return bases._infer_stmts(stmts, context, frame) -# pylint: disable=no-value-for-parameter -nodes.Name._infer = decorators.raise_if_nothing_inferred(infer_name) -nodes.AssignName.infer_lhs = infer_name # won't work with a path wrapper +nodes.Name._infer = infer_name +nodes.AssignName.infer_lhs = infer_name @decorators.raise_if_nothing_inferred @decorators.path_wrapper -def infer_call(self, context=None): +def infer_call(self, context=contextmod.global_context): """infer a Call node by trying to guess what the function returns""" callcontext = contextmod.copy_context(context, branch_path=False) callcontext.callcontext = contextmod.CallContext( @@ -226,7 +229,7 @@ nodes.Call._infer = infer_call @decorators.raise_if_nothing_inferred @decorators.path_wrapper -def infer_import(self, context=None, asname=True): +def infer_import(self, context=contextmod.global_context, asname=True): """infer an Import node: return the imported module/object""" name = context.lookupname if name is None: @@ -246,7 +249,7 @@ nodes.Import._infer = infer_import @decorators.raise_if_nothing_inferred @decorators.path_wrapper -def infer_import_from(self, context=None, asname=True): +def infer_import_from(self, context=contextmod.global_context, asname=True): """infer a ImportFrom node: return the imported module/object""" name = context.lookupname if name is None: @@ -274,7 +277,8 @@ nodes.ImportFrom._infer = infer_import_from @decorators.raise_if_nothing_inferred -def infer_attribute(self, context=None): +@decorators.path_wrapper +def infer_attribute(self, context=contextmod.global_context): """infer an Attribute node by using getattr on the associated object""" for owner in self.expr.infer(context): if owner is util.Uninferable: @@ -298,25 +302,28 @@ def infer_attribute(self, context=None): # Can't determine anything useful. pass + context = contextmod.copy_context(context, branch_path=False) + context.boundnode = owner 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 - context.boundnode = None + except exceptions.AttributeInferenceError as error: + raise exceptions.InferenceError( + error.message, + target=self, + attribute=context.lookupname, + context=context, + ) from error + return dict(node=self, context=context) -nodes.Attribute._infer = decorators.path_wrapper(infer_attribute) -nodes.AssignAttr.infer_lhs = infer_attribute # # won't work with a path wrapper +nodes.Attribute._infer = infer_attribute +nodes.AssignAttr.infer_lhs = infer_attribute @decorators.raise_if_nothing_inferred @decorators.path_wrapper -def infer_global(self, context=None): +def infer_global(self, context=contextmod.global_context): if context.lookupname is None: raise exceptions.InferenceError(node=self, context=context) try: @@ -334,7 +341,8 @@ _SUBSCRIPT_SENTINEL = object() @decorators.raise_if_nothing_inferred -def infer_subscript(self, context=None): +@decorators.path_wrapper +def infer_subscript(self, context=contextmod.global_context): """Inference for subscripts We're understanding if the index is a Const @@ -392,13 +400,13 @@ def infer_subscript(self, context=None): return None -nodes.Subscript._infer = decorators.path_wrapper(infer_subscript) +nodes.Subscript._infer = infer_subscript nodes.Subscript.infer_lhs = infer_subscript @decorators.raise_if_nothing_inferred @decorators.path_wrapper -def _infer_boolop(self, context=None): +def _infer_boolop(self, context=contextmod.global_context): """Infer a boolean operation (and / or / not). The function will calculate the boolean operation @@ -466,7 +474,7 @@ def _filter_operation_errors(self, infer_callable, context, error): yield result -def _infer_unaryop(self, context=None): +def _infer_unaryop(self, context=contextmod.global_context): """Infer what an UnaryOp should return when evaluated.""" for operand in self.operand.infer(context): try: @@ -522,7 +530,7 @@ def _infer_unaryop(self, context=None): @decorators.raise_if_nothing_inferred @decorators.path_wrapper -def infer_unaryop(self, context=None): +def infer_unaryop(self, context=contextmod.global_context): """Infer what an UnaryOp should return when evaluated.""" yield from _filter_operation_errors( self, _infer_unaryop, context, util.BadUnaryOperationMessage @@ -737,9 +745,8 @@ def _infer_binop(self, context): # we use two separate contexts for evaluating lhs and rhs because # 1. evaluating lhs may leave some undesired entries in context.path # which may not let us infer right value of rhs - context = context or contextmod.InferenceContext() - lhs_context = contextmod.copy_context(context, branch_path=False) - rhs_context = contextmod.copy_context(context, branch_path=False) + lhs_context = contextmod.copy_context(context, branch_path=True) + rhs_context = contextmod.copy_context(context, branch_path=True) lhs_iter = left.infer(context=lhs_context) rhs_iter = right.infer(context=rhs_context) for lhs, rhs in itertools.product(lhs_iter, rhs_iter): @@ -756,7 +763,7 @@ def _infer_binop(self, context): @decorators.yes_if_nothing_inferred @decorators.path_wrapper -def infer_binop(self, context=None): +def infer_binop(self, context=contextmod.global_context): return _filter_operation_errors( self, _infer_binop, context, util.BadBinaryOperationMessage ) @@ -766,10 +773,10 @@ nodes.BinOp._infer_binop = _infer_binop nodes.BinOp._infer = infer_binop -def _infer_augassign(self, context=None): +def _infer_augassign(self, context=contextmod.global_context): """Inference logic for augmented binary operations.""" if context is None: - context = contextmod.InferenceContext() + context = contextmod.global_context rhs_context = context.clone(branch_path=False) @@ -795,7 +802,7 @@ def _infer_augassign(self, context=None): @decorators.raise_if_nothing_inferred @decorators.path_wrapper -def infer_augassign(self, context=None): +def infer_augassign(self, context=contextmod.global_context): return _filter_operation_errors( self, _infer_augassign, context, util.BadBinaryOperationMessage ) @@ -808,7 +815,8 @@ nodes.AugAssign._infer = infer_augassign @decorators.raise_if_nothing_inferred -def infer_arguments(self, context=None): +@decorators.path_wrapper +def infer_arguments(self, context=contextmod.global_context): name = context.lookupname if name is None: raise exceptions.InferenceError(node=self, context=context) @@ -820,7 +828,7 @@ nodes.Arguments._infer = infer_arguments @decorators.raise_if_nothing_inferred @decorators.path_wrapper -def infer_assign(self, context=None): +def infer_assign(self, context=contextmod.global_context): """infer a AssignName/AssignAttr: need to inspect the RHS part of the assign node """ @@ -838,7 +846,7 @@ nodes.AssignAttr._infer = infer_assign @decorators.raise_if_nothing_inferred @decorators.path_wrapper -def infer_empty_node(self, context=None): +def infer_empty_node(self, context=contextmod.global_context): if not self.has_underlying_object(): yield util.Uninferable else: @@ -852,7 +860,8 @@ nodes.EmptyNode._infer = infer_empty_node @decorators.raise_if_nothing_inferred -def infer_index(self, context=None): +@decorators.path_wrapper +def infer_index(self, context=contextmod.global_context): return self.value.infer(context) @@ -860,7 +869,7 @@ nodes.Index._infer = infer_index # TODO: move directly into bases.Instance when the dependency hell # will be solved. -def instance_getitem(self, index, context=None): +def instance_getitem(self, index, context=contextmod.global_context): # Rewrap index to Const for this case new_context = contextmod.bind_context_to_node(context, self, branch_path=False) if not context: diff --git a/astroid/interpreter/objectmodel.py b/astroid/interpreter/objectmodel.py index 3103cdec..fc5a812d 100644 --- a/astroid/interpreter/objectmodel.py +++ b/astroid/interpreter/objectmodel.py @@ -106,7 +106,6 @@ class ObjectModel: It should return an AST or an interpreter object, but if the name is not found, then an AttributeInferenceError will be raised. """ - if name in self.attributes(): return getattr(self, "py" + name) raise exceptions.AttributeInferenceError(target=self._instance, attribute=name) @@ -294,7 +293,7 @@ class FunctionModel(ObjectModel): # is different. return 0 - def infer_call_result(self, caller, context=None): + def infer_call_result(self, caller, context=contextmod.global_context): if len(caller.args) != 2: raise exceptions.InferenceError( "Invalid arguments for descriptor binding", @@ -430,7 +429,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): + def infer_call_result(self, caller, context=contextmod.global_context): yield other_self.py__mro__ implicit_metaclass = self._instance.implicit_metaclass() @@ -440,7 +439,7 @@ class ClassModel(ObjectModel): @property def py__bases__(self): obj = node_classes.Tuple() - context = contextmod.InferenceContext() + context = contextmod.global_context elts = list(self._instance._inferred_bases(context)) obj.postinit(elts=elts) return obj @@ -478,7 +477,7 @@ class ClassModel(ObjectModel): obj.postinit(classes) class SubclassesBoundMethod(bases.BoundMethod): - def infer_call_result(self, caller, context=None): + def infer_call_result(self, caller, context=contextmod.global_context): yield obj implicit_metaclass = self._instance.implicit_metaclass() @@ -625,7 +624,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): + def infer_call_result(self, caller, context=contextmod.global_context): yield obj meth = next(self._instance._proxied.igetattr(name)) diff --git a/astroid/node_classes.py b/astroid/node_classes.py index fe6f6bbb..abe0e0b7 100644 --- a/astroid/node_classes.py +++ b/astroid/node_classes.py @@ -49,7 +49,7 @@ MANAGER = manager.AstroidManager() @decorators.raise_if_nothing_inferred -def unpack_infer(stmt, context=None): +def unpack_infer(stmt, context=contextmod.global_context): """recursively generate nodes inferred by the given statement. If the inferred value is a list or a tuple, recurse on the elements """ @@ -155,7 +155,7 @@ def are_exclusive( _SLICE_SENTINEL = object() -def _slice_value(index, context=None): +def _slice_value(index, context=contextmod.global_context): """Get the value of the given slice index.""" if isinstance(index, Const): @@ -182,7 +182,7 @@ def _slice_value(index, context=None): return _SLICE_SENTINEL -def _infer_slice(node, context=None): +def _infer_slice(node, context=contextmod.global_context): lower = _slice_value(node.lower, context) upper = _slice_value(node.upper, context) step = _slice_value(node.step, context) @@ -197,7 +197,7 @@ def _infer_slice(node, context=None): ) -def _container_getitem(instance, elts, index, context=None): +def _container_getitem(instance, elts, index, context=contextmod.global_context): """Get a slice or an item, using the given *index*, for the given sequence.""" try: if isinstance(index, Slice): @@ -326,7 +326,7 @@ class NodeNG: self.col_offset = col_offset self.parent = parent - def infer(self, context=None, **kwargs): + def infer(self, context=contextmod.global_context, **kwargs): """Get a generator of the inferred values. This is the main entry point to the inference system. @@ -725,7 +725,7 @@ class NodeNG: # overridden for ImportFrom, Import, Global, TryExcept and Arguments pass - def _infer(self, context=None): + def _infer(self, context=contextmod.global_context): """we don't know how to resolve a statement by default""" # this method is overridden by most concrete classes raise exceptions.InferenceError( @@ -1093,7 +1093,7 @@ class LookupMixIn: :rtype: iterable """ frame, stmts = self.lookup(name) - context = contextmod.InferenceContext() + context = contextmod.global_context return bases._infer_stmts(stmts, context, frame) def _filter_stmts(self, stmts, frame, offset): @@ -1960,10 +1960,10 @@ class AugAssign(mixins.AssignTypeMixin, Statement): self.value = value # This is set by inference.py - def _infer_augassign(self, context=None): + def _infer_augassign(self, context=contextmod.global_context): raise NotImplementedError - def type_errors(self, context=None): + def type_errors(self, context=contextmod.global_context): """Get a list of type errors which can occur during inference. Each TypeError is represented by a :class:`BadBinaryOperationMessage` , @@ -2073,10 +2073,10 @@ class BinOp(NodeNG): self.right = right # This is set by inference.py - def _infer_binop(self, context=None): + def _infer_binop(self, context=contextmod.global_context): raise NotImplementedError - def type_errors(self, context=None): + def type_errors(self, context=contextmod.global_context): """Get a list of type errors which can occur during inference. Each TypeError is represented by a :class:`BadBinaryOperationMessage`, @@ -2454,7 +2454,7 @@ class Const(mixins.NoChildrenMixin, NodeNG, bases.Instance): raise AttributeError return super().__getattr__(name) - def getitem(self, index, context=None): + def getitem(self, index, context=contextmod.global_context): """Get an item from this node if subscriptable. :param index: The node to use as a subscript index. @@ -2763,7 +2763,7 @@ class Dict(NodeNG, bases.Instance): """ return [key for (key, _) in self.items] - def getitem(self, index, context=None): + def getitem(self, index, context=contextmod.global_context): """Get an item from this node. :param index: The node to use as a subscript index. @@ -3600,7 +3600,7 @@ class List(_BaseContainer): """ return "%s.list" % BUILTINS - def getitem(self, index, context=None): + def getitem(self, index, context=contextmod.global_context): """Get an item from this node. :param index: The node to use as a subscript index. @@ -3885,7 +3885,7 @@ class Slice(NodeNG): """ return "%s.slice" % BUILTINS - def igetattr(self, attrname, context=None): + def igetattr(self, attrname, context=contextmod.global_context): """Infer the possible values of the given attribute on the slice. :param attrname: The name of the attribute to infer. @@ -3903,7 +3903,7 @@ class Slice(NodeNG): else: yield from self.getattr(attrname, context=context) - def getattr(self, attrname, context=None): + def getattr(self, attrname, context=contextmod.global_context): return self._proxied.getattr(attrname, context) def get_children(self): @@ -4217,7 +4217,7 @@ class Tuple(_BaseContainer): """ return "%s.tuple" % BUILTINS - def getitem(self, index, context=None): + def getitem(self, index, context=contextmod.global_context): """Get an item from this node. :param index: The node to use as a subscript index. @@ -4274,10 +4274,10 @@ class UnaryOp(NodeNG): self.operand = operand # This is set by inference.py - def _infer_unaryop(self, context=None): + def _infer_unaryop(self, context=contextmod.global_context): raise NotImplementedError - def type_errors(self, context=None): + def type_errors(self, context=contextmod.global_context): """Get a list of type errors which can occur during inference. Each TypeError is represented by a :class:`BadBinaryOperationMessage`, @@ -4589,7 +4589,7 @@ class Unknown(mixins.AssignTypeMixin, NodeNG): def qname(self): return "Unknown" - def infer(self, context=None, **kwargs): + def infer(self, context=contextmod.global_context, **kwargs): """Inference on an Unknown node immediately terminates.""" yield util.Uninferable diff --git a/astroid/objects.py b/astroid/objects.py index 367f650e..d9a4f593 100644 --- a/astroid/objects.py +++ b/astroid/objects.py @@ -20,6 +20,7 @@ leads to an inferred FrozenSet: import builtins from astroid import bases +from astroid import context as contextmod from astroid import decorators from astroid import exceptions from astroid import MANAGER @@ -38,7 +39,7 @@ class FrozenSet(node_classes._BaseContainer): def pytype(self): return "%s.frozenset" % BUILTINS - def _infer(self, context=None): + def _infer(self, context=contextmod.global_context): yield self @decorators.cachedproperty @@ -71,7 +72,7 @@ class Super(node_classes.NodeNG): self._self_class = self_class self._scope = scope - def _infer(self, context=None): + def _infer(self, context=contextmod.global_context): yield self def super_mro(self): @@ -131,7 +132,7 @@ class Super(node_classes.NodeNG): def qname(self): return "super" - def igetattr(self, name, context=None): + def igetattr(self, name, context=contextmod.global_context): """Retrieve the inferred values of the given attribute name.""" if name in self.special_attributes: @@ -198,7 +199,7 @@ class Super(node_classes.NodeNG): target=self, attribute=name, context=context ) - def getattr(self, name, context=None): + def getattr(self, name, context=contextmod.global_context): return list(self.igetattr(name, context=context)) diff --git a/astroid/protocols.py b/astroid/protocols.py index be54645c..b4db8f9c 100644 --- a/astroid/protocols.py +++ b/astroid/protocols.py @@ -267,7 +267,9 @@ def _resolve_looppart(parts, assign_path, context): @decorators.raise_if_nothing_inferred -def for_assigned_stmts(self, node=None, context=None, assign_path=None): +def for_assigned_stmts( + self, node=None, context=contextmod.global_context, assign_path=None +): if isinstance(self, nodes.AsyncFor) or getattr(self, "is_async", False): # Skip inferring of async code for now return dict(node=self, unknown=node, assign_path=assign_path, context=context) @@ -284,7 +286,9 @@ nodes.For.assigned_stmts = for_assigned_stmts nodes.Comprehension.assigned_stmts = for_assigned_stmts -def sequence_assigned_stmts(self, node=None, context=None, assign_path=None): +def sequence_assigned_stmts( + self, node=None, context=contextmod.global_context, assign_path=None +): if assign_path is None: assign_path = [] try: @@ -307,7 +311,9 @@ nodes.Tuple.assigned_stmts = sequence_assigned_stmts nodes.List.assigned_stmts = sequence_assigned_stmts -def assend_assigned_stmts(self, node=None, context=None, assign_path=None): +def assend_assigned_stmts( + self, node=None, context=contextmod.global_context, assign_path=None +): return self.parent.assigned_stmts(node=self, context=context) @@ -360,7 +366,9 @@ def _arguments_infer_argname(self, name, context): yield util.Uninferable -def arguments_assigned_stmts(self, node=None, context=None, assign_path=None): +def arguments_assigned_stmts( + self, node=None, context=contextmod.global_context, assign_path=None +): if context.callcontext: # reset call context/name callcontext = context.callcontext @@ -375,7 +383,9 @@ nodes.Arguments.assigned_stmts = arguments_assigned_stmts @decorators.raise_if_nothing_inferred -def assign_assigned_stmts(self, node=None, context=None, assign_path=None): +def assign_assigned_stmts( + self, node=None, context=contextmod.global_context, assign_path=None +): if not assign_path: yield self.value return None @@ -386,7 +396,9 @@ def assign_assigned_stmts(self, node=None, context=None, assign_path=None): return dict(node=self, unknown=node, assign_path=assign_path, context=context) -def assign_annassigned_stmts(self, node=None, context=None, assign_path=None): +def assign_annassigned_stmts( + self, node=None, context=contextmod.global_context, assign_path=None +): for inferred in assign_assigned_stmts(self, node, context, assign_path): if inferred is None: yield util.Uninferable @@ -440,7 +452,9 @@ def _resolve_assignment_parts(parts, assign_path, context): @decorators.raise_if_nothing_inferred -def excepthandler_assigned_stmts(self, node=None, context=None, assign_path=None): +def excepthandler_assigned_stmts( + self, node=None, context=contextmod.global_context, assign_path=None +): for assigned in node_classes.unpack_infer(self.type): if isinstance(assigned, nodes.ClassDef): assigned = objects.ExceptionInstance(assigned) @@ -507,7 +521,9 @@ def _infer_context_manager(self, mgr, context): @decorators.raise_if_nothing_inferred -def with_assigned_stmts(self, node=None, context=None, assign_path=None): +def with_assigned_stmts( + self, node=None, context=contextmod.global_context, assign_path=None +): """Infer names and other nodes from a *with* statement. This enables only inference for name binding in a *with* statement. @@ -534,6 +550,7 @@ def with_assigned_stmts(self, node=None, context=None, assign_path=None): A list of indices, where each index specifies what item to fetch from the inference results. """ + context = contextmod.copy_context(context, branch_path=False) try: mgr = next(mgr for (mgr, vars) in self.items if vars == node) except StopIteration: @@ -580,7 +597,9 @@ nodes.With.assigned_stmts = with_assigned_stmts @decorators.yes_if_nothing_inferred -def starred_assigned_stmts(self, node=None, context=None, assign_path=None): +def starred_assigned_stmts( + self, node=None, context=contextmod.global_context, assign_path=None +): """ Arguments: self: nodes.Starred @@ -616,7 +635,7 @@ def starred_assigned_stmts(self, node=None, context=None, assign_path=None): ) if context is None: - context = contextmod.InferenceContext() + context = contextmod.global_context if isinstance(stmt, nodes.Assign): value = stmt.value diff --git a/astroid/scoped_nodes.py b/astroid/scoped_nodes.py index 1ab3893d..4f46f328 100644 --- a/astroid/scoped_nodes.py +++ b/astroid/scoped_nodes.py @@ -36,6 +36,7 @@ from typing import Optional, List from astroid import bases from astroid import context as contextmod +from astroid.context import global_context from astroid import exceptions from astroid import decorators as decorators_mod from astroid.interpreter import objectmodel @@ -511,7 +512,7 @@ class Module(LocalsDictNodeNG): """ return "Module" - def getattr(self, name, context=None, ignore_locals=False): + def getattr(self, name, context=contextmod.global_context, ignore_locals=False): result = [] name_in_locals = name in self.locals @@ -533,7 +534,7 @@ class Module(LocalsDictNodeNG): target=self, attribute=name, context=context ) - def igetattr(self, name, context=None): + def igetattr(self, name, context=contextmod.global_context): """Infer the possible values of the given variable. :param name: The name of the variable to infer. @@ -1188,7 +1189,7 @@ class Lambda(mixins.FilterStmtsMixin, LocalsDictNodeNG): names.append(self.args.kwarg) return names - def infer_call_result(self, caller, context=None): + def infer_call_result(self, caller, context=contextmod.global_context): """Infer what the function returns when called. :param caller: Unused @@ -1513,7 +1514,7 @@ class FunctionDef(mixins.MultiLineBlockMixin, node_classes.Statement, Lambda): """ return self.fromlineno, self.tolineno - def getattr(self, name, context=None): + def getattr(self, name, context=contextmod.global_context): """this method doesn't look in the instance_attrs dictionary since it's done by an Instance proxy at inference time. """ @@ -1523,7 +1524,7 @@ class FunctionDef(mixins.MultiLineBlockMixin, node_classes.Statement, Lambda): return [self.special_attributes.lookup(name)] raise exceptions.AttributeInferenceError(target=self, attribute=name) - def igetattr(self, name, context=None): + def igetattr(self, name, context=contextmod.global_context): """Inferred getattr, which returns an iterator of inferred statements.""" try: return bases._infer_stmts(self.getattr(name, context), context, frame=self) @@ -1585,9 +1586,10 @@ class FunctionDef(mixins.MultiLineBlockMixin, node_classes.Statement, Lambda): if self.decorators: for node in self.decorators.nodes: try: - inferred = next(node.infer()) + inferred = next(node.infer(context=global_context)) except exceptions.InferenceError: continue + if inferred and inferred.qname() in ( "abc.abstractproperty", "abc.abstractmethod", @@ -1611,7 +1613,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): + def infer_call_result(self, caller=None, context=contextmod.global_context): """Infer what the function returns when called. :returns: What the function returns. @@ -1959,9 +1961,9 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement if metaclass is not None: self._metaclass = metaclass - def _newstyle_impl(self, context=None): + def _newstyle_impl(self, context=contextmod.global_context): if context is None: - context = contextmod.InferenceContext() + context = contextmod.global_context if self._newstyle is not None: return self._newstyle for base in self.ancestors(recurs=False, context=context): @@ -2033,7 +2035,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement """ return True - def is_subtype_of(self, type_name, context=None): + def is_subtype_of(self, type_name, context=contextmod.global_context): """Whether this class is a subtype of the given type. :param type_name: The name of the type of check against. @@ -2085,7 +2087,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement result.parent = caller.parent return result - def infer_call_result(self, caller, context=None): + def infer_call_result(self, caller, context=contextmod.global_context): """infer what a class is returning when called""" if ( self.is_subtype_of("%s.type" % (BUILTINS,), context) @@ -2171,7 +2173,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement """ return [bnode.as_string() for bnode in self.bases] - def ancestors(self, recurs=True, context=None): + def ancestors(self, recurs=True, context=contextmod.global_context): """Iterate over the base classes in prefixed depth first order. :param recurs: Whether to recurse or return direct ancestors only. @@ -2184,7 +2186,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement # FIXME: inference make infinite loops possible here yielded = {self} if context is None: - context = contextmod.InferenceContext() + context = contextmod.global_context if not self.bases and self.qname() != "builtins.object": yield builtin_lookup("object")[1][0] return @@ -2215,7 +2217,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement except exceptions.InferenceError: continue - def local_attr_ancestors(self, name, context=None): + def local_attr_ancestors(self, name, context=contextmod.global_context): """Iterate over the parents that define the given name. :param name: The name to find definitions for. @@ -2236,7 +2238,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement if name in astroid: yield astroid - def instance_attr_ancestors(self, name, context=None): + def instance_attr_ancestors(self, name, context=contextmod.global_context): """Iterate over the parents that define the given name as an attribute. :param name: The name to find definitions for. @@ -2261,7 +2263,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement """ return node in self.bases - def local_attr(self, name, context=None): + def local_attr(self, name, context=contextmod.global_context): """Get the list of assign nodes associated to the given name. Assignments are looked for in both this class and in parents. @@ -2286,7 +2288,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement target=self, attribute=name, context=context ) - def instance_attr(self, name, context=None): + def instance_attr(self, name, context=contextmod.global_context): """Get the list of nodes associated to the given attribute name. Assignments are looked for in both this class and in parents. @@ -2319,7 +2321,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement """ return bases.Instance(self) - def getattr(self, name, context=None, class_context=True): + def getattr(self, name, context=contextmod.global_context, class_context=True): """Get an attribute from this class, using Python's attribute semantic. This method doesn't look in the :attr:`instance_attrs` dictionary @@ -2406,7 +2408,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement else: yield bases.BoundMethod(attr, self) - def igetattr(self, name, context=None, class_context=True): + def igetattr(self, name, context=contextmod.global_context, class_context=True): """Infer the possible values of the given variable. :param name: The name of the variable to infer. @@ -2443,7 +2445,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement error.message, target=self, attribute=name, context=context ) - def has_dynamic_getattr(self, context=None): + def has_dynamic_getattr(self, context=contextmod.global_context): """Check if the class has a custom __getattr__ or __getattribute__. If any such method is found and it is not from @@ -2470,7 +2472,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement pass return False - def getitem(self, index, context=None): + def getitem(self, index, context=contextmod.global_context): """Return the inference of a subscript. This is basically looking up the method in the metaclass and calling it. @@ -2537,7 +2539,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement _metaclass = None - def declared_metaclass(self, context=None): + def declared_metaclass(self, context=contextmod.global_context): """Return the explicit declared metaclass for the current class. An explicit declared metaclass is defined @@ -2573,7 +2575,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement return None - def _find_metaclass(self, seen=None, context=None): + def _find_metaclass(self, seen=None, context=contextmod.global_context): if seen is None: seen = set() seen.add(self) @@ -2587,7 +2589,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement break return klass - def metaclass(self, context=None): + def metaclass(self, context=contextmod.global_context): """Get the metaclass of this class. If this class does not define explicitly a metaclass, @@ -2706,7 +2708,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement return sorted(slots, key=lambda item: item.value) - def _inferred_bases(self, context=None): + def _inferred_bases(self, context=contextmod.global_context): # Similar with .ancestors, but the difference is when one base is inferred, # only the first object is wanted. That's because # we aren't interested in superclasses, as in the following @@ -2721,7 +2723,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement # only in SomeClass. if context is None: - context = contextmod.InferenceContext() + context = contextmod.global_context if not self.bases and self.qname() != "builtins.object": yield builtin_lookup("object")[1][0] return @@ -2740,7 +2742,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement else: yield from baseobj.bases - def _compute_mro(self, context=None): + def _compute_mro(self, context=contextmod.global_context): inferred_bases = list(self._inferred_bases(context=context)) bases_mro = [] for base in inferred_bases: @@ -2763,7 +2765,7 @@ class ClassDef(mixins.FilterStmtsMixin, LocalsDictNodeNG, node_classes.Statement _verify_duplicates_mro(unmerged_mro, self, context) return _c3_merge(unmerged_mro, self, context) - def mro(self, context=None): + def mro(self, context=contextmod.global_context): """Get the method resolution order, using C3 linearization. :returns: The list of ancestors, sorted by the mro. |
