_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q30900
TreeRebuilder.visit_compare
train
def visit_compare(self, node, parent): """visit a Compare node by returning a fresh instance of it""" newnode = nodes.Compare(node.lineno, node.col_offset, parent) newnode.postinit( self.visit(node.left, newnode), [ (self._cmp_op_classes[op.__class__], self.visit(expr, newnode)) for (op, expr) in zip(node.ops, node.comparators) ], ) return newnode
python
{ "resource": "" }
q30901
TreeRebuilder.visit_comprehension
train
def visit_comprehension(self, node, parent): """visit a Comprehension node by returning a fresh instance of it""" newnode = nodes.Comprehension(parent) newnode.postinit( self.visit(node.target, newnode), self.visit(node.iter, newnode), [self.visit(child, newnode) for child in node.ifs], getattr(node, "is_async", None), ) return newnode
python
{ "resource": "" }
q30902
TreeRebuilder.visit_decorators
train
def visit_decorators(self, node, parent): """visit a Decorators node by returning a fresh instance of it""" # /!\ node is actually a _ast.FunctionDef node while # parent is an astroid.nodes.FunctionDef node newnode = nodes.Decorators(node.lineno, node.col_offset, parent) newnode.postinit([self.visit(child, newnode) for child in node.decorator_list]) return newnode
python
{ "resource": "" }
q30903
TreeRebuilder.visit_delete
train
def visit_delete(self, node, parent): """visit a Delete node by returning a fresh instance of it""" newnode = nodes.Delete(node.lineno, node.col_offset, parent) newnode.postinit([self.visit(child, newnode) for child in node.targets]) return newnode
python
{ "resource": "" }
q30904
TreeRebuilder.visit_dict
train
def visit_dict(self, node, parent): """visit a Dict node by returning a fresh instance of it""" newnode = nodes.Dict(node.lineno, node.col_offset, parent) items = list(self._visit_dict_items(node, parent, newnode)) newnode.postinit(items) return newnode
python
{ "resource": "" }
q30905
TreeRebuilder.visit_dictcomp
train
def visit_dictcomp(self, node, parent): """visit a DictComp node by returning a fresh instance of it""" newnode = nodes.DictComp(node.lineno, node.col_offset, parent) newnode.postinit( self.visit(node.key, newnode), self.visit(node.value, newnode), [self.visit(child, newnode) for child in node.generators], ) return newnode
python
{ "resource": "" }
q30906
TreeRebuilder.visit_expr
train
def visit_expr(self, node, parent): """visit a Expr node by returning a fresh instance of it""" newnode = nodes.Expr(node.lineno, node.col_offset, parent) newnode.postinit(self.visit(node.value, newnode)) return newnode
python
{ "resource": "" }
q30907
TreeRebuilder.visit_ellipsis
train
def visit_ellipsis(self, node, parent): """visit an Ellipsis node by returning a fresh instance of it""" return nodes.Ellipsis( getattr(node, "lineno", None), getattr(node, "col_offset", None), parent )
python
{ "resource": "" }
q30908
TreeRebuilder.visit_emptynode
train
def visit_emptynode(self, node, parent): """visit an EmptyNode node by returning a fresh instance of it""" return nodes.EmptyNode( getattr(node, "lineno", None), getattr(node, "col_offset", None), parent )
python
{ "resource": "" }
q30909
TreeRebuilder.visit_exec
train
def visit_exec(self, node, parent): """visit an Exec node by returning a fresh instance of it""" newnode = nodes.Exec(node.lineno, node.col_offset, parent) newnode.postinit( self.visit(node.body, newnode), _visit_or_none(node, "globals", self, newnode), _visit_or_none(node, "locals", self, newnode), ) return newnode
python
{ "resource": "" }
q30910
TreeRebuilder.visit_extslice
train
def visit_extslice(self, node, parent): """visit an ExtSlice node by returning a fresh instance of it""" newnode = nodes.ExtSlice(parent=parent) newnode.postinit([self.visit(dim, newnode) for dim in node.dims]) return newnode
python
{ "resource": "" }
q30911
TreeRebuilder._visit_for
train
def _visit_for(self, cls, node, parent): """visit a For node by returning a fresh instance of it""" newnode = cls(node.lineno, node.col_offset, parent) type_annotation = self.check_type_comment(node) newnode.postinit( target=self.visit(node.target, newnode), iter=self.visit(node.iter, newnode), body=[self.visit(child, newnode) for child in node.body], orelse=[self.visit(child, newnode) for child in node.orelse], type_annotation=type_annotation, ) return newnode
python
{ "resource": "" }
q30912
TreeRebuilder.visit_importfrom
train
def visit_importfrom(self, node, parent): """visit an ImportFrom node by returning a fresh instance of it""" names = [(alias.name, alias.asname) for alias in node.names] newnode = nodes.ImportFrom( node.module or "", names, node.level or None, getattr(node, "lineno", None), getattr(node, "col_offset", None), parent, ) # store From names to add them to locals after building self._import_from_nodes.append(newnode) return newnode
python
{ "resource": "" }
q30913
TreeRebuilder._visit_functiondef
train
def _visit_functiondef(self, cls, node, parent): """visit an FunctionDef node to become astroid""" self._global_names.append({}) node, doc = self._get_doc(node) newnode = cls(node.name, doc, node.lineno, node.col_offset, parent) if node.decorator_list: decorators = self.visit_decorators(node, newnode) else: decorators = None if PY3 and node.returns: returns = self.visit(node.returns, newnode) else: returns = None type_comment_args = type_comment_returns = None type_comment_annotation = self.check_function_type_comment(node) if type_comment_annotation: type_comment_returns, type_comment_args = type_comment_annotation newnode.postinit( args=self.visit(node.args, newnode), body=[self.visit(child, newnode) for child in node.body], decorators=decorators, returns=returns, type_comment_returns=type_comment_returns, type_comment_args=type_comment_args, ) self._global_names.pop() return newnode
python
{ "resource": "" }
q30914
TreeRebuilder.visit_generatorexp
train
def visit_generatorexp(self, node, parent): """visit a GeneratorExp node by returning a fresh instance of it""" newnode = nodes.GeneratorExp(node.lineno, node.col_offset, parent) newnode.postinit( self.visit(node.elt, newnode), [self.visit(child, newnode) for child in node.generators], ) return newnode
python
{ "resource": "" }
q30915
TreeRebuilder.visit_attribute
train
def visit_attribute(self, node, parent): """visit an Attribute node by returning a fresh instance of it""" context = self._get_context(node) if context == astroid.Del: # FIXME : maybe we should reintroduce and visit_delattr ? # for instance, deactivating assign_ctx newnode = nodes.DelAttr(node.attr, node.lineno, node.col_offset, parent) elif context == astroid.Store: newnode = nodes.AssignAttr(node.attr, node.lineno, node.col_offset, parent) # Prohibit a local save if we are in an ExceptHandler. if not isinstance(parent, astroid.ExceptHandler): self._delayed_assattr.append(newnode) else: newnode = nodes.Attribute(node.attr, node.lineno, node.col_offset, parent) newnode.postinit(self.visit(node.value, newnode)) return newnode
python
{ "resource": "" }
q30916
TreeRebuilder.visit_global
train
def visit_global(self, node, parent): """visit a Global node to become astroid""" newnode = nodes.Global( node.names, getattr(node, "lineno", None), getattr(node, "col_offset", None), parent, ) if self._global_names: # global at the module level, no effect for name in node.names: self._global_names[-1].setdefault(name, []).append(newnode) return newnode
python
{ "resource": "" }
q30917
TreeRebuilder.visit_if
train
def visit_if(self, node, parent): """visit an If node by returning a fresh instance of it""" newnode = nodes.If(node.lineno, node.col_offset, parent) newnode.postinit( self.visit(node.test, newnode), [self.visit(child, newnode) for child in node.body], [self.visit(child, newnode) for child in node.orelse], ) return newnode
python
{ "resource": "" }
q30918
TreeRebuilder.visit_ifexp
train
def visit_ifexp(self, node, parent): """visit a IfExp node by returning a fresh instance of it""" newnode = nodes.IfExp(node.lineno, node.col_offset, parent) newnode.postinit( self.visit(node.test, newnode), self.visit(node.body, newnode), self.visit(node.orelse, newnode), ) return newnode
python
{ "resource": "" }
q30919
TreeRebuilder.visit_import
train
def visit_import(self, node, parent): """visit a Import node by returning a fresh instance of it""" names = [(alias.name, alias.asname) for alias in node.names] newnode = nodes.Import( names, getattr(node, "lineno", None), getattr(node, "col_offset", None), parent, ) # save import names in parent's locals: for (name, asname) in newnode.names: name = asname or name parent.set_local(name.split(".")[0], newnode) return newnode
python
{ "resource": "" }
q30920
TreeRebuilder.visit_index
train
def visit_index(self, node, parent): """visit a Index node by returning a fresh instance of it""" newnode = nodes.Index(parent=parent) newnode.postinit(self.visit(node.value, newnode)) return newnode
python
{ "resource": "" }
q30921
TreeRebuilder.visit_keyword
train
def visit_keyword(self, node, parent): """visit a Keyword node by returning a fresh instance of it""" newnode = nodes.Keyword(node.arg, parent=parent) newnode.postinit(self.visit(node.value, newnode)) return newnode
python
{ "resource": "" }
q30922
TreeRebuilder.visit_lambda
train
def visit_lambda(self, node, parent): """visit a Lambda node by returning a fresh instance of it""" newnode = nodes.Lambda(node.lineno, node.col_offset, parent) newnode.postinit(self.visit(node.args, newnode), self.visit(node.body, newnode)) return newnode
python
{ "resource": "" }
q30923
TreeRebuilder.visit_list
train
def visit_list(self, node, parent): """visit a List node by returning a fresh instance of it""" context = self._get_context(node) newnode = nodes.List( ctx=context, lineno=node.lineno, col_offset=node.col_offset, parent=parent ) newnode.postinit([self.visit(child, newnode) for child in node.elts]) return newnode
python
{ "resource": "" }
q30924
TreeRebuilder.visit_listcomp
train
def visit_listcomp(self, node, parent): """visit a ListComp node by returning a fresh instance of it""" newnode = nodes.ListComp(node.lineno, node.col_offset, parent) newnode.postinit( self.visit(node.elt, newnode), [self.visit(child, newnode) for child in node.generators], ) return newnode
python
{ "resource": "" }
q30925
TreeRebuilder.visit_name
train
def visit_name(self, node, parent): """visit a Name node by returning a fresh instance of it""" context = self._get_context(node) # True and False can be assigned to something in py2x, so we have to # check first the context. if context == astroid.Del: newnode = nodes.DelName(node.id, node.lineno, node.col_offset, parent) elif context == astroid.Store: newnode = nodes.AssignName(node.id, node.lineno, node.col_offset, parent) elif node.id in CONST_NAME_TRANSFORMS: newnode = nodes.Const( CONST_NAME_TRANSFORMS[node.id], getattr(node, "lineno", None), getattr(node, "col_offset", None), parent, ) return newnode else: newnode = nodes.Name(node.id, node.lineno, node.col_offset, parent) # XXX REMOVE me : if context in (astroid.Del, astroid.Store): # 'Aug' ?? self._save_assignment(newnode) return newnode
python
{ "resource": "" }
q30926
TreeRebuilder.visit_constant
train
def visit_constant(self, node, parent): """visit a Constant node by returning a fresh instance of Const""" return nodes.Const( node.value, getattr(node, "lineno", None), getattr(node, "col_offset", None), parent, )
python
{ "resource": "" }
q30927
TreeRebuilder.visit_num
train
def visit_num(self, node, parent): """visit a Num node by returning a fresh instance of Const""" return nodes.Const( node.n, getattr(node, "lineno", None), getattr(node, "col_offset", None), parent, )
python
{ "resource": "" }
q30928
TreeRebuilder.visit_pass
train
def visit_pass(self, node, parent): """visit a Pass node by returning a fresh instance of it""" return nodes.Pass(node.lineno, node.col_offset, parent)
python
{ "resource": "" }
q30929
TreeRebuilder.visit_print
train
def visit_print(self, node, parent): """visit a Print node by returning a fresh instance of it""" newnode = nodes.Print(node.nl, node.lineno, node.col_offset, parent) newnode.postinit( _visit_or_none(node, "dest", self, newnode), [self.visit(child, newnode) for child in node.values], ) return newnode
python
{ "resource": "" }
q30930
TreeRebuilder.visit_raise
train
def visit_raise(self, node, parent): """visit a Raise node by returning a fresh instance of it""" newnode = nodes.Raise(node.lineno, node.col_offset, parent) # pylint: disable=too-many-function-args newnode.postinit( _visit_or_none(node, "type", self, newnode), _visit_or_none(node, "inst", self, newnode), _visit_or_none(node, "tback", self, newnode), ) return newnode
python
{ "resource": "" }
q30931
TreeRebuilder.visit_return
train
def visit_return(self, node, parent): """visit a Return node by returning a fresh instance of it""" newnode = nodes.Return(node.lineno, node.col_offset, parent) if node.value is not None: newnode.postinit(self.visit(node.value, newnode)) return newnode
python
{ "resource": "" }
q30932
TreeRebuilder.visit_set
train
def visit_set(self, node, parent): """visit a Set node by returning a fresh instance of it""" newnode = nodes.Set(node.lineno, node.col_offset, parent) newnode.postinit([self.visit(child, newnode) for child in node.elts]) return newnode
python
{ "resource": "" }
q30933
TreeRebuilder.visit_setcomp
train
def visit_setcomp(self, node, parent): """visit a SetComp node by returning a fresh instance of it""" newnode = nodes.SetComp(node.lineno, node.col_offset, parent) newnode.postinit( self.visit(node.elt, newnode), [self.visit(child, newnode) for child in node.generators], ) return newnode
python
{ "resource": "" }
q30934
TreeRebuilder.visit_slice
train
def visit_slice(self, node, parent): """visit a Slice node by returning a fresh instance of it""" newnode = nodes.Slice(parent=parent) newnode.postinit( _visit_or_none(node, "lower", self, newnode), _visit_or_none(node, "upper", self, newnode), _visit_or_none(node, "step", self, newnode), ) return newnode
python
{ "resource": "" }
q30935
TreeRebuilder.visit_subscript
train
def visit_subscript(self, node, parent): """visit a Subscript node by returning a fresh instance of it""" context = self._get_context(node) newnode = nodes.Subscript( ctx=context, lineno=node.lineno, col_offset=node.col_offset, parent=parent ) newnode.postinit( self.visit(node.value, newnode), self.visit(node.slice, newnode) ) return newnode
python
{ "resource": "" }
q30936
TreeRebuilder.visit_tryexcept
train
def visit_tryexcept(self, node, parent): """visit a TryExcept node by returning a fresh instance of it""" newnode = nodes.TryExcept(node.lineno, node.col_offset, parent) newnode.postinit( [self.visit(child, newnode) for child in node.body], [self.visit(child, newnode) for child in node.handlers], [self.visit(child, newnode) for child in node.orelse], ) return newnode
python
{ "resource": "" }
q30937
TreeRebuilder.visit_tryfinally
train
def visit_tryfinally(self, node, parent): """visit a TryFinally node by returning a fresh instance of it""" newnode = nodes.TryFinally(node.lineno, node.col_offset, parent) newnode.postinit( [self.visit(child, newnode) for child in node.body], [self.visit(n, newnode) for n in node.finalbody], ) return newnode
python
{ "resource": "" }
q30938
TreeRebuilder.visit_tuple
train
def visit_tuple(self, node, parent): """visit a Tuple node by returning a fresh instance of it""" context = self._get_context(node) newnode = nodes.Tuple( ctx=context, lineno=node.lineno, col_offset=node.col_offset, parent=parent ) newnode.postinit([self.visit(child, newnode) for child in node.elts]) return newnode
python
{ "resource": "" }
q30939
TreeRebuilder.visit_unaryop
train
def visit_unaryop(self, node, parent): """visit a UnaryOp node by returning a fresh instance of it""" newnode = nodes.UnaryOp( self._unary_op_classes[node.op.__class__], node.lineno, node.col_offset, parent, ) newnode.postinit(self.visit(node.operand, newnode)) return newnode
python
{ "resource": "" }
q30940
TreeRebuilder.visit_while
train
def visit_while(self, node, parent): """visit a While node by returning a fresh instance of it""" newnode = nodes.While(node.lineno, node.col_offset, parent) newnode.postinit( self.visit(node.test, newnode), [self.visit(child, newnode) for child in node.body], [self.visit(child, newnode) for child in node.orelse], ) return newnode
python
{ "resource": "" }
q30941
TreeRebuilder.visit_yield
train
def visit_yield(self, node, parent): """visit a Yield node by returning a fresh instance of it""" newnode = nodes.Yield(node.lineno, node.col_offset, parent) if node.value is not None: newnode.postinit(self.visit(node.value, newnode)) return newnode
python
{ "resource": "" }
q30942
TreeRebuilder3.visit_arg
train
def visit_arg(self, node, parent): """visit an arg node by returning a fresh AssName instance""" return self.visit_assignname(node, parent, node.arg)
python
{ "resource": "" }
q30943
TreeRebuilder3.visit_excepthandler
train
def visit_excepthandler(self, node, parent): """visit an ExceptHandler node by returning a fresh instance of it""" newnode = nodes.ExceptHandler(node.lineno, node.col_offset, parent) if node.name: name = self.visit_assignname(node, newnode, node.name) else: name = None newnode.postinit( _visit_or_none(node, "type", self, newnode), name, [self.visit(child, newnode) for child in node.body], ) return newnode
python
{ "resource": "" }
q30944
TreeRebuilder3.visit_nonlocal
train
def visit_nonlocal(self, node, parent): """visit a Nonlocal node and return a new instance of it""" return nodes.Nonlocal( node.names, getattr(node, "lineno", None), getattr(node, "col_offset", None), parent, )
python
{ "resource": "" }
q30945
TreeRebuilder3.visit_starred
train
def visit_starred(self, node, parent): """visit a Starred node and return a new instance of it""" context = self._get_context(node) newnode = nodes.Starred( ctx=context, lineno=node.lineno, col_offset=node.col_offset, parent=parent ) newnode.postinit(self.visit(node.value, newnode)) return newnode
python
{ "resource": "" }
q30946
TreeRebuilder3.visit_annassign
train
def visit_annassign(self, node, parent): """visit an AnnAssign node by returning a fresh instance of it""" newnode = nodes.AnnAssign(node.lineno, node.col_offset, parent) annotation = _visit_or_none(node, "annotation", self, newnode) newnode.postinit( target=self.visit(node.target, newnode), annotation=annotation, simple=node.simple, value=_visit_or_none(node, "value", self, newnode), ) return newnode
python
{ "resource": "" }
q30947
AstroidManager.ast_from_module
train
def ast_from_module(self, module, modname=None): """given an imported module, return the astroid object""" modname = modname or module.__name__ if modname in self.astroid_cache: return self.astroid_cache[modname] try: # some builtin modules don't have __file__ attribute filepath = module.__file__ if modutils.is_python_source(filepath): return self.ast_from_file(filepath, modname) except AttributeError: pass from astroid.builder import AstroidBuilder return AstroidBuilder(self).module_build(module, modname)
python
{ "resource": "" }
q30948
AstroidManager.ast_from_class
train
def ast_from_class(self, klass, modname=None): """get astroid for the given class""" if modname is None: try: modname = klass.__module__ except AttributeError as exc: raise exceptions.AstroidBuildingError( "Unable to get module for class {class_name}.", cls=klass, class_repr=safe_repr(klass), modname=modname, ) from exc modastroid = self.ast_from_module_name(modname) return modastroid.getattr(klass.__name__)[0]
python
{ "resource": "" }
q30949
AstroidManager.infer_ast_from_something
train
def infer_ast_from_something(self, obj, context=None): """infer astroid for the given class""" if hasattr(obj, "__class__") and not isinstance(obj, type): klass = obj.__class__ else: klass = obj try: modname = klass.__module__ except AttributeError as exc: raise exceptions.AstroidBuildingError( "Unable to get module for {class_repr}.", cls=klass, class_repr=safe_repr(klass), ) from exc except Exception as exc: raise exceptions.AstroidImportError( "Unexpected error while retrieving module for {class_repr}:\n" "{error}", cls=klass, class_repr=safe_repr(klass), ) from exc try: name = klass.__name__ except AttributeError as exc: raise exceptions.AstroidBuildingError( "Unable to get name for {class_repr}:\n", cls=klass, class_repr=safe_repr(klass), ) from exc except Exception as exc: raise exceptions.AstroidImportError( "Unexpected error while retrieving name for {class_repr}:\n" "{error}", cls=klass, class_repr=safe_repr(klass), ) from exc # take care, on living object __module__ is regularly wrong :( modastroid = self.ast_from_module_name(modname) if klass is obj: for inferred in modastroid.igetattr(name, context): yield inferred else: for inferred in modastroid.igetattr(name, context): yield inferred.instantiate_class()
python
{ "resource": "" }
q30950
CallSite.from_call
train
def from_call(cls, call_node): """Get a CallSite object from the given Call node.""" callcontext = contextmod.CallContext(call_node.args, call_node.keywords) return cls(callcontext)
python
{ "resource": "" }
q30951
_inference_tip_cached
train
def _inference_tip_cached(func, instance, args, kwargs, _cache={}): """Cache decorator used for inference tips""" node = args[0] try: return iter(_cache[func, node]) except KeyError: result = func(*args, **kwargs) # Need to keep an iterator around original, copy = itertools.tee(result) _cache[func, node] = list(copy) return original
python
{ "resource": "" }
q30952
inference_tip
train
def inference_tip(infer_function, raise_on_overwrite=False): """Given an instance specific inference function, return a function to be given to MANAGER.register_transform to set this inference function. :param bool raise_on_overwrite: Raise an `InferenceOverwriteError` if the inference tip will overwrite another. Used for debugging Typical usage .. sourcecode:: python MANAGER.register_transform(Call, inference_tip(infer_named_tuple), predicate) .. Note:: Using an inference tip will override any previously set inference tip for the given node. Use a predicate in the transform to prevent excess overwrites. """ def transform(node, infer_function=infer_function): if ( raise_on_overwrite and node._explicit_inference is not None and node._explicit_inference is not infer_function ): raise InferenceOverwriteError( "Inference already set to {existing_inference}. " "Trying to overwrite with {new_inference} for {node}".format( existing_inference=infer_function, new_inference=node._explicit_inference, node=node, ) ) # pylint: disable=no-value-for-parameter node._explicit_inference = _inference_tip_cached(infer_function) return node return transform
python
{ "resource": "" }
q30953
cached
train
def cached(func, instance, args, kwargs): """Simple decorator to cache result of method calls without args.""" cache = getattr(instance, "__cache", None) if cache is None: instance.__cache = cache = {} try: return cache[func] except KeyError: cache[func] = result = func(*args, **kwargs) return result
python
{ "resource": "" }
q30954
path_wrapper
train
def path_wrapper(func): """return the given infer function wrapped to handle the path Used to stop inference if the node has already been looked at for a given `InferenceContext` to prevent infinite recursion """ @functools.wraps(func) def wrapped(node, context=None, _func=func, **kwargs): """wrapper function handling context""" if context is None: context = contextmod.InferenceContext() if context.push(node): return None yielded = set() generator = _func(node, context, **kwargs) try: while True: res = next(generator) # unproxy only true instance, not const, tuple, dict... if res.__class__.__name__ == "Instance": ares = res._proxied else: ares = res if ares not in yielded: yield res yielded.add(ares) except StopIteration as error: if error.args: return error.args[0] return None return wrapped
python
{ "resource": "" }
q30955
attach_dummy_node
train
def attach_dummy_node(node, name, runtime_object=_marker): """create a dummy node and register it in the locals of the given node with the specified name """ enode = nodes.EmptyNode() enode.object = runtime_object _attach_local_node(node, enode, name)
python
{ "resource": "" }
q30956
attach_const_node
train
def attach_const_node(node, name, value): """create a Const node and register it in the locals of the given node with the specified name """ if name not in node.special_attributes: _attach_local_node(node, nodes.const_factory(value), name)
python
{ "resource": "" }
q30957
attach_import_node
train
def attach_import_node(node, modname, membername): """create a ImportFrom node and register it in the locals of the given node with the specified name """ from_node = nodes.ImportFrom(modname, [(membername, None)]) _attach_local_node(node, from_node, membername)
python
{ "resource": "" }
q30958
build_module
train
def build_module(name, doc=None): """create and initialize an astroid Module node""" node = nodes.Module(name, doc, pure_python=False) node.package = False node.parent = None return node
python
{ "resource": "" }
q30959
build_class
train
def build_class(name, basenames=(), doc=None): """create and initialize an astroid ClassDef node""" node = nodes.ClassDef(name, doc) for base in basenames: basenode = nodes.Name() basenode.name = base node.bases.append(basenode) basenode.parent = node return node
python
{ "resource": "" }
q30960
build_function
train
def build_function(name, args=None, defaults=None, doc=None): """create and initialize an astroid FunctionDef node""" args, defaults = args or [], defaults or [] # first argument is now a list of decorators func = nodes.FunctionDef(name, doc) func.args = argsnode = nodes.Arguments() argsnode.args = [] for arg in args: argsnode.args.append(nodes.Name()) argsnode.args[-1].name = arg argsnode.args[-1].parent = argsnode argsnode.defaults = [] for default in defaults: argsnode.defaults.append(nodes.const_factory(default)) argsnode.defaults[-1].parent = argsnode argsnode.kwarg = None argsnode.vararg = None argsnode.parent = func if args: register_arguments(func) return func
python
{ "resource": "" }
q30961
register_arguments
train
def register_arguments(func, args=None): """add given arguments to local args is a list that may contains nested lists (i.e. def func(a, (b, c, d)): ...) """ if args is None: args = func.args.args if func.args.vararg: func.set_local(func.args.vararg, func.args) if func.args.kwarg: func.set_local(func.args.kwarg, func.args) for arg in args: if isinstance(arg, nodes.Name): func.set_local(arg.name, arg) else: register_arguments(func, arg.elts)
python
{ "resource": "" }
q30962
object_build_class
train
def object_build_class(node, member, localname): """create astroid for a living class object""" basenames = [base.__name__ for base in member.__bases__] return _base_class_object_build(node, member, basenames, localname=localname)
python
{ "resource": "" }
q30963
object_build_function
train
def object_build_function(node, member, localname): """create astroid for a living function object""" # pylint: disable=deprecated-method; completely removed in 2.0 args, varargs, varkw, defaults = inspect.getargspec(member) if varargs is not None: args.append(varargs) if varkw is not None: args.append(varkw) func = build_function( getattr(member, "__name__", None) or localname, args, defaults, member.__doc__ ) node.add_local_node(func, localname)
python
{ "resource": "" }
q30964
object_build_methoddescriptor
train
def object_build_methoddescriptor(node, member, localname): """create astroid for a living method descriptor object""" # FIXME get arguments ? func = build_function( getattr(member, "__name__", None) or localname, doc=member.__doc__ ) # set node's arguments to None to notice that we have no information, not # and empty argument list func.args.args = None node.add_local_node(func, localname) _add_dunder_class(func, member)
python
{ "resource": "" }
q30965
_astroid_bootstrapping
train
def _astroid_bootstrapping(): """astroid bootstrapping the builtins module""" # this boot strapping is necessary since we need the Const nodes to # inspect_build builtins, and then we can proxy Const builder = InspectBuilder() astroid_builtin = builder.inspect_build(builtins) # pylint: disable=redefined-outer-name for cls, node_cls in node_classes.CONST_CLS.items(): if cls is type(None): proxy = build_class("NoneType") proxy.parent = astroid_builtin elif cls is type(NotImplemented): proxy = build_class("NotImplementedType") proxy.parent = astroid_builtin else: proxy = astroid_builtin.getattr(cls.__name__)[0] if cls in (dict, list, set, tuple): node_cls._proxied = proxy else: _CONST_PROXY[cls] = proxy # Set the builtin module as parent for some builtins. nodes.Const._proxied = property(_set_proxied) _GeneratorType = nodes.ClassDef( types.GeneratorType.__name__, types.GeneratorType.__doc__ ) _GeneratorType.parent = astroid_builtin bases.Generator._proxied = _GeneratorType builder.object_build(bases.Generator._proxied, types.GeneratorType) if hasattr(types, "AsyncGeneratorType"): # pylint: disable=no-member; AsyncGeneratorType _AsyncGeneratorType = nodes.ClassDef( types.AsyncGeneratorType.__name__, types.AsyncGeneratorType.__doc__ ) _AsyncGeneratorType.parent = astroid_builtin bases.AsyncGenerator._proxied = _AsyncGeneratorType builder.object_build(bases.AsyncGenerator._proxied, types.AsyncGeneratorType) builtin_types = ( types.GetSetDescriptorType, types.GeneratorType, types.MemberDescriptorType, type(None), type(NotImplemented), types.FunctionType, types.MethodType, types.BuiltinFunctionType, types.ModuleType, types.TracebackType, ) for _type in builtin_types: if _type.__name__ not in astroid_builtin: cls = nodes.ClassDef(_type.__name__, _type.__doc__) cls.parent = astroid_builtin builder.object_build(cls, _type) astroid_builtin[_type.__name__] = cls
python
{ "resource": "" }
q30966
InspectBuilder.imported_member
train
def imported_member(self, node, member, name): """verify this is not an imported class or handle it""" # /!\ some classes like ExtensionClass doesn't have a __module__ # attribute ! Also, this may trigger an exception on badly built module # (see http://www.logilab.org/ticket/57299 for instance) try: modname = getattr(member, "__module__", None) except TypeError: modname = None if modname is None: if name in ("__new__", "__subclasshook__"): # Python 2.5.1 (r251:54863, Sep 1 2010, 22:03:14) # >>> print object.__new__.__module__ # None modname = builtins.__name__ else: attach_dummy_node(node, name, member) return True real_name = {"gtk": "gtk_gtk", "_io": "io"}.get(modname, modname) if real_name != self._module.__name__: # check if it sounds valid and then add an import node, else use a # dummy node try: getattr(sys.modules[modname], name) except (KeyError, AttributeError): attach_dummy_node(node, name, member) else: attach_import_node(node, modname, name) return True return False
python
{ "resource": "" }
q30967
parse
train
def parse(code, module_name="", path=None, apply_transforms=True): """Parses a source string in order to obtain an astroid AST from it :param str code: The code for the module. :param str module_name: The name for the module, if any :param str path: The path for the module :param bool apply_transforms: Apply the transforms for the give code. Use it if you don't want the default transforms to be applied. """ code = textwrap.dedent(code) builder = AstroidBuilder(manager=MANAGER, apply_transforms=apply_transforms) return builder.string_build(code, modname=module_name, path=path)
python
{ "resource": "" }
q30968
_extract_expressions
train
def _extract_expressions(node): """Find expressions in a call to _TRANSIENT_FUNCTION and extract them. The function walks the AST recursively to search for expressions that are wrapped into a call to _TRANSIENT_FUNCTION. If it finds such an expression, it completely removes the function call node from the tree, replacing it by the wrapped expression inside the parent. :param node: An astroid node. :type node: astroid.bases.NodeNG :yields: The sequence of wrapped expressions on the modified tree expression can be found. """ if ( isinstance(node, nodes.Call) and isinstance(node.func, nodes.Name) and node.func.name == _TRANSIENT_FUNCTION ): real_expr = node.args[0] real_expr.parent = node.parent # Search for node in all _astng_fields (the fields checked when # get_children is called) of its parent. Some of those fields may # be lists or tuples, in which case the elements need to be checked. # When we find it, replace it by real_expr, so that the AST looks # like no call to _TRANSIENT_FUNCTION ever took place. for name in node.parent._astroid_fields: child = getattr(node.parent, name) if isinstance(child, (list, tuple)): for idx, compound_child in enumerate(child): if compound_child is node: child[idx] = real_expr elif child is node: setattr(node.parent, name, real_expr) yield real_expr else: for child in node.get_children(): yield from _extract_expressions(child)
python
{ "resource": "" }
q30969
_find_statement_by_line
train
def _find_statement_by_line(node, line): """Extracts the statement on a specific line from an AST. If the line number of node matches line, it will be returned; otherwise its children are iterated and the function is called recursively. :param node: An astroid node. :type node: astroid.bases.NodeNG :param line: The line number of the statement to extract. :type line: int :returns: The statement on the line, or None if no statement for the line can be found. :rtype: astroid.bases.NodeNG or None """ if isinstance(node, (nodes.ClassDef, nodes.FunctionDef)): # This is an inaccuracy in the AST: the nodes that can be # decorated do not carry explicit information on which line # the actual definition (class/def), but .fromline seems to # be close enough. node_line = node.fromlineno else: node_line = node.lineno if node_line == line: return node for child in node.get_children(): result = _find_statement_by_line(child, line) if result: return result return None
python
{ "resource": "" }
q30970
extract_node
train
def extract_node(code, module_name=""): """Parses some Python code as a module and extracts a designated AST node. Statements: To extract one or more statement nodes, append #@ to the end of the line Examples: >>> def x(): >>> def y(): >>> return 1 #@ The return statement will be extracted. >>> class X(object): >>> def meth(self): #@ >>> pass The function object 'meth' will be extracted. Expressions: To extract arbitrary expressions, surround them with the fake function call __(...). After parsing, the surrounded expression will be returned and the whole AST (accessible via the returned node's parent attribute) will look like the function call was never there in the first place. Examples: >>> a = __(1) The const node will be extracted. >>> def x(d=__(foo.bar)): pass The node containing the default argument will be extracted. >>> def foo(a, b): >>> return 0 < __(len(a)) < b The node containing the function call 'len' will be extracted. If no statements or expressions are selected, the last toplevel statement will be returned. If the selected statement is a discard statement, (i.e. an expression turned into a statement), the wrapped expression is returned instead. For convenience, singleton lists are unpacked. :param str code: A piece of Python code that is parsed as a module. Will be passed through textwrap.dedent first. :param str module_name: The name of the module. :returns: The designated node from the parse tree, or a list of nodes. :rtype: astroid.bases.NodeNG, or a list of nodes. """ def _extract(node): if isinstance(node, nodes.Expr): return node.value return node requested_lines = [] for idx, line in enumerate(code.splitlines()): if line.strip().endswith(_STATEMENT_SELECTOR): requested_lines.append(idx + 1) tree = parse(code, module_name=module_name) if not tree.body: raise ValueError("Empty tree, cannot extract from it") extracted = [] if requested_lines: extracted = [_find_statement_by_line(tree, line) for line in requested_lines] # Modifies the tree. extracted.extend(_extract_expressions(tree)) if not extracted: extracted.append(tree.body[-1]) extracted = [_extract(node) for node in extracted] if len(extracted) == 1: return extracted[0] return extracted
python
{ "resource": "" }
q30971
AstroidBuilder.module_build
train
def module_build(self, module, modname=None): """Build an astroid from a living module instance.""" node = None path = getattr(module, "__file__", None) if path is not None: path_, ext = os.path.splitext(modutils._path_from_filename(path)) if ext in (".py", ".pyc", ".pyo") and os.path.exists(path_ + ".py"): node = self.file_build(path_ + ".py", modname) if node is None: # this is a built-in module # get a partial representation by introspection node = self.inspect_build(module, modname=modname, path=path) if self._apply_transforms: # We have to handle transformation by ourselves since the # rebuilder isn't called for builtin nodes node = self._manager.visit_transforms(node) return node
python
{ "resource": "" }
q30972
AstroidBuilder.string_build
train
def string_build(self, data, modname="", path=None): """Build astroid from source code string.""" module = self._data_build(data, modname, path) module.file_bytes = data.encode("utf-8") return self._post_build(module, "utf-8")
python
{ "resource": "" }
q30973
AstroidBuilder._post_build
train
def _post_build(self, module, encoding): """Handles encoding and delayed nodes after a module has been built""" module.file_encoding = encoding self._manager.cache_module(module) # post tree building steps after we stored the module in the cache: for from_node in module._import_from_nodes: if from_node.modname == "__future__": for symbol, _ in from_node.names: module.future_imports.add(symbol) self.add_from_names_to_locals(from_node) # handle delayed assattr nodes for delayed in module._delayed_assattr: self.delayed_assattr(delayed) # Visit the transforms if self._apply_transforms: module = self._manager.visit_transforms(module) return module
python
{ "resource": "" }
q30974
AstroidBuilder._data_build
train
def _data_build(self, data, modname, path): """Build tree node from data and add some informations""" try: node = _parse(data + "\n") except (TypeError, ValueError, SyntaxError) as exc: raise exceptions.AstroidSyntaxError( "Parsing Python code failed:\n{error}", source=data, modname=modname, path=path, error=exc, ) from exc if path is not None: node_file = os.path.abspath(path) else: node_file = "<?>" if modname.endswith(".__init__"): modname = modname[:-9] package = True else: package = ( path is not None and os.path.splitext(os.path.basename(path))[0] == "__init__" ) builder = rebuilder.TreeRebuilder(self._manager) module = builder.visit_module(node, modname, node_file, package) module._import_from_nodes = builder._import_from_nodes module._delayed_assattr = builder._delayed_assattr return module
python
{ "resource": "" }
q30975
AstroidBuilder.add_from_names_to_locals
train
def add_from_names_to_locals(self, node): """Store imported names to the locals Resort the locals if coming from a delayed node """ _key_func = lambda node: node.fromlineno def sort_locals(my_list): my_list.sort(key=_key_func) for (name, asname) in node.names: if name == "*": try: imported = node.do_import_module() except exceptions.AstroidBuildingError: continue for name in imported.public_names(): node.parent.set_local(name, node) sort_locals(node.parent.scope().locals[name]) else: node.parent.set_local(asname or name, node) sort_locals(node.parent.scope().locals[asname or name])
python
{ "resource": "" }
q30976
AstroidBuilder.delayed_assattr
train
def delayed_assattr(self, node): """Visit a AssAttr node This adds name to locals and handle members definition. """ try: frame = node.frame() for inferred in node.expr.infer(): if inferred is util.Uninferable: continue try: if inferred.__class__ is bases.Instance: inferred = inferred._proxied iattrs = inferred.instance_attrs if not _can_assign_attr(inferred, node.attrname): continue elif isinstance(inferred, bases.Instance): # Const, Tuple, ... we may be wrong, may be not, but # anyway we don't want to pollute builtin's namespace continue elif inferred.is_function: iattrs = inferred.instance_attrs else: iattrs = inferred.locals except AttributeError: # XXX log error continue values = iattrs.setdefault(node.attrname, []) if node in values: continue # get assign in __init__ first XXX useful ? if ( frame.name == "__init__" and values and values[0].frame().name != "__init__" ): values.insert(0, node) else: values.append(node) except exceptions.InferenceError: pass
python
{ "resource": "" }
q30977
_resolve_looppart
train
def _resolve_looppart(parts, assign_path, context): """recursive function to resolve multiple assignments on loops""" assign_path = assign_path[:] index = assign_path.pop(0) for part in parts: if part is util.Uninferable: continue if not hasattr(part, "itered"): continue try: itered = part.itered() except TypeError: continue for stmt in itered: index_node = nodes.Const(index) try: assigned = stmt.getitem(index_node, context) except ( AttributeError, exceptions.AstroidTypeError, exceptions.AstroidIndexError, ): continue if not assign_path: # we achieved to resolved the assignment path, # don't infer the last part yield assigned elif assigned is util.Uninferable: break else: # we are not yet on the last part of the path # search on each possibly inferred value try: yield from _resolve_looppart( assigned.infer(context), assign_path, context ) except exceptions.InferenceError: break
python
{ "resource": "" }
q30978
_resolve_assignment_parts
train
def _resolve_assignment_parts(parts, assign_path, context): """recursive function to resolve multiple assignments""" assign_path = assign_path[:] index = assign_path.pop(0) for part in parts: assigned = None if isinstance(part, nodes.Dict): # A dictionary in an iterating context try: assigned, _ = part.items[index] except IndexError: return elif hasattr(part, "getitem"): index_node = nodes.Const(index) try: assigned = part.getitem(index_node, context) except (exceptions.AstroidTypeError, exceptions.AstroidIndexError): return if not assigned: return if not assign_path: # we achieved to resolved the assignment path, don't infer the # last part yield assigned elif assigned is util.Uninferable: return else: # we are not yet on the last part of the path search on each # possibly inferred value try: yield from _resolve_assignment_parts( assigned.infer(context), assign_path, context ) except exceptions.InferenceError: return
python
{ "resource": "" }
q30979
_infer_sequence_helper
train
def _infer_sequence_helper(node, context=None): """Infer all values based on _BaseContainer.elts""" values = [] for elt in node.elts: if isinstance(elt, nodes.Starred): starred = helpers.safe_infer(elt.value, context) if not starred: raise exceptions.InferenceError(node=node, context=context) if not hasattr(starred, "elts"): raise exceptions.InferenceError(node=node, context=context) values.extend(_infer_sequence_helper(starred)) else: values.append(elt) return values
python
{ "resource": "" }
q30980
_update_with_replacement
train
def _update_with_replacement(lhs_dict, rhs_dict): """Delete nodes that equate to duplicate keys Since an astroid node doesn't 'equal' another node with the same value, this function uses the as_string method to make sure duplicate keys don't get through Note that both the key and the value are astroid nodes Fixes issue with DictUnpack causing duplicte keys in inferred Dict items :param dict(nodes.NodeNG, nodes.NodeNG) lhs_dict: Dictionary to 'merge' nodes into :param dict(nodes.NodeNG, nodes.NodeNG) rhs_dict: Dictionary with nodes to pull from :return dict(nodes.NodeNG, nodes.NodeNG): merged dictionary of nodes """ combined_dict = itertools.chain(lhs_dict.items(), rhs_dict.items()) # Overwrite keys which have the same string values string_map = {key.as_string(): (key, value) for key, value in combined_dict} # Return to dictionary return dict(string_map.values())
python
{ "resource": "" }
q30981
_infer_map
train
def _infer_map(node, context): """Infer all values based on Dict.items""" values = {} for name, value in node.items: if isinstance(name, nodes.DictUnpack): double_starred = helpers.safe_infer(value, context) if not double_starred: raise exceptions.InferenceError if not isinstance(double_starred, nodes.Dict): raise exceptions.InferenceError(node=node, context=context) unpack_items = _infer_map(double_starred, context) values = _update_with_replacement(values, unpack_items) else: key = helpers.safe_infer(name, context=context) value = helpers.safe_infer(value, context=context) if any(not elem for elem in (key, value)): raise exceptions.InferenceError(node=node, context=context) values = _update_with_replacement(values, {key: value}) return values
python
{ "resource": "" }
q30982
_higher_function_scope
train
def _higher_function_scope(node): """ Search for the first function which encloses the given scope. This can be used for looking up in that function's scope, in case looking up in a lower scope for a particular name fails. :param node: A scope node. :returns: ``None``, if no parent function scope was found, otherwise an instance of :class:`astroid.scoped_nodes.Function`, which encloses the given node. """ current = node while current.parent and not isinstance(current.parent, nodes.FunctionDef): current = current.parent if current and current.parent: return current.parent return None
python
{ "resource": "" }
q30983
infer_call
train
def infer_call(self, context=None): """infer a Call node by trying to guess what the function returns""" callcontext = contextmod.copy_context(context) callcontext.callcontext = contextmod.CallContext( args=self.args, keywords=self.keywords ) callcontext.boundnode = None if context is not None: callcontext.extra_context = _populate_context_lookup(self, context.clone()) for callee in self.func.infer(context): if callee is util.Uninferable: yield callee continue try: if hasattr(callee, "infer_call_result"): yield from callee.infer_call_result(caller=self, context=callcontext) except exceptions.InferenceError: continue return dict(node=self, context=context)
python
{ "resource": "" }
q30984
infer_attribute
train
def infer_attribute(self, context=None): """infer an Attribute node by using getattr on the associated object""" for owner in self.expr.infer(context): if owner is util.Uninferable: yield owner continue if context and context.boundnode: # This handles the situation where the attribute is accessed through a subclass # of a base class and the attribute is defined at the base class's level, # by taking in consideration a redefinition in the subclass. if isinstance(owner, bases.Instance) and isinstance( context.boundnode, bases.Instance ): try: if helpers.is_subtype( helpers.object_type(context.boundnode), helpers.object_type(owner), ): owner = context.boundnode except exceptions._NonDeducibleTypeHierarchy: # Can't determine anything useful. pass 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 return dict(node=self, context=context)
python
{ "resource": "" }
q30985
infer_subscript
train
def infer_subscript(self, context=None): """Inference for subscripts We're understanding if the index is a Const or a slice, passing the result of inference to the value's `getitem` method, which should handle each supported index type accordingly. """ found_one = False for value in self.value.infer(context): if value is util.Uninferable: yield util.Uninferable return None for index in self.slice.infer(context): if index is util.Uninferable: yield util.Uninferable return None # Try to deduce the index value. index_value = _SUBSCRIPT_SENTINEL if value.__class__ == bases.Instance: index_value = index else: if index.__class__ == bases.Instance: instance_as_index = helpers.class_instance_as_index(index) if instance_as_index: index_value = instance_as_index else: index_value = index if index_value is _SUBSCRIPT_SENTINEL: raise exceptions.InferenceError(node=self, context=context) try: assigned = value.getitem(index_value, context) except ( exceptions.AstroidTypeError, exceptions.AstroidIndexError, exceptions.AttributeInferenceError, AttributeError, ) as exc: raise exceptions.InferenceError(node=self, context=context) from exc # Prevent inferring if the inferred subscript # is the same as the original subscripted object. if self is assigned or assigned is util.Uninferable: yield util.Uninferable return None yield from assigned.infer(context) found_one = True if found_one: return dict(node=self, context=context) return None
python
{ "resource": "" }
q30986
_invoke_binop_inference
train
def _invoke_binop_inference(instance, opnode, op, other, context, method_name): """Invoke binary operation inference on the given instance.""" methods = dunder_lookup.lookup(instance, method_name) context = contextmod.bind_context_to_node(context, instance) method = methods[0] inferred = next(method.infer(context=context)) if inferred is util.Uninferable: raise exceptions.InferenceError return instance.infer_binary_op(opnode, op, other, context, inferred)
python
{ "resource": "" }
q30987
_aug_op
train
def _aug_op(instance, opnode, op, other, context, reverse=False): """Get an inference callable for an augmented binary operation.""" method_name = protocols.AUGMENTED_OP_METHOD[op] return functools.partial( _invoke_binop_inference, instance=instance, op=op, opnode=opnode, other=other, context=context, method_name=method_name, )
python
{ "resource": "" }
q30988
_bin_op
train
def _bin_op(instance, opnode, op, other, context, reverse=False): """Get an inference callable for a normal binary operation. If *reverse* is True, then the reflected method will be used instead. """ if reverse: method_name = protocols.REFLECTED_BIN_OP_METHOD[op] else: method_name = protocols.BIN_OP_METHOD[op] return functools.partial( _invoke_binop_inference, instance=instance, op=op, opnode=opnode, other=other, context=context, method_name=method_name, )
python
{ "resource": "" }
q30989
_get_binop_contexts
train
def _get_binop_contexts(context, left, right): """Get contexts for binary operations. This will return two inference contexts, the first one for x.__op__(y), the other one for y.__rop__(x), where only the arguments are inversed. """ # The order is important, since the first one should be # left.__op__(right). for arg in (right, left): new_context = context.clone() new_context.callcontext = contextmod.CallContext(args=[arg]) new_context.boundnode = None yield new_context
python
{ "resource": "" }
q30990
_get_binop_flow
train
def _get_binop_flow( left, left_type, binary_opnode, right, right_type, context, reverse_context ): """Get the flow for binary operations. The rules are a bit messy: * if left and right have the same type, then only one method will be called, left.__op__(right) * if left and right are unrelated typewise, then first left.__op__(right) is tried and if this does not exist or returns NotImplemented, then right.__rop__(left) is tried. * if left is a subtype of right, then only left.__op__(right) is tried. * if left is a supertype of right, then right.__rop__(left) is first tried and then left.__op__(right) """ op = binary_opnode.op if _same_type(left_type, right_type): methods = [_bin_op(left, binary_opnode, op, right, context)] elif helpers.is_subtype(left_type, right_type): methods = [_bin_op(left, binary_opnode, op, right, context)] elif helpers.is_supertype(left_type, right_type): methods = [ _bin_op(right, binary_opnode, op, left, reverse_context, reverse=True), _bin_op(left, binary_opnode, op, right, context), ] else: methods = [ _bin_op(left, binary_opnode, op, right, context), _bin_op(right, binary_opnode, op, left, reverse_context, reverse=True), ] return methods
python
{ "resource": "" }
q30991
_get_aug_flow
train
def _get_aug_flow( left, left_type, aug_opnode, right, right_type, context, reverse_context ): """Get the flow for augmented binary operations. The rules are a bit messy: * if left and right have the same type, then left.__augop__(right) is first tried and then left.__op__(right). * if left and right are unrelated typewise, then left.__augop__(right) is tried, then left.__op__(right) is tried and then right.__rop__(left) is tried. * if left is a subtype of right, then left.__augop__(right) is tried and then left.__op__(right). * if left is a supertype of right, then left.__augop__(right) is tried, then right.__rop__(left) and then left.__op__(right) """ bin_op = aug_opnode.op.strip("=") aug_op = aug_opnode.op if _same_type(left_type, right_type): methods = [ _aug_op(left, aug_opnode, aug_op, right, context), _bin_op(left, aug_opnode, bin_op, right, context), ] elif helpers.is_subtype(left_type, right_type): methods = [ _aug_op(left, aug_opnode, aug_op, right, context), _bin_op(left, aug_opnode, bin_op, right, context), ] elif helpers.is_supertype(left_type, right_type): methods = [ _aug_op(left, aug_opnode, aug_op, right, context), _bin_op(right, aug_opnode, bin_op, left, reverse_context, reverse=True), _bin_op(left, aug_opnode, bin_op, right, context), ] else: methods = [ _aug_op(left, aug_opnode, aug_op, right, context), _bin_op(left, aug_opnode, bin_op, right, context), _bin_op(right, aug_opnode, bin_op, left, reverse_context, reverse=True), ] return methods
python
{ "resource": "" }
q30992
_infer_binary_operation
train
def _infer_binary_operation(left, right, binary_opnode, context, flow_factory): """Infer a binary operation between a left operand and a right operand This is used by both normal binary operations and augmented binary operations, the only difference is the flow factory used. """ context, reverse_context = _get_binop_contexts(context, left, right) left_type = helpers.object_type(left) right_type = helpers.object_type(right) methods = flow_factory( left, left_type, binary_opnode, right, right_type, context, reverse_context ) for method in methods: try: results = list(method()) except AttributeError: continue except exceptions.AttributeInferenceError: continue except exceptions.InferenceError: yield util.Uninferable return else: if any(result is util.Uninferable for result in results): yield util.Uninferable return if all(map(_is_not_implemented, results)): continue not_implemented = sum( 1 for result in results if _is_not_implemented(result) ) if not_implemented and not_implemented != len(results): # Can't infer yet what this is. yield util.Uninferable return yield from results return # The operation doesn't seem to be supported so let the caller know about it yield util.BadBinaryOperationMessage(left_type, binary_opnode.op, right_type)
python
{ "resource": "" }
q30993
_infer_binop
train
def _infer_binop(self, context): """Binary operation inference logic.""" left = self.left right = self.right # 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) rhs_context = contextmod.copy_context(context) lhs_iter = left.infer(context=lhs_context) rhs_iter = right.infer(context=rhs_context) for lhs, rhs in itertools.product(lhs_iter, rhs_iter): if any(value is util.Uninferable for value in (rhs, lhs)): # Don't know how to process this. yield util.Uninferable return try: yield from _infer_binary_operation(lhs, rhs, self, context, _get_binop_flow) except exceptions._NonDeducibleTypeHierarchy: yield util.Uninferable
python
{ "resource": "" }
q30994
_infer_augassign
train
def _infer_augassign(self, context=None): """Inference logic for augmented binary operations.""" if context is None: context = contextmod.InferenceContext() rhs_context = context.clone() lhs_iter = self.target.infer_lhs(context=context) rhs_iter = self.value.infer(context=rhs_context) for lhs, rhs in itertools.product(lhs_iter, rhs_iter): if any(value is util.Uninferable for value in (rhs, lhs)): # Don't know how to process this. yield util.Uninferable return try: yield from _infer_binary_operation( left=lhs, right=rhs, binary_opnode=self, context=context, flow_factory=_get_aug_flow, ) except exceptions._NonDeducibleTypeHierarchy: yield util.Uninferable
python
{ "resource": "" }
q30995
_nose_tools_functions
train
def _nose_tools_functions(): """Get an iterator of names and bound methods.""" module = _BUILDER.string_build( textwrap.dedent( """ import unittest class Test(unittest.TestCase): pass a = Test() """ ) ) try: case = next(module["a"].infer()) except astroid.InferenceError: return for method in case.methods(): if method.name.startswith("assert") and "_" not in method.name: pep8_name = _pep8(method.name) yield pep8_name, astroid.BoundMethod(method, case) if method.name == "assertEqual": # nose also exports assert_equals. yield "assert_equals", astroid.BoundMethod(method, case)
python
{ "resource": "" }
q30996
_nose_tools_trivial_transform
train
def _nose_tools_trivial_transform(): """Custom transform for the nose.tools module.""" stub = _BUILDER.string_build("""__all__ = []""") all_entries = ["ok_", "eq_"] for pep8_name, method in _nose_tools_functions(): all_entries.append(pep8_name) stub[pep8_name] = method # Update the __all__ variable, since nose.tools # does this manually with .append. all_assign = stub["__all__"].parent all_object = astroid.List(all_entries) all_object.parent = all_assign all_assign.value = all_object return stub
python
{ "resource": "" }
q30997
_looks_like_numpy_function
train
def _looks_like_numpy_function(func_name, numpy_module_name, node): """ Return True if the current node correspond to the function inside the numpy module in parameters :param node: the current node :type node: FunctionDef :param func_name: name of the function :type func_name: str :param numpy_module_name: name of the numpy module :type numpy_module_name: str :return: True if the current node correspond to the function looked for :rtype: bool """ return node.name == func_name and node.parent.name == numpy_module_name
python
{ "resource": "" }
q30998
numpy_function_infer_call_result
train
def numpy_function_infer_call_result(node): """ A wrapper around infer_call_result method bounded to the node. :param node: the node which infer_call_result should be filtered :type node: FunctionDef :return: a function that filter the results of the call to node.infer_call_result :rtype: function """ #  Put the origin infer_call_result method into the closure origin_infer_call_result = node.infer_call_result def infer_call_result_wrapper(caller=None, context=None): """ Call the origin infer_call_result method bounded to the node instance and filter the results to remove List and Tuple instances """ unfiltered_infer_call_result = origin_infer_call_result(caller, context) return ( x for x in unfiltered_infer_call_result if not isinstance(x, (astroid.List, astroid.Tuple)) ) return infer_call_result_wrapper
python
{ "resource": "" }
q30999
unpack_infer
train
def unpack_infer(stmt, context=None): """recursively generate nodes inferred by the given statement. If the inferred value is a list or a tuple, recurse on the elements """ if isinstance(stmt, (List, Tuple)): for elt in stmt.elts: if elt is util.Uninferable: yield elt continue yield from unpack_infer(elt, context) return dict(node=stmt, context=context) # if inferred is a final node, return it and stop inferred = next(stmt.infer(context)) if inferred is stmt: yield inferred return dict(node=stmt, context=context) # else, infer recursively, except Uninferable object that should be returned as is for inferred in stmt.infer(context): if inferred is util.Uninferable: yield inferred else: yield from unpack_infer(inferred, context) return dict(node=stmt, context=context)
python
{ "resource": "" }