desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'return Instance of ClassDef node, else return self'
| def instantiate_class(self):
| return bases.Instance(self)
|
'Get an attribute from this class, using Python\'s attribute semantic
This method doesn\'t look in the instance_attrs dictionary
since it\'s done by an Instance proxy at inference time. It
may return a Uninferable object if the attribute has not been actually
found but a __getattr__ or __getattribute__ method is defined.
If *class_context* is given, then it\'s considered that the
attribute is accessed from a class context,
e.g. ClassDef.attribute, otherwise it might have been accessed
from an instance as well. If *class_context* is used in that
case, then a lookup in the implicit metaclass and the explicit
metaclass will be done.'
| def getattr(self, name, context=None, class_context=True):
| values = self.locals.get(name, [])
if ((name in self.special_attributes) and class_context and (not values)):
result = [self.special_attributes.lookup(name)]
if (name == '__bases__'):
result += values
return result
values = list(values)
for classnode in self.ancestors(recurs=True, context=context):
values += classnode.locals.get(name, [])
if class_context:
values += self._metaclass_lookup_attribute(name, context)
if (not values):
raise exceptions.AttributeInferenceError(target=self, attribute=name, context=context)
return values
|
'Search the given name in the implicit and the explicit metaclass.'
| def _metaclass_lookup_attribute(self, name, context):
| attrs = set()
implicit_meta = self.implicit_metaclass()
metaclass = self.metaclass()
for cls in {implicit_meta, metaclass}:
if (cls and (cls != self) and isinstance(cls, ClassDef)):
cls_attributes = self._get_attribute_from_metaclass(cls, name, context)
attrs.update(set(cls_attributes))
return attrs
|
'inferred getattr, need special treatment in class to handle
descriptors'
| def igetattr(self, name, context=None, class_context=True):
| context = contextmod.copy_context(context)
context.lookupname = name
try:
attrs = self.getattr(name, context, class_context=class_context)
for inferred in bases._infer_stmts(attrs, context, frame=self):
if ((not isinstance(inferred, node_classes.Const)) and isinstance(inferred, bases.Instance)):
try:
inferred._proxied.getattr('__get__', context)
except exceptions.AttributeInferenceError:
(yield inferred)
else:
(yield util.Uninferable)
else:
(yield function_to_method(inferred, self))
except exceptions.AttributeInferenceError as error:
if ((not name.startswith('__')) and self.has_dynamic_getattr(context)):
(yield util.Uninferable)
else:
util.reraise(exceptions.InferenceError(error.message, target=self, attribute=name, context=context))
|
'Check if the current instance has a custom __getattr__
or a custom __getattribute__.
If any such method is found and it is not from
builtins, nor from an extension module, then the function
will return True.'
| def has_dynamic_getattr(self, context=None):
| def _valid_getattr(node):
root = node.root()
return ((root.name != BUILTINS) and getattr(root, 'pure_python', None))
try:
return _valid_getattr(self.getattr('__getattr__', context)[0])
except exceptions.AttributeInferenceError:
try:
getattribute = self.getattr('__getattribute__', context)[0]
return _valid_getattr(getattribute)
except exceptions.AttributeInferenceError:
pass
return False
|
'Return the inference of a subscript.
This is basically looking up the method in the metaclass and calling it.'
| def getitem(self, index, context=None):
| try:
methods = dunder_lookup.lookup(self, '__getitem__')
except exceptions.AttributeInferenceError as exc:
util.reraise(exceptions.AstroidTypeError(node=self, error=exc, context=context))
method = methods[0]
if context:
new_context = context.clone()
else:
new_context = contextmod.InferenceContext()
new_context.callcontext = contextmod.CallContext(args=[index])
new_context.boundnode = self
return next(method.infer_call_result(self, new_context))
|
'return an iterator on all methods defined in the class and
its ancestors'
| def methods(self):
| done = {}
for astroid in itertools.chain(iter((self,)), self.ancestors()):
for meth in astroid.mymethods():
if (meth.name in done):
continue
done[meth.name] = None
(yield meth)
|
'return an iterator on all methods defined in the class'
| def mymethods(self):
| for member in self.values():
if isinstance(member, FunctionDef):
(yield member)
|
'Get the implicit metaclass of the current class
For newstyle classes, this will return an instance of builtins.type.
For oldstyle classes, it will simply return None, since there\'s
no implicit metaclass there.'
| def implicit_metaclass(self):
| if self.newstyle:
return builtin_lookup('type')[1][0]
|
'Return the explicit declared metaclass for the current class.
An explicit declared metaclass is defined
either by passing the ``metaclass`` keyword argument
in the class definition line (Python 3) or (Python 2) by
having a ``__metaclass__`` class attribute, or if there are
no explicit bases but there is a global ``__metaclass__`` variable.'
| def declared_metaclass(self):
| for base in self.bases:
try:
for baseobj in base.infer():
if (isinstance(baseobj, ClassDef) and baseobj.hide):
self._metaclass = baseobj._metaclass
self._metaclass_hack = True
break
except exceptions.InferenceError:
pass
if self._metaclass:
try:
return next((node for node in self._metaclass.infer() if (node is not util.Uninferable)))
except (exceptions.InferenceError, StopIteration):
return None
if six.PY3:
return None
if ('__metaclass__' in self.locals):
assignment = self.locals['__metaclass__'][(-1)]
elif self.bases:
return None
elif ('__metaclass__' in self.root().locals):
assignments = [ass for ass in self.root().locals['__metaclass__'] if (ass.lineno < self.lineno)]
if (not assignments):
return None
assignment = assignments[(-1)]
else:
return None
try:
inferred = next(assignment.infer())
except exceptions.InferenceError:
return
if (inferred is util.Uninferable):
return None
return inferred
|
'Return the metaclass of this class.
If this class does not define explicitly a metaclass,
then the first defined metaclass in ancestors will be used
instead.'
| def metaclass(self):
| return self._find_metaclass()
|
'Return an iterator with the inferred slots.'
| def _islots(self):
| if ('__slots__' not in self.locals):
return
for slots in self.igetattr('__slots__'):
for meth in ITER_METHODS:
try:
slots.getattr(meth)
break
except exceptions.AttributeInferenceError:
continue
else:
continue
if isinstance(slots, node_classes.Const):
if slots.value:
(yield slots)
continue
if (not hasattr(slots, 'itered')):
continue
if isinstance(slots, node_classes.Dict):
values = [item[0] for item in slots.items]
else:
values = slots.itered()
if (values is util.Uninferable):
continue
if (not values):
raise StopIteration(values)
for elt in values:
try:
for inferred in elt.infer():
if (inferred is util.Uninferable):
continue
if ((not isinstance(inferred, node_classes.Const)) or (not isinstance(inferred.value, six.string_types))):
continue
if (not inferred.value):
continue
(yield inferred)
except exceptions.InferenceError:
continue
|
'Get all the slots for this node.
If the class doesn\'t define any slot, through `__slots__`
variable, then this function will return a None.
Also, it will return None in the case the slots weren\'t inferred.
Otherwise, it will return a list of slot names.'
| @decorators_mod.cached
def slots(self):
| def grouped_slots():
for cls in self.mro()[:(-1)]:
try:
cls_slots = cls._slots()
except NotImplementedError:
continue
if (cls_slots is not None):
for slot in cls_slots:
(yield slot)
else:
(yield None)
if (not self.newstyle):
raise NotImplementedError('The concept of slots is undefined for old-style classes.')
slots = list(grouped_slots())
if (not all(((slot is not None) for slot in slots))):
return None
return sorted(slots, key=(lambda item: item.value))
|
'Get the method resolution order, using C3 linearization.
It returns the list of ancestors sorted by the mro.
This will raise `NotImplementedError` for old-style classes, since
they don\'t have the concept of MRO.'
| def mro(self, context=None):
| if (not self.newstyle):
raise NotImplementedError('Could not obtain mro for old-style classes.')
return self._compute_mro(context=context)
|
'Get the MRO which will be used to lookup attributes in this super.'
| def super_mro(self):
| if (not isinstance(self.mro_pointer, scoped_nodes.ClassDef)):
raise exceptions.SuperError('The first argument to super must be a subtype of type, not {mro_pointer}.', super_=self)
if isinstance(self.type, scoped_nodes.ClassDef):
self._class_based = True
mro_type = self.type
else:
mro_type = getattr(self.type, '_proxied', None)
if (not isinstance(mro_type, (bases.Instance, scoped_nodes.ClassDef))):
raise exceptions.SuperError('The second argument to super must be an instance or subtype of type, not {type}.', super_=self)
if (not mro_type.newstyle):
raise exceptions.SuperError('Unable to call super on old-style classes.', super_=self)
mro = mro_type.mro()
if (self.mro_pointer not in mro):
raise exceptions.SuperError('The second argument to super must be an instance or subtype of type, not {type}.', super_=self)
index = mro.index(self.mro_pointer)
return mro[(index + 1):]
|
'Get the name of the MRO pointer.'
| @property
def name(self):
| return self.mro_pointer.name
|
'Retrieve the inferred values of the given attribute name.'
| def igetattr(self, name, context=None):
| if (name in self.special_attributes):
(yield self.special_attributes.lookup(name))
return
try:
mro = self.super_mro()
except exceptions.SuperError as exc:
util.reraise(exceptions.AttributeInferenceError('Lookup for {name} on {target!r} because super call {super!r} is invalid.', target=self, attribute=name, context=context, super_=exc.super_))
except exceptions.MroError as exc:
util.reraise(exceptions.AttributeInferenceError('Lookup for {name} on {target!r} failed because {cls!r} has an invalid MRO.', target=self, attribute=name, context=context, mros=exc.mros, cls=exc.cls))
found = False
for cls in mro:
if (name not in cls.locals):
continue
found = True
for inferred in bases._infer_stmts([cls[name]], context, frame=self):
if (not isinstance(inferred, scoped_nodes.FunctionDef)):
(yield inferred)
continue
if (inferred.type == 'classmethod'):
(yield bases.BoundMethod(inferred, cls))
elif ((self._scope.type == 'classmethod') and (inferred.type == 'method')):
(yield inferred)
elif (self._class_based or (inferred.type == 'staticmethod')):
(yield inferred)
elif bases._is_property(inferred):
for value in inferred.infer_call_result(self, context):
(yield value)
else:
(yield bases.BoundMethod(inferred, cls))
if (not found):
raise exceptions.AttributeInferenceError(target=self, attribute=name, context=context)
|
'Optimize BinOps with string Const nodes on the lhs.
This fixes an infinite recursion crash, where multiple
strings are joined using the addition operator. With a
sufficient number of such strings, astroid will fail
with a maximum recursion limit exceeded. The
function will return a Const node with all the strings
already joined.
Return ``None`` if no AST node can be obtained
through optimization.'
| def optimize_binop(self, node, parent=None):
| ast_nodes = []
current = node
while isinstance(current, _ast.BinOp):
if (not isinstance(current.left, _ast.BinOp)):
return
if ((not isinstance(current.left.op, _ast.Add)) or (not isinstance(current.op, _ast.Add))):
return
if (not isinstance(current.right, _TYPES)):
return
ast_nodes.append(current.right.s)
current = current.left
if (isinstance(current, _ast.BinOp) and isinstance(current.left, _TYPES) and isinstance(current.right, _TYPES)):
ast_nodes.append(current.right.s)
ast_nodes.append(current.left.s)
break
if (not ast_nodes):
return
known = type(ast_nodes[0])
if any(((not isinstance(element, known)) for element in ast_nodes[1:])):
return
value = known().join(reversed(ast_nodes))
newnode = nodes.Const(value, node.lineno, node.col_offset, parent)
return newnode
|
'handle block line numbers range for try/finally, for, if and while
statements'
| def _elsed_block_range(self, lineno, orelse, last=None):
| if (lineno == self.fromlineno):
return (lineno, lineno)
if orelse:
if (lineno >= orelse[0].fromlineno):
return (lineno, orelse[(-1)].tolineno)
return (lineno, (orelse[0].fromlineno - 1))
return (lineno, (last or self.tolineno))
|
'method used in _filter_stmts to get statements and trigger break'
| def _get_filtered_stmts(self, _, node, _stmts, mystmt):
| if (self.statement() is mystmt):
return ([node], True)
return (_stmts, False)
|
'method used in filter_stmts'
| def _get_filtered_stmts(self, lookup_node, node, _stmts, mystmt):
| if (self is mystmt):
return (_stmts, True)
if (self.statement() is mystmt):
return ([node], True)
return (_stmts, False)
|
'return the ast for a module whose name is <modname> imported by <self>'
| def do_import_module(self, modname=None):
| mymodule = self.root()
level = getattr(self, 'level', None)
if (modname is None):
modname = self.modname
if (mymodule.relative_to_absolute_name(modname, level) == mymodule.name):
return mymodule
return mymodule.import_module(modname, level=level, relative_only=(level and (level >= 1)))
|
'get name from \'as\' name'
| def real_name(self, asname):
| for (name, _asname) in self.names:
if (name == '*'):
return asname
if (not _asname):
name = name.split('.', 1)[0]
_asname = name
if (asname == _asname):
return name
raise exceptions.AttributeInferenceError('Could not find original name for {attribute} in {target!r}', target=self, attribute=asname)
|
'Get a CallSite object from the given Call node.'
| @classmethod
def from_call(cls, call_node):
| callcontext = contextmod.CallContext(call_node.args, call_node.keywords)
return cls(callcontext)
|
'Check if in the current CallSite were passed *invalid* arguments
This can mean multiple things. For instance, if an unpacking
of an invalid object was passed, then this method will return True.
Other cases can be when the arguments can\'t be inferred by astroid,
for example, by passing objects which aren\'t known statically.'
| def has_invalid_arguments(self):
| return (len(self.positional_arguments) != len(self._unpacked_args))
|
'Check if in the current CallSite were passed *invalid* keyword arguments
For instance, unpacking a dictionary with integer keys is invalid
(**{1:2}), because the keys must be strings, which will make this
method to return True. Other cases where this might return True if
objects which can\'t be inferred were passed.'
| def has_invalid_keywords(self):
| return (len(self.keyword_arguments) != len(self._unpacked_kwargs))
|
'infer a function argument value according to the call context
Arguments:
funcnode: The function being called.
name: The name of the argument whose value is being inferred.
context: TODO'
| def infer_argument(self, funcnode, name, context):
| if (name in self.duplicated_keywords):
raise exceptions.InferenceError('The arguments passed to {func!r} have duplicate keywords.', call_site=self, func=funcnode, arg=name, context=context)
try:
return self.keyword_arguments[name].infer(context)
except KeyError:
pass
if (len(self.positional_arguments) > len(funcnode.args.args)):
if (not funcnode.args.vararg):
raise exceptions.InferenceError('Too many positional arguments passed to {func!r} that does not have *args.', call_site=self, func=funcnode, arg=name, context=context)
positional = self.positional_arguments[:len(funcnode.args.args)]
vararg = self.positional_arguments[len(funcnode.args.args):]
argindex = funcnode.args.find_argname(name)[0]
kwonlyargs = set((arg.name for arg in funcnode.args.kwonlyargs))
kwargs = {key: value for (key, value) in self.keyword_arguments.items() if (key not in kwonlyargs)}
if (len(positional) < len(funcnode.args.args)):
for func_arg in funcnode.args.args:
if (func_arg.name in kwargs):
arg = kwargs.pop(func_arg.name)
positional.append(arg)
if (argindex is not None):
if ((argindex == 0) and (funcnode.type in ('method', 'classmethod'))):
if (context.boundnode is not None):
boundnode = context.boundnode
else:
boundnode = funcnode.parent.frame()
if isinstance(boundnode, nodes.ClassDef):
method_scope = funcnode.parent.scope()
if (method_scope is boundnode.metaclass()):
return iter((boundnode,))
if (funcnode.type == 'method'):
if (not isinstance(boundnode, bases.Instance)):
boundnode = bases.Instance(boundnode)
return iter((boundnode,))
if (funcnode.type == 'classmethod'):
return iter((boundnode,))
if (funcnode.type in ('method', 'classmethod')):
argindex -= 1
try:
return self.positional_arguments[argindex].infer(context)
except IndexError:
pass
if (funcnode.args.kwarg == name):
if self.has_invalid_keywords():
raise exceptions.InferenceError("Inference failed to find values for all keyword arguments to {func!r}: {unpacked_kwargs!r} doesn't correspond to {keyword_arguments!r}.", keyword_arguments=self.keyword_arguments, unpacked_kwargs=self._unpacked_kwargs, call_site=self, func=funcnode, arg=name, context=context)
kwarg = nodes.Dict(lineno=funcnode.args.lineno, col_offset=funcnode.args.col_offset, parent=funcnode.args)
kwarg.postinit([(nodes.const_factory(key), value) for (key, value) in kwargs.items()])
return iter((kwarg,))
elif (funcnode.args.vararg == name):
if self.has_invalid_arguments():
raise exceptions.InferenceError("Inference failed to find values for all positional arguments to {func!r}: {unpacked_args!r} doesn't correspond to {positional_arguments!r}.", positional_arguments=self.positional_arguments, unpacked_args=self._unpacked_args, call_site=self, func=funcnode, arg=name, context=context)
args = nodes.Tuple(lineno=funcnode.args.lineno, col_offset=funcnode.args.col_offset, parent=funcnode.args)
args.postinit(vararg)
return iter((args,))
try:
return funcnode.args.default_value(name).infer(context)
except exceptions.NoDefault:
pass
raise exceptions.InferenceError('No value found for argument {name} to {func!r}', call_site=self, func=funcnode, arg=name, context=context)
|
'visit a Module node by returning a fresh instance of it'
| def visit_module(self, node, modname, modpath, package):
| (node, doc) = _get_doc(node)
newnode = nodes.Module(name=modname, doc=doc, file=modpath, path=modpath, package=package, parent=None)
newnode.postinit([self.visit(child, newnode) for child in node.body])
return newnode
|
'save assignement situation since node.parent is not available yet'
| def _save_assignment(self, node, name=None):
| if (self._global_names and (node.name in self._global_names[(-1)])):
node.root().set_local(node.name, node)
else:
node.parent.set_local(node.name, node)
|
'visit a Arguments node by returning a fresh instance of it'
| def visit_arguments(self, node, parent):
| (vararg, kwarg) = (node.vararg, node.kwarg)
if PY34:
newnode = nodes.Arguments((vararg.arg if vararg else None), (kwarg.arg if kwarg else None), parent)
else:
newnode = nodes.Arguments(vararg, kwarg, parent)
args = [self.visit(child, newnode) for child in node.args]
defaults = [self.visit(child, newnode) for child in node.defaults]
varargannotation = None
kwargannotation = None
if vararg:
if PY34:
if node.vararg.annotation:
varargannotation = self.visit(node.vararg.annotation, newnode)
vararg = vararg.arg
elif (PY3 and node.varargannotation):
varargannotation = self.visit(node.varargannotation, newnode)
if kwarg:
if PY34:
if node.kwarg.annotation:
kwargannotation = self.visit(node.kwarg.annotation, newnode)
kwarg = kwarg.arg
elif PY3:
if node.kwargannotation:
kwargannotation = self.visit(node.kwargannotation, newnode)
if PY3:
kwonlyargs = [self.visit(child, newnode) for child in node.kwonlyargs]
kw_defaults = [(self.visit(child, newnode) if child else None) for child in node.kw_defaults]
annotations = [(self.visit(arg.annotation, newnode) if arg.annotation else None) for arg in node.args]
kwonlyargs_annotations = [(self.visit(arg.annotation, newnode) if arg.annotation else None) for arg in node.kwonlyargs]
else:
kwonlyargs = []
kw_defaults = []
annotations = []
kwonlyargs_annotations = []
newnode.postinit(args=args, defaults=defaults, kwonlyargs=kwonlyargs, kw_defaults=kw_defaults, annotations=annotations, kwonlyargs_annotations=kwonlyargs_annotations, varargannotation=varargannotation, kwargannotation=kwargannotation)
if vararg:
newnode.parent.set_local(vararg, newnode)
if kwarg:
newnode.parent.set_local(kwarg, newnode)
return newnode
|
'visit a Assert node by returning a fresh instance of it'
| def visit_assert(self, node, parent):
| newnode = nodes.Assert(node.lineno, node.col_offset, parent)
if node.msg:
msg = self.visit(node.msg, newnode)
else:
msg = None
newnode.postinit(self.visit(node.test, newnode), msg)
return newnode
|
'visit a Assign node by returning a fresh instance of it'
| def visit_assign(self, node, parent):
| newnode = nodes.Assign(node.lineno, node.col_offset, parent)
newnode.postinit([self.visit(child, newnode) for child in node.targets], self.visit(node.value, newnode))
return newnode
|
'visit a node and return a AssignName node'
| def visit_assignname(self, node, parent, node_name=None):
| newnode = nodes.AssignName(node_name, getattr(node, 'lineno', None), getattr(node, 'col_offset', None), parent)
self._save_assignment(newnode)
return newnode
|
'visit a AugAssign node by returning a fresh instance of it'
| def visit_augassign(self, node, parent):
| newnode = nodes.AugAssign((_BIN_OP_CLASSES[type(node.op)] + '='), node.lineno, node.col_offset, parent)
newnode.postinit(self.visit(node.target, newnode), self.visit(node.value, newnode))
return newnode
|
'visit a Backquote node by returning a fresh instance of it'
| def visit_repr(self, node, parent):
| newnode = nodes.Repr(node.lineno, node.col_offset, parent)
newnode.postinit(self.visit(node.value, newnode))
return newnode
|
'visit a BinOp node by returning a fresh instance of it'
| def visit_binop(self, node, parent):
| if (isinstance(node.left, _ast.BinOp) and self._manager.optimize_ast):
optimized = self._peepholer.optimize_binop(node, parent)
if optimized:
return optimized
newnode = nodes.BinOp(_BIN_OP_CLASSES[type(node.op)], node.lineno, node.col_offset, parent)
newnode.postinit(self.visit(node.left, newnode), self.visit(node.right, newnode))
return newnode
|
'visit a BoolOp node by returning a fresh instance of it'
| def visit_boolop(self, node, parent):
| newnode = nodes.BoolOp(_BOOL_OP_CLASSES[type(node.op)], node.lineno, node.col_offset, parent)
newnode.postinit([self.visit(child, newnode) for child in node.values])
return newnode
|
'visit a Break node by returning a fresh instance of it'
| def visit_break(self, node, parent):
| return nodes.Break(getattr(node, 'lineno', None), getattr(node, 'col_offset', None), parent)
|
'visit a CallFunc node by returning a fresh instance of it'
| def visit_call(self, node, parent):
| newnode = nodes.Call(node.lineno, node.col_offset, parent)
starargs = _visit_or_none(node, 'starargs', self, newnode)
kwargs = _visit_or_none(node, 'kwargs', self, newnode)
args = [self.visit(child, newnode) for child in node.args]
if node.keywords:
keywords = [self.visit(child, newnode) for child in node.keywords]
else:
keywords = None
if starargs:
new_starargs = nodes.Starred(col_offset=starargs.col_offset, lineno=starargs.lineno, parent=starargs.parent)
new_starargs.postinit(value=starargs)
args.append(new_starargs)
if kwargs:
new_kwargs = nodes.Keyword(arg=None, col_offset=kwargs.col_offset, lineno=kwargs.lineno, parent=kwargs.parent)
new_kwargs.postinit(value=kwargs)
if keywords:
keywords.append(new_kwargs)
else:
keywords = [new_kwargs]
newnode.postinit(self.visit(node.func, newnode), args, keywords)
return newnode
|
'visit a ClassDef node to become astroid'
| def visit_classdef(self, node, parent, newstyle=None):
| (node, doc) = _get_doc(node)
newnode = nodes.ClassDef(node.name, doc, node.lineno, node.col_offset, parent)
metaclass = None
if PY3:
for keyword in node.keywords:
if (keyword.arg == 'metaclass'):
metaclass = self.visit(keyword, newnode).value
break
if node.decorator_list:
decorators = self.visit_decorators(node, newnode)
else:
decorators = None
newnode.postinit([self.visit(child, newnode) for child in node.bases], [self.visit(child, newnode) for child in node.body], decorators, newstyle, metaclass, ([self.visit(kwd, newnode) for kwd in node.keywords if (kwd.arg != 'metaclass')] if PY3 else []))
return newnode
|
'visit a Const node by returning a fresh instance of it'
| def visit_const(self, node, parent):
| return nodes.Const(node.value, getattr(node, 'lineno', None), getattr(node, 'col_offset', None), parent)
|
'visit a Continue node by returning a fresh instance of it'
| def visit_continue(self, node, parent):
| return nodes.Continue(getattr(node, 'lineno', None), getattr(node, 'col_offset', None), parent)
|
'visit a Compare node by returning a fresh instance of it'
| def visit_compare(self, node, parent):
| newnode = nodes.Compare(node.lineno, node.col_offset, parent)
newnode.postinit(self.visit(node.left, newnode), [(_CMP_OP_CLASSES[op.__class__], self.visit(expr, newnode)) for (op, expr) in zip(node.ops, node.comparators)])
return newnode
|
'visit a Comprehension node by returning a fresh instance of it'
| def visit_comprehension(self, node, parent):
| 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
|
'visit a Decorators node by returning a fresh instance of it'
| def visit_decorators(self, node, parent):
| newnode = nodes.Decorators(node.lineno, node.col_offset, parent)
newnode.postinit([self.visit(child, newnode) for child in node.decorator_list])
return newnode
|
'visit a Delete node by returning a fresh instance of it'
| def visit_delete(self, node, parent):
| newnode = nodes.Delete(node.lineno, node.col_offset, parent)
newnode.postinit([self.visit(child, newnode) for child in node.targets])
return newnode
|
'visit a Dict node by returning a fresh instance of it'
| def visit_dict(self, node, parent):
| newnode = nodes.Dict(node.lineno, node.col_offset, parent)
items = list(self._visit_dict_items(node, parent, newnode))
newnode.postinit(items)
return newnode
|
'visit a DictComp node by returning a fresh instance of it'
| def visit_dictcomp(self, node, parent):
| 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
|
'visit a Expr node by returning a fresh instance of it'
| def visit_expr(self, node, parent):
| newnode = nodes.Expr(node.lineno, node.col_offset, parent)
newnode.postinit(self.visit(node.value, newnode))
return newnode
|
'visit an Ellipsis node by returning a fresh instance of it'
| def visit_ellipsis(self, node, parent):
| return nodes.Ellipsis(getattr(node, 'lineno', None), getattr(node, 'col_offset', None), parent)
|
'visit an EmptyNode node by returning a fresh instance of it'
| def visit_emptynode(self, node, parent):
| return nodes.EmptyNode(getattr(node, 'lineno', None), getattr(node, 'col_offset', None), parent)
|
'visit an ExceptHandler node by returning a fresh instance of it'
| def visit_excepthandler(self, node, parent):
| newnode = nodes.ExceptHandler(node.lineno, node.col_offset, parent)
newnode.postinit(_visit_or_none(node, 'type', self, newnode), _visit_or_none(node, 'name', self, newnode), [self.visit(child, newnode) for child in node.body])
return newnode
|
'visit an Exec node by returning a fresh instance of it'
| def visit_exec(self, node, parent):
| 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
|
'visit an ExtSlice node by returning a fresh instance of it'
| def visit_extslice(self, node, parent):
| newnode = nodes.ExtSlice(parent=parent)
newnode.postinit([self.visit(dim, newnode) for dim in node.dims])
return newnode
|
'visit a For node by returning a fresh instance of it'
| def _visit_for(self, cls, node, parent):
| newnode = cls(node.lineno, node.col_offset, parent)
newnode.postinit(self.visit(node.target, newnode), self.visit(node.iter, newnode), [self.visit(child, newnode) for child in node.body], [self.visit(child, newnode) for child in node.orelse])
return newnode
|
'visit an ImportFrom node by returning a fresh instance of it'
| def visit_importfrom(self, node, parent):
| 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)
self._import_from_nodes.append(newnode)
return newnode
|
'visit an FunctionDef node to become astroid'
| def _visit_functiondef(self, cls, node, parent):
| self._global_names.append({})
(node, doc) = _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
newnode.postinit(self.visit(node.args, newnode), [self.visit(child, newnode) for child in node.body], decorators, returns)
self._global_names.pop()
return newnode
|
'visit a GeneratorExp node by returning a fresh instance of it'
| def visit_generatorexp(self, node, parent):
| 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
|
'visit an Attribute node by returning a fresh instance of it'
| def visit_attribute(self, node, parent):
| context = _get_context(node)
if (context == astroid.Del):
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)
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
|
'visit a Global node to become astroid'
| def visit_global(self, node, parent):
| newnode = nodes.Global(node.names, getattr(node, 'lineno', None), getattr(node, 'col_offset', None), parent)
if self._global_names:
for name in node.names:
self._global_names[(-1)].setdefault(name, []).append(newnode)
return newnode
|
'visit an If node by returning a fresh instance of it'
| def visit_if(self, node, parent):
| 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
|
'visit a IfExp node by returning a fresh instance of it'
| def visit_ifexp(self, node, parent):
| 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
|
'visit a Import node by returning a fresh instance of it'
| def visit_import(self, node, parent):
| names = [(alias.name, alias.asname) for alias in node.names]
newnode = nodes.Import(names, getattr(node, 'lineno', None), getattr(node, 'col_offset', None), parent)
for (name, asname) in newnode.names:
name = (asname or name)
parent.set_local(name.split('.')[0], newnode)
return newnode
|
'visit a Index node by returning a fresh instance of it'
| def visit_index(self, node, parent):
| newnode = nodes.Index(parent=parent)
newnode.postinit(self.visit(node.value, newnode))
return newnode
|
'visit a Keyword node by returning a fresh instance of it'
| def visit_keyword(self, node, parent):
| newnode = nodes.Keyword(node.arg, parent=parent)
newnode.postinit(self.visit(node.value, newnode))
return newnode
|
'visit a Lambda node by returning a fresh instance of it'
| def visit_lambda(self, node, parent):
| newnode = nodes.Lambda(node.lineno, node.col_offset, parent)
newnode.postinit(self.visit(node.args, newnode), self.visit(node.body, newnode))
return newnode
|
'visit a List node by returning a fresh instance of it'
| def visit_list(self, node, parent):
| context = _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
|
'visit a ListComp node by returning a fresh instance of it'
| def visit_listcomp(self, node, parent):
| 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
|
'visit a Name node by returning a fresh instance of it'
| def visit_name(self, node, parent):
| context = _get_context(node)
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)
if (context in (astroid.Del, astroid.Store)):
self._save_assignment(newnode)
return newnode
|
'visit a String/Bytes node by returning a fresh instance of Const'
| def visit_str(self, node, parent):
| return nodes.Const(node.s, getattr(node, 'lineno', None), getattr(node, 'col_offset', None), parent)
|
'visit a Num node by returning a fresh instance of Const'
| def visit_num(self, node, parent):
| return nodes.Const(node.n, getattr(node, 'lineno', None), getattr(node, 'col_offset', None), parent)
|
'visit a Pass node by returning a fresh instance of it'
| def visit_pass(self, node, parent):
| return nodes.Pass(node.lineno, node.col_offset, parent)
|
'visit a Print node by returning a fresh instance of it'
| def visit_print(self, node, parent):
| 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
|
'visit a Raise node by returning a fresh instance of it'
| def visit_raise(self, node, parent):
| newnode = nodes.Raise(node.lineno, node.col_offset, parent)
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
|
'visit a Return node by returning a fresh instance of it'
| def visit_return(self, node, parent):
| newnode = nodes.Return(node.lineno, node.col_offset, parent)
if (node.value is not None):
newnode.postinit(self.visit(node.value, newnode))
return newnode
|
'visit a Set node by returning a fresh instance of it'
| def visit_set(self, node, parent):
| newnode = nodes.Set(node.lineno, node.col_offset, parent)
newnode.postinit([self.visit(child, newnode) for child in node.elts])
return newnode
|
'visit a SetComp node by returning a fresh instance of it'
| def visit_setcomp(self, node, parent):
| 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
|
'visit a Slice node by returning a fresh instance of it'
| def visit_slice(self, node, parent):
| 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
|
'visit a Subscript node by returning a fresh instance of it'
| def visit_subscript(self, node, parent):
| context = _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
|
'visit a TryExcept node by returning a fresh instance of it'
| def visit_tryexcept(self, node, parent):
| 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
|
'visit a TryFinally node by returning a fresh instance of it'
| def visit_tryfinally(self, node, parent):
| 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
|
'visit a Tuple node by returning a fresh instance of it'
| def visit_tuple(self, node, parent):
| context = _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
|
'visit a UnaryOp node by returning a fresh instance of it'
| def visit_unaryop(self, node, parent):
| newnode = nodes.UnaryOp(_UNARY_OP_CLASSES[node.op.__class__], node.lineno, node.col_offset, parent)
newnode.postinit(self.visit(node.operand, newnode))
return newnode
|
'visit a While node by returning a fresh instance of it'
| def visit_while(self, node, parent):
| 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
|
'visit a Yield node by returning a fresh instance of it'
| def visit_yield(self, node, parent):
| newnode = nodes.Yield(node.lineno, node.col_offset, parent)
if (node.value is not None):
newnode.postinit(self.visit(node.value, newnode))
return newnode
|
'visit a arg node by returning a fresh AssName instance'
| def visit_arg(self, node, parent):
| return self.visit_assignname(node, parent, node.arg)
|
'visit an ExceptHandler node by returning a fresh instance of it'
| def visit_excepthandler(self, node, parent):
| 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
|
'visit a Nonlocal node and return a new instance of it'
| def visit_nonlocal(self, node, parent):
| return nodes.Nonlocal(node.names, getattr(node, 'lineno', None), getattr(node, 'col_offset', None), parent)
|
'visit a Raise node by returning a fresh instance of it'
| def visit_raise(self, node, parent):
| newnode = nodes.Raise(node.lineno, node.col_offset, parent)
newnode.postinit(_visit_or_none(node, 'exc', self, newnode), _visit_or_none(node, 'cause', self, newnode))
return newnode
|
'visit a Starred node and return a new instance of it'
| def visit_starred(self, node, parent):
| context = _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
|
'visit an AnnAssign node by returning a fresh instance of it'
| def visit_annassign(self, node, parent):
| 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
|
'Makes this visitor behave as a simple function'
| def __call__(self, node):
| return node.accept(self)
|
'return a list of nodes to string'
| def _stmt_list(self, stmts):
| stmts = '\n'.join([nstr for nstr in [n.accept(self) for n in stmts] if nstr])
return (self.indent + stmts.replace('\n', ('\n' + self.indent)))
|
'return an astroid.Function node as string'
| def visit_arguments(self, node):
| return node.format_args()
|
'return an astroid.AssAttr node as string'
| def visit_assignattr(self, node):
| return self.visit_attribute(node)
|
'return an astroid.Assert node as string'
| def visit_assert(self, node):
| if node.fail:
return ('assert %s, %s' % (node.test.accept(self), node.fail.accept(self)))
return ('assert %s' % node.test.accept(self))
|
'return an astroid.AssName node as string'
| def visit_assignname(self, node):
| return node.name
|
'return an astroid.Assign node as string'
| def visit_assign(self, node):
| lhs = ' = '.join([n.accept(self) for n in node.targets])
return ('%s = %s' % (lhs, node.value.accept(self)))
|
'return an astroid.AugAssign node as string'
| def visit_augassign(self, node):
| return ('%s %s %s' % (node.target.accept(self), node.op, node.value.accept(self)))
|
'Return an astroid.AugAssign node as string'
| def visit_annassign(self, node):
| target = node.target.accept(self)
annotation = node.annotation.accept(self)
if (node.value is None):
return ('%s: %s' % (target, annotation))
return ('%s: %s = %s' % (target, annotation, node.value.accept(self)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.