desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'return an astroid.Repr node as string'
| def visit_repr(self, node):
| return ('`%s`' % node.value.accept(self))
|
'return an astroid.BinOp node as string'
| def visit_binop(self, node):
| return ('(%s) %s (%s)' % (node.left.accept(self), node.op, node.right.accept(self)))
|
'return an astroid.BoolOp node as string'
| def visit_boolop(self, node):
| return (' %s ' % node.op).join([('(%s)' % n.accept(self)) for n in node.values])
|
'return an astroid.Break node as string'
| def visit_break(self, node):
| return 'break'
|
'return an astroid.Call node as string'
| def visit_call(self, node):
| expr_str = node.func.accept(self)
args = [arg.accept(self) for arg in node.args]
if node.keywords:
keywords = [kwarg.accept(self) for kwarg in node.keywords]
else:
keywords = []
args.extend(keywords)
return ('%s(%s)' % (expr_str, ', '.join(args)))
|
'return an astroid.ClassDef node as string'
| def visit_classdef(self, node):
| decorate = (node.decorators.accept(self) if node.decorators else '')
bases = ', '.join([n.accept(self) for n in node.bases])
if (sys.version_info[0] == 2):
bases = (('(%s)' % bases) if bases else '')
else:
metaclass = node.metaclass()
if (metaclass and (not node.has_metaclass_... |
'return an astroid.Compare node as string'
| def visit_compare(self, node):
| rhs_str = ' '.join([('%s %s' % (op, expr.accept(self))) for (op, expr) in node.ops])
return ('%s %s' % (node.left.accept(self), rhs_str))
|
'return an astroid.Comprehension node as string'
| def visit_comprehension(self, node):
| ifs = ''.join([(' if %s' % n.accept(self)) for n in node.ifs])
return ('for %s in %s%s' % (node.target.accept(self), node.iter.accept(self), ifs))
|
'return an astroid.Const node as string'
| def visit_const(self, node):
| return repr(node.value)
|
'return an astroid.Continue node as string'
| def visit_continue(self, node):
| return 'continue'
|
'return an astroid.Delete node as string'
| def visit_delete(self, node):
| return ('del %s' % ', '.join([child.accept(self) for child in node.targets]))
|
'return an astroid.DelAttr node as string'
| def visit_delattr(self, node):
| return self.visit_attribute(node)
|
'return an astroid.DelName node as string'
| def visit_delname(self, node):
| return node.name
|
'return an astroid.Decorators node as string'
| def visit_decorators(self, node):
| return ('@%s\n' % '\n@'.join([item.accept(self) for item in node.nodes]))
|
'return an astroid.Dict node as string'
| def visit_dict(self, node):
| return ('{%s}' % ', '.join(self._visit_dict(node)))
|
'return an astroid.DictComp node as string'
| def visit_dictcomp(self, node):
| return ('{%s: %s %s}' % (node.key.accept(self), node.value.accept(self), ' '.join([n.accept(self) for n in node.generators])))
|
'return an astroid.Discard node as string'
| def visit_expr(self, node):
| return node.value.accept(self)
|
'dummy method for visiting an Empty node'
| def visit_emptynode(self, node):
| return ''
|
'return an astroid.Ellipsis node as string'
| def visit_ellipsis(self, node):
| return '...'
|
'return an Empty node as string'
| def visit_empty(self, node):
| return ''
|
'return an astroid.Exec node as string'
| def visit_exec(self, node):
| if node.locals:
return ('exec %s in %s, %s' % (node.expr.accept(self), node.locals.accept(self), node.globals.accept(self)))
if node.globals:
return ('exec %s in %s' % (node.expr.accept(self), node.globals.accept(self)))
return ('exec %s' % node.expr.accept(self))
|
'return an astroid.ExtSlice node as string'
| def visit_extslice(self, node):
| return ','.join([dim.accept(self) for dim in node.dims])
|
'return an astroid.For node as string'
| def visit_for(self, node):
| fors = ('for %s in %s:\n%s' % (node.target.accept(self), node.iter.accept(self), self._stmt_list(node.body)))
if node.orelse:
fors = ('%s\nelse:\n%s' % (fors, self._stmt_list(node.orelse)))
return fors
|
'return an astroid.ImportFrom node as string'
| def visit_importfrom(self, node):
| return ('from %s import %s' % ((('.' * (node.level or 0)) + node.modname), _import_string(node.names)))
|
'return an astroid.Function node as string'
| def visit_functiondef(self, node):
| decorate = (node.decorators.accept(self) if node.decorators else '')
docs = (('\n%s"""%s"""' % (self.indent, node.doc)) if node.doc else '')
return_annotation = ''
if (six.PY3 and node.returns):
return_annotation = ('->' + node.returns.as_string())
trailer = (return_annotation + ':')
... |
'return an astroid.GeneratorExp node as string'
| def visit_generatorexp(self, node):
| return ('(%s %s)' % (node.elt.accept(self), ' '.join([n.accept(self) for n in node.generators])))
|
'return an astroid.Getattr node as string'
| def visit_attribute(self, node):
| return ('%s.%s' % (node.expr.accept(self), node.attrname))
|
'return an astroid.Global node as string'
| def visit_global(self, node):
| return ('global %s' % ', '.join(node.names))
|
'return an astroid.If node as string'
| def visit_if(self, node):
| ifs = [('if %s:\n%s' % (node.test.accept(self), self._stmt_list(node.body)))]
if node.orelse:
ifs.append(('else:\n%s' % self._stmt_list(node.orelse)))
return '\n'.join(ifs)
|
'return an astroid.IfExp node as string'
| def visit_ifexp(self, node):
| return ('%s if %s else %s' % (node.body.accept(self), node.test.accept(self), node.orelse.accept(self)))
|
'return an astroid.Import node as string'
| def visit_import(self, node):
| return ('import %s' % _import_string(node.names))
|
'return an astroid.Keyword node as string'
| def visit_keyword(self, node):
| if (node.arg is None):
return ('**%s' % node.value.accept(self))
return ('%s=%s' % (node.arg, node.value.accept(self)))
|
'return an astroid.Lambda node as string'
| def visit_lambda(self, node):
| return ('lambda %s: %s' % (node.args.accept(self), node.body.accept(self)))
|
'return an astroid.List node as string'
| def visit_list(self, node):
| return ('[%s]' % ', '.join([child.accept(self) for child in node.elts]))
|
'return an astroid.ListComp node as string'
| def visit_listcomp(self, node):
| return ('[%s %s]' % (node.elt.accept(self), ' '.join([n.accept(self) for n in node.generators])))
|
'return an astroid.Module node as string'
| def visit_module(self, node):
| docs = (('"""%s"""\n\n' % node.doc) if node.doc else '')
return ((docs + '\n'.join([n.accept(self) for n in node.body])) + '\n\n')
|
'return an astroid.Name node as string'
| def visit_name(self, node):
| return node.name
|
'return an astroid.Pass node as string'
| def visit_pass(self, node):
| return 'pass'
|
'return an astroid.Print node as string'
| def visit_print(self, node):
| nodes = ', '.join([n.accept(self) for n in node.values])
if (not node.nl):
nodes = ('%s,' % nodes)
if node.dest:
return ('print >> %s, %s' % (node.dest.accept(self), nodes))
return ('print %s' % nodes)
|
'return an astroid.Raise node as string'
| def visit_raise(self, node):
| if node.exc:
if node.inst:
if node.tback:
return ('raise %s, %s, %s' % (node.exc.accept(self), node.inst.accept(self), node.tback.accept(self)))
return ('raise %s, %s' % (node.exc.accept(self), node.inst.accept(self)))
return ('raise %s' % no... |
'return an astroid.Return node as string'
| def visit_return(self, node):
| if node.value:
return ('return %s' % node.value.accept(self))
return 'return'
|
'return a astroid.Index node as string'
| def visit_index(self, node):
| return node.value.accept(self)
|
'return an astroid.Set node as string'
| def visit_set(self, node):
| return ('{%s}' % ', '.join([child.accept(self) for child in node.elts]))
|
'return an astroid.SetComp node as string'
| def visit_setcomp(self, node):
| return ('{%s %s}' % (node.elt.accept(self), ' '.join([n.accept(self) for n in node.generators])))
|
'return a astroid.Slice node as string'
| def visit_slice(self, node):
| lower = (node.lower.accept(self) if node.lower else '')
upper = (node.upper.accept(self) if node.upper else '')
step = (node.step.accept(self) if node.step else '')
if step:
return ('%s:%s:%s' % (lower, upper, step))
return ('%s:%s' % (lower, upper))
|
'return an astroid.Subscript node as string'
| def visit_subscript(self, node):
| return ('%s[%s]' % (node.value.accept(self), node.slice.accept(self)))
|
'return an astroid.TryExcept node as string'
| def visit_tryexcept(self, node):
| trys = [('try:\n%s' % self._stmt_list(node.body))]
for handler in node.handlers:
trys.append(handler.accept(self))
if node.orelse:
trys.append(('else:\n%s' % self._stmt_list(node.orelse)))
return '\n'.join(trys)
|
'return an astroid.TryFinally node as string'
| def visit_tryfinally(self, node):
| return ('try:\n%s\nfinally:\n%s' % (self._stmt_list(node.body), self._stmt_list(node.finalbody)))
|
'return an astroid.Tuple node as string'
| def visit_tuple(self, node):
| if (len(node.elts) == 1):
return ('(%s, )' % node.elts[0].accept(self))
return ('(%s)' % ', '.join([child.accept(self) for child in node.elts]))
|
'return an astroid.UnaryOp node as string'
| def visit_unaryop(self, node):
| if (node.op == 'not'):
operator = 'not '
else:
operator = node.op
return ('%s%s' % (operator, node.operand.accept(self)))
|
'return an astroid.While node as string'
| def visit_while(self, node):
| whiles = ('while %s:\n%s' % (node.test.accept(self), self._stmt_list(node.body)))
if node.orelse:
whiles = ('%s\nelse:\n%s' % (whiles, self._stmt_list(node.orelse)))
return whiles
|
'return an astroid.With node as string'
| def visit_with(self, node):
| items = ', '.join(((('(%s)' % expr.accept(self)) + ((vars and (' as (%s)' % vars.accept(self))) or '')) for (expr, vars) in node.items))
return ('with %s:\n%s' % (items, self._stmt_list(node.body)))
|
'yield an ast.Yield node as string'
| def visit_yield(self, node):
| yi_val = ((' ' + node.value.accept(self)) if node.value else '')
expr = ('yield' + yi_val)
if node.parent.is_statement:
return expr
return ('(%s)' % (expr,))
|
'return Starred node as string'
| def visit_starred(self, node):
| return ('*' + node.value.accept(self))
|
'return an astroid.Nonlocal node as string'
| def visit_nonlocal(self, node):
| return ('nonlocal %s' % ', '.join(node.names))
|
'return an astroid.Raise node as string'
| def visit_raise(self, node):
| if node.exc:
if node.cause:
return ('raise %s from %s' % (node.exc.accept(self), node.cause.accept(self)))
return ('raise %s' % node.exc.accept(self))
return 'raise'
|
'Return an astroid.YieldFrom node as string.'
| def visit_yieldfrom(self, node):
| yi_val = ((' ' + node.value.accept(self)) if node.value else '')
expr = ('yield from' + yi_val)
if node.parent.is_statement:
return expr
return ('(%s)' % (expr,))
|
'return an astroid.Comprehension node as string'
| def visit_comprehension(self, node):
| return ('%s%s' % (('async ' if node.is_async else ''), super(AsStringVisitor3, self).visit_comprehension(node)))
|
'Visit the transforms and apply them to the given *node*.'
| def visit_transforms(self, node):
| return self._transform.visit(node)
|
'given a module name, return the astroid object'
| def ast_from_file(self, filepath, modname=None, fallback=True, source=False):
| try:
filepath = modutils.get_source_file(filepath, include_no_ext=True)
source = True
except modutils.NoSourceFile:
pass
if (modname is None):
try:
modname = '.'.join(modutils.modpath_from_file(filepath))
except ImportError:
modname = filepath
... |
'given a module name, return the astroid object'
| def ast_from_module_name(self, modname, context_file=None):
| if (modname in self.astroid_cache):
return self.astroid_cache[modname]
if (modname == '__main__'):
return self._build_stub_module(modname)
old_cwd = os.getcwd()
if context_file:
os.chdir(os.path.dirname(context_file))
try:
found_spec = self.file_from_module_name(modna... |
'given an imported module, return the astroid object'
| def ast_from_module(self, module, modname=None):
| modname = (modname or module.__name__)
if (modname in self.astroid_cache):
return self.astroid_cache[modname]
try:
filepath = module.__file__
if modutils.is_python_source(filepath):
return self.ast_from_file(filepath, modname)
except AttributeError:
pass
f... |
'get astroid for the given class'
| def ast_from_class(self, klass, modname=None):
| if (modname is None):
try:
modname = klass.__module__
except AttributeError:
util.reraise(exceptions.AstroidBuildingError('Unable to get module for class {class_name}.', cls=klass, class_repr=safe_repr(klass), modname=modname))
modastroid = self.ast_from... |
'infer astroid for the given class'
| def infer_ast_from_something(self, obj, context=None):
| if (hasattr(obj, '__class__') and (not isinstance(obj, type))):
klass = obj.__class__
else:
klass = obj
try:
modname = klass.__module__
except AttributeError:
util.reraise(exceptions.AstroidBuildingError('Unable to get module for {class_repr}.', cls=klass, ... |
'Registers a hook to resolve imports that cannot be found otherwise.
`hook` must be a function that accepts a single argument `modname` which
contains the name of the module or package that could not be imported.
If `hook` can resolve the import, must return a node of type `astroid.Module`,
otherwise, it must raise `As... | def register_failed_import_hook(self, hook):
| self._failed_import_hooks.append(hook)
|
'Cache a module if no module with the same name is known yet.'
| def cache_module(self, module):
| self.astroid_cache.setdefault(module.name, module)
|
'Get the attributes which are exported by this object model.'
| @lru_cache(maxsize=None)
def attributes(self):
| return [obj[2:] for obj in dir(self) if obj.startswith('py')]
|
'Look up the given *name* in the current model
It should return an AST or an interpreter object,
but if the name is not found, then an AttributeInferenceError will be raised.'
| def lookup(self, name):
| if (name in self.attributes()):
return getattr(self, ('py' + name))
raise exceptions.AttributeInferenceError(target=self._instance, attribute=name)
|
'Get the subclasses of the underlying class
This looks only in the current module for retrieving the subclasses,
thus it might miss a couple of them.'
| @property
def py__subclasses__(self):
| from astroid import bases
from astroid import scoped_nodes
if (not self._instance.newstyle):
raise exceptions.AttributeInferenceError(target=self._instance, attribute='__subclasses__')
qname = self._instance.qname()
root = self._instance.root()
classes = [cls for cls in root.nodes_of_cla... |
'Generate a bound method that can infer the given *obj*.'
| def _generic_dict_attribute(self, obj, name):
| class DictMethodBoundMethod(astroid.BoundMethod, ):
def infer_call_result(self, caller, context=None):
(yield obj)
meth = next(self._instance._proxied.igetattr(name))
return DictMethodBoundMethod(proxy=meth, bound=self._instance)
|
'inferred getattr'
| def igetattr(self, name, context=None):
| if (not context):
context = contextmod.InferenceContext()
try:
if context.push((self._proxied, name)):
return
get_attr = self.getattr(name, context, lookupclass=False)
for stmt in _infer_stmts(self._wrap_attr(get_attr, context), context, frame=self):
(yiel... |
'wrap bound methods of attrs in a InstanceMethod proxies'
| def _wrap_attr(self, attrs, context=None):
| for attr in attrs:
if isinstance(attr, UnboundMethod):
if _is_property(attr):
for inferred in attr.infer_call_result(self, context):
(yield inferred)
else:
(yield BoundMethod(attr, self))
elif (hasattr(attr, 'name') and (att... |
'infer what a class instance is returning when called'
| def infer_call_result(self, caller, context=None):
| inferred = False
for node in self._proxied.igetattr('__call__', context):
if ((node is util.Uninferable) or (not node.callable())):
continue
for res in node.infer_call_result(caller, context):
inferred = True
(yield res)
if (not inferred):
raise ex... |
'Infer the truth value for an Instance
The truth value of an instance is determined by these conditions:
* if it implements __bool__ on Python 3 or __nonzero__
on Python 2, then its bool value will be determined by
calling this special method and checking its result.
* when this method is not defined, __len__() is call... | def bool_value(self):
| context = contextmod.InferenceContext()
context.callcontext = contextmod.CallContext(args=[])
context.boundnode = self
try:
result = _infer_method_result_truth(self, BOOL_SPECIAL_METHOD, context)
except (exceptions.InferenceError, exceptions.AttributeInferenceError):
try:
... |
'Try to infer what type.__new__(mcs, name, bases, attrs) returns.
In order for such call to be valid, the metaclass needs to be
a subtype of ``type``, the name needs to be a string, the bases
needs to be a tuple of classes and the attributes a dictionary
of strings to values.'
| def _infer_type_new_call(self, caller, context):
| from astroid import node_classes
mcs = next(caller.args[0].infer(context=context))
if (mcs.__class__.__name__ != 'ClassDef'):
return
if (not mcs.is_subtype_of(('%s.type' % BUILTINS))):
return
name = next(caller.args[1].infer(context=context))
if (name.__class__.__name__ != 'Const... |
'main interface to the interface system, return a generator on inferred
values.
If the instance has some explicit inference function set, it will be
called instead of the default interface.'
| def infer(self, context=None, **kwargs):
| if (self._explicit_inference is not None):
try:
return self._explicit_inference(self, context, **kwargs)
except exceptions.UseInferenceDefault:
pass
if (not context):
return self._infer(context, **kwargs)
key = (self, context.lookupname, context.callcontext, c... |
'return self.name or self.attrname or \'\' for nice representation'
| def _repr_name(self):
| return getattr(self, 'name', getattr(self, 'attrname', ''))
|
'an optimized version of list(get_children())[-1]'
| def last_child(self):
| for field in self._astroid_fields[::(-1)]:
attr = getattr(self, field)
if (not attr):
continue
if isinstance(attr, (list, tuple)):
return attr[(-1)]
return attr
return None
|
'return true if i\'m a parent of the given node'
| def parent_of(self, node):
| parent = node.parent
while (parent is not None):
if (self is parent):
return True
parent = parent.parent
return False
|
'return the first parent node marked as statement node'
| def statement(self):
| if self.is_statement:
return self
return self.parent.statement()
|
'return the first parent frame node (i.e. Module, FunctionDef or
ClassDef)'
| def frame(self):
| return self.parent.frame()
|
'return the first node defining a new scope (i.e. Module,
FunctionDef, ClassDef, Lambda but also GenExpr)'
| def scope(self):
| return self.parent.scope()
|
'return the root node of the tree, (i.e. a Module)'
| def root(self):
| if self.parent:
return self.parent.root()
return self
|
'search for the right sequence where the child lies in'
| def child_sequence(self, child):
| for field in self._astroid_fields:
node_or_sequence = getattr(self, field)
if (node_or_sequence is child):
return [node_or_sequence]
if (isinstance(node_or_sequence, (tuple, list)) and (child in node_or_sequence)):
return node_or_sequence
msg = "Could not fi... |
'return a 2-uple (child attribute name, sequence or node)'
| def locate_child(self, child):
| for field in self._astroid_fields:
node_or_sequence = getattr(self, field)
if (child is node_or_sequence):
return (field, child)
if (isinstance(node_or_sequence, (tuple, list)) and (child in node_or_sequence)):
return (field, node_or_sequence)
msg = "Could not ... |
'return the next sibling statement'
| def next_sibling(self):
| return self.parent.next_sibling()
|
'return the previous sibling statement'
| def previous_sibling(self):
| return self.parent.previous_sibling()
|
'return the node which is the nearest before this one in the
given list of nodes'
| def nearest(self, nodes):
| myroot = self.root()
mylineno = self.fromlineno
nearest = (None, 0)
for node in nodes:
assert (node.root() is myroot), ('nodes %s and %s are not from the same module' % (self, node))
lineno = node.fromlineno
if (node.fromlineno > mylineno):
... |
'return the line number where the given node appears
we need this method since not all nodes have the lineno attribute
correctly set...'
| def _fixed_source_line(self):
| line = self.lineno
_node = self
try:
while (line is None):
_node = next(_node.get_children())
line = _node.lineno
except StopIteration:
_node = self.parent
while (_node and (line is None)):
line = _node.lineno
_node = _node.parent
... |
'handle block line numbers range for non block opening statements'
| def block_range(self, lineno):
| return (lineno, self.tolineno)
|
'delegate to a scoped parent handling a locals dictionary'
| def set_local(self, name, stmt):
| self.parent.set_local(name, stmt)
|
'return an iterator on nodes which are instance of the given class(es)
klass may be a class object or a tuple of class objects'
| def nodes_of_class(self, klass, skip_klass=None):
| if isinstance(self, klass):
(yield self)
for child_node in self.get_children():
if ((skip_klass is not None) and isinstance(child_node, skip_klass)):
continue
for matching in child_node.nodes_of_class(klass, skip_klass):
(yield matching)
|
'we don\'t know how to resolve a statement by default'
| def _infer(self, context=None):
| raise exceptions.InferenceError('No inference function for {node!r}.', node=self, context=context)
|
'return list of inferred values for a more simple inference usage'
| def inferred(self):
| return list(self.infer())
|
'instantiate a node if it is a ClassDef node, else return self'
| def instantiate_class(self):
| return self
|
'Returns a string representation of the AST from this node.
:param ids: If true, includes the ids with the node type names.
:param include_linenos: If true, includes the line numbers and
column offsets.
:param ast_state: If true, includes information derived from
the whole AST like local and global variables.
:param in... | def repr_tree(self, ids=False, include_linenos=False, ast_state=False, indent=' ', max_depth=0, max_width=80):
| @_singledispatch
def _repr_tree(node, result, done, cur_indent='', depth=1):
"Outputs a representation of a non-tuple/list, non-node that's\n contained within an AST, including strings.\n ... |
'Determine the bool value of this node
The boolean value of a node can have three
possible values:
* False. For instance, empty data structures,
False, empty strings, instances which return
explicitly False from the __nonzero__ / __bool__
method.
* True. Most of constructs are True by default:
classes, functions, modul... | def bool_value(self):
| return util.Uninferable
|
'return the next sibling statement'
| def next_sibling(self):
| stmts = self.parent.child_sequence(self)
index = stmts.index(self)
try:
return stmts[(index + 1)]
except IndexError:
pass
|
'return the previous sibling statement'
| def previous_sibling(self):
| stmts = self.parent.child_sequence(self)
index = stmts.index(self)
if (index >= 1):
return stmts[(index - 1)]
|
'lookup a variable name
return the scope node and the list of assignments associated to the
given name according to the scope where it has been found (locals,
globals or builtin)
The lookup is starting from self\'s scope. If self is not a frame itself
and the name is found in the inner frame locals, statements will be
... | def lookup(self, name):
| return self.scope().scope_lookup(self, name)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.