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_hack())): if bases: bases = ('(%s, metaclass=%s)' % (bases, metaclass.name)) else: bases = ('(metaclass=%s)' % metaclass.name) else: bases = (('(%s)' % bases) if bases else '') docs = (('\n%s"""%s"""' % (self.indent, node.doc)) if node.doc else '') return ('\n\n%sclass %s%s:%s\n%s\n' % (decorate, node.name, bases, docs, self._stmt_list(node.body)))
'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 + ':') else: trailer = ':' def_format = '\n%sdef %s(%s)%s%s\n%s' return (def_format % (decorate, node.name, node.args.accept(self), trailer, docs, self._stmt_list(node.body)))
'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' % node.exc.accept(self)) return 'raise'
'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 if ((modname in self.astroid_cache) and (self.astroid_cache[modname].file == filepath)): return self.astroid_cache[modname] if source: from astroid.builder import AstroidBuilder return AstroidBuilder(self).file_build(filepath, modname) elif (fallback and modname): return self.ast_from_module_name(modname) raise exceptions.AstroidBuildingError('Unable to build an AST for {path}.', path=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(modname, context_file) if (found_spec.type == spec.ModuleType.PY_ZIPMODULE): module = self.zip_import_data(found_spec.location) if (module is not None): return module elif (found_spec.type in (spec.ModuleType.C_BUILTIN, spec.ModuleType.C_EXTENSION)): if ((found_spec.type == spec.ModuleType.C_EXTENSION) and (not self._can_load_extension(modname))): return self._build_stub_module(modname) try: module = modutils.load_module_from_name(modname) except Exception as ex: util.reraise(exceptions.AstroidImportError('Loading {modname} failed with:\n{error}', modname=modname, path=found_spec.location, error=ex)) return self.ast_from_module(module, modname) elif (found_spec.type == spec.ModuleType.PY_COMPILED): raise exceptions.AstroidImportError('Unable to load compiled module {modname}.', modname=modname, path=found_spec.location) elif (found_spec.type == spec.ModuleType.PY_NAMESPACE): return self._build_namespace_module(modname, found_spec.submodule_search_locations) if (found_spec.location is None): raise exceptions.AstroidImportError("Can't find a file for module {modname}.", modname=modname) return self.ast_from_file(found_spec.location, modname, fallback=False) except exceptions.AstroidBuildingError as e: for hook in self._failed_import_hooks: try: return hook(modname) except exceptions.AstroidBuildingError: pass raise e finally: os.chdir(old_cwd)
'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 from astroid.builder import AstroidBuilder return AstroidBuilder(self).module_build(module, modname)
'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_module_name(modname) return modastroid.getattr(klass.__name__)[0]
'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, class_repr=safe_repr(klass))) except Exception as ex: util.reraise(exceptions.AstroidImportError('Unexpected error while retrieving module for {class_repr}:\n{error}', cls=klass, class_repr=safe_repr(klass), error=ex)) try: name = klass.__name__ except AttributeError: util.reraise(exceptions.AstroidBuildingError('Unable to get name for {class_repr}:\n', cls=klass, class_repr=safe_repr(klass))) except Exception as ex: util.reraise(exceptions.AstroidImportError('Unexpected error while retrieving name for {class_repr}:\n{error}', cls=klass, class_repr=safe_repr(klass), error=ex)) 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())
'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 `AstroidBuildingError`.'
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_class(scoped_nodes.ClassDef) if ((cls != self._instance) and cls.is_subtype_of(qname))] obj = node_classes.List(parent=self._instance) obj.postinit(classes) class SubclassesBoundMethod(bases.BoundMethod, ): def infer_call_result(self, caller, context=None): (yield obj) implicit_metaclass = self._instance.implicit_metaclass() subclasses_method = implicit_metaclass.locals['__subclasses__'][0] return SubclassesBoundMethod(proxy=subclasses_method, bound=implicit_metaclass)
'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): (yield stmt) except exceptions.AttributeInferenceError: try: attrs = self._proxied.igetattr(name, context, class_context=False) for stmt in self._wrap_attr(attrs, context): (yield stmt) except exceptions.AttributeInferenceError as error: util.reraise(exceptions.InferenceError(**vars(error)))
'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 (attr.name == '<lambda>')): if (attr.statement().scope() == self._proxied): if (attr.args.args and (attr.args.args[0].name == 'self')): (yield BoundMethod(attr, self)) continue (yield attr) else: (yield attr)
'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 exceptions.InferenceError(node=self, caller=caller, context=context)
'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 called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither __len__() nor __bool__(), all its instances are considered true.'
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: result = _infer_method_result_truth(self, '__len__', context) except (exceptions.AttributeInferenceError, exceptions.InferenceError): return True return result
'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'): return if (not isinstance(name.value, str)): return bases = next(caller.args[2].infer(context=context)) if (bases.__class__.__name__ != 'Tuple'): return inferred_bases = [next(elt.infer(context=context)) for elt in bases.elts] if any(((base.__class__.__name__ != 'ClassDef') for base in inferred_bases)): return attrs = next(caller.args[3].infer(context=context)) if (attrs.__class__.__name__ != 'Dict'): return cls_locals = collections.defaultdict(list) for (key, value) in attrs.items: key = next(key.infer(context=context)) value = next(value.infer(context=context)) if (key.__class__.__name__ != 'Const'): return if (not isinstance(key.value, str)): return cls_locals[key.value].append(value) cls = mcs.__class__(name=name.value, lineno=caller.lineno, col_offset=caller.col_offset, parent=caller) empty = node_classes.Pass() cls.postinit(bases=bases.elts, body=[empty], decorators=[], newstyle=True, metaclass=mcs, keywords=[]) cls.locals = cls_locals return cls
'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, context.boundnode) if (key in context.inferred): return iter(context.inferred[key]) return context.cache_generator(key, self._infer(context, **kwargs))
'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 find %s in %s's children" raise exceptions.AstroidError((msg % (repr(child), repr(self))))
'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 find %s in %s's children" raise exceptions.AstroidError((msg % (repr(child), repr(self))))
'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): break if (lineno > nearest[1]): nearest = (node, lineno) return nearest[0]
'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 return line
'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 indent: A string to use to indent the output string. :param max_depth: If set to a positive integer, won\'t return nodes deeper than max_depth in the string. :param max_width: Only positive integer values are valid, the default is 80. Attempts to format the output string to stay within max_width characters, but can exceed it under some circumstances.'
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 " lines = pprint.pformat(node, width=max((max_width - len(cur_indent)), 1)).splitlines(True) result.append(lines[0]) result.extend([(cur_indent + line) for line in lines[1:]]) return (len(lines) != 1) @_repr_tree.register(tuple) @_repr_tree.register(list) def _repr_seq(node, result, done, cur_indent='', depth=1): "Outputs a representation of a sequence that's contained within an AST." cur_indent += indent result.append('[') if (not node): broken = False elif (len(node) == 1): broken = _repr_tree(node[0], result, done, cur_indent, depth) elif (len(node) == 2): broken = _repr_tree(node[0], result, done, cur_indent, depth) if (not broken): result.append(', ') else: result.append(',\n') result.append(cur_indent) broken = (_repr_tree(node[1], result, done, cur_indent, depth) or broken) else: result.append('\n') result.append(cur_indent) for child in node[:(-1)]: _repr_tree(child, result, done, cur_indent, depth) result.append(',\n') result.append(cur_indent) _repr_tree(node[(-1)], result, done, cur_indent, depth) broken = True result.append(']') return broken @_repr_tree.register(NodeNG) def _repr_node(node, result, done, cur_indent='', depth=1): 'Outputs a strings representation of an astroid node.' if (node in done): result.append((indent + ('<Recursion on %s with id=%s' % (type(node).__name__, id(node))))) return False else: done.add(node) if (max_depth and (depth > max_depth)): result.append('...') return False depth += 1 cur_indent += indent if ids: result.append(('%s<0x%x>(\n' % (type(node).__name__, id(node)))) else: result.append(('%s(' % type(node).__name__)) fields = [] if include_linenos: fields.extend(('lineno', 'col_offset')) fields.extend(node._other_fields) fields.extend(node._astroid_fields) if ast_state: fields.extend(node._other_other_fields) if (not fields): broken = False elif (len(fields) == 1): result.append(('%s=' % fields[0])) broken = _repr_tree(getattr(node, fields[0]), result, done, cur_indent, depth) else: result.append('\n') result.append(cur_indent) for field in fields[:(-1)]: result.append(('%s=' % field)) _repr_tree(getattr(node, field), result, done, cur_indent, depth) result.append(',\n') result.append(cur_indent) result.append(('%s=' % fields[(-1)])) _repr_tree(getattr(node, fields[(-1)]), result, done, cur_indent, depth) broken = True result.append(')') return broken result = [] _repr_tree(self, result, set()) return ''.join(result)
'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, modules etc * Uninferable: the inference engine is uncertain of the node\'s value.'
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 filtered to remove ignorable statements according to self\'s location'
def lookup(self, name):
return self.scope().scope_lookup(self, name)