summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSylvain Thénault <sylvain.thenault@logilab.fr>2014-07-25 15:57:12 +0200
committerSylvain Thénault <sylvain.thenault@logilab.fr>2014-07-25 15:57:12 +0200
commit6895584b2b3cb9cb128804048f826d3b077d1d1b (patch)
treedfada18a16627cd82b9f0ae1041803f79f5f2c3f
parent320d0ae58cde934193f83428fb1149f097a4bec2 (diff)
downloadastroid-git-6895584b2b3cb9cb128804048f826d3b077d1d1b.tar.gz
pylint source code
-rw-r--r--__pkginfo__.py5
-rw-r--r--as_string.py83
-rw-r--r--bases.py13
-rw-r--r--builder.py10
-rw-r--r--inference.py15
-rw-r--r--inspector.py2
-rw-r--r--manager.py10
-rw-r--r--mixins.py4
-rw-r--r--modutils.py18
-rw-r--r--node_classes.py39
-rw-r--r--protocols.py4
-rw-r--r--raw_building.py6
-rw-r--r--rebuilder.py31
-rw-r--r--scoped_nodes.py27
-rw-r--r--test_utils.py6
-rw-r--r--utils.py22
16 files changed, 152 insertions, 143 deletions
diff --git a/__pkginfo__.py b/__pkginfo__.py
index 85398ff1..14010bf5 100644
--- a/__pkginfo__.py
+++ b/__pkginfo__.py
@@ -38,11 +38,12 @@ description = "rebuild a new abstract syntax tree from Python's ast"
from os.path import join
include_dirs = ['brain',
join('test', 'regrtest_data'),
- join('test', 'data'), join('test', 'data2')]
+ join('test', 'data'), join('test', 'data2')
+ ]
classifiers = ["Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Software Development :: Quality Assurance",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
- ]
+ ]
diff --git a/as_string.py b/as_string.py
index ace1c4e3..f19713d9 100644
--- a/as_string.py
+++ b/as_string.py
@@ -44,29 +44,29 @@ def _repr_tree(node, result, indent='', _done=None, ids=False):
if not hasattr(node, '_astroid_fields'): # not a astroid node
return
if node in _done:
- result.append( indent + 'loop in tree: %s' % node )
+ result.append(indent + 'loop in tree: %s' % node)
return
_done.add(node)
node_str = str(node)
if ids:
node_str += ' . \t%x' % id(node)
- result.append( indent + node_str )
+ result.append(indent + node_str)
indent += INDENT
for field in node._astroid_fields:
value = getattr(node, field)
- if isinstance(value, (list, tuple) ):
- result.append( indent + field + " = [" )
+ if isinstance(value, (list, tuple)):
+ result.append(indent + field + " = [")
for child in value:
- if isinstance(child, (list, tuple) ):
+ if isinstance(child, (list, tuple)):
# special case for Dict # FIXME
_repr_tree(child[0], result, indent, _done, ids)
_repr_tree(child[1], result, indent, _done, ids)
result.append(indent + ',')
else:
_repr_tree(child, result, indent, _done, ids)
- result.append( indent + "]" )
+ result.append(indent + "]")
else:
- result.append( indent + field + " = " )
+ result.append(indent + field + " = ")
_repr_tree(value, result, indent, _done, ids)
@@ -97,7 +97,7 @@ class AsStringVisitor(object):
"""return an astroid.Assert node as string"""
if node.fail:
return 'assert %s, %s' % (node.test.accept(self),
- node.fail.accept(self))
+ node.fail.accept(self))
return 'assert %s' % node.test.accept(self)
def visit_assname(self, node):
@@ -124,7 +124,7 @@ class AsStringVisitor(object):
def visit_boolop(self, node):
"""return an astroid.BoolOp node as string"""
return (' %s ' % node.op).join(['(%s)' % n.accept(self)
- for n in node.values])
+ for n in node.values])
def visit_break(self, node):
"""return an astroid.Break node as string"""
@@ -135,15 +135,15 @@ class AsStringVisitor(object):
expr_str = node.func.accept(self)
args = [arg.accept(self) for arg in node.args]
if node.starargs:
- args.append( '*' + node.starargs.accept(self))
+ args.append('*' + node.starargs.accept(self))
if node.kwargs:
- args.append( '**' + node.kwargs.accept(self))
+ args.append('**' + node.kwargs.accept(self))
return '%s(%s)' % (expr_str, ', '.join(args))
def visit_class(self, node):
"""return an astroid.Class node as string"""
decorate = node.decorators and node.decorators.accept(self) or ''
- bases = ', '.join([n.accept(self) for n in node.bases])
+ bases = ', '.join([n.accept(self) for n in node.bases])
if sys.version_info[0] == 2:
bases = bases and '(%s)' % bases or ''
else:
@@ -157,7 +157,7 @@ class AsStringVisitor(object):
bases = bases and '(%s)' % bases or ''
docs = node.doc and '\n%s"""%s"""' % (INDENT, node.doc) or ''
return '\n\n%sclass %s%s:%s\n%s\n' % (decorate, node.name, bases, docs,
- self._stmt_list( node.body))
+ self._stmt_list(node.body))
def visit_compare(self, node):
"""return an astroid.Compare node as string"""
@@ -167,9 +167,9 @@ class AsStringVisitor(object):
def visit_comprehension(self, node):
"""return an astroid.Comprehension node as string"""
- ifs = ''.join([ ' if %s' % n.accept(self) for n in node.ifs])
+ 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 )
+ node.iter.accept(self), ifs)
def visit_const(self, node):
"""return an astroid.Const node as string"""
@@ -182,7 +182,7 @@ class AsStringVisitor(object):
def visit_delete(self, node): # XXX check if correct
"""return an astroid.Delete node as string"""
return 'del %s' % ', '.join([child.accept(self)
- for child in node.targets])
+ for child in node.targets])
def visit_delattr(self, node):
"""return an astroid.DelAttr node as string"""
@@ -199,12 +199,13 @@ class AsStringVisitor(object):
def visit_dict(self, node):
"""return an astroid.Dict node as string"""
return '{%s}' % ', '.join(['%s: %s' % (key.accept(self),
- value.accept(self)) for key, value in node.items])
+ value.accept(self))
+ for key, value in node.items])
def visit_dictcomp(self, node):
"""return an astroid.DictComp node as string"""
return '{%s: %s %s}' % (node.key.accept(self), node.value.accept(self),
- ' '.join([n.accept(self) for n in node.generators]))
+ ' '.join([n.accept(self) for n in node.generators]))
def visit_discard(self, node):
"""return an astroid.Discard node as string"""
@@ -218,7 +219,7 @@ class AsStringVisitor(object):
if node.type:
if node.name:
excs = 'except %s, %s' % (node.type.accept(self),
- node.name.accept(self))
+ node.name.accept(self))
else:
excs = 'except %s' % node.type.accept(self)
else:
@@ -246,13 +247,13 @@ class AsStringVisitor(object):
def visit_extslice(self, node):
"""return an astroid.ExtSlice node as string"""
- return ','.join( [dim.accept(self) for dim in node.dims] )
+ return ','.join([dim.accept(self) for dim in node.dims])
def visit_for(self, node):
"""return an astroid.For node as string"""
fors = 'for %s in %s:\n%s' % (node.target.accept(self),
- node.iter.accept(self),
- self._stmt_list( node.body))
+ 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
@@ -267,12 +268,12 @@ class AsStringVisitor(object):
decorate = node.decorators and node.decorators.accept(self) or ''
docs = node.doc and '\n%s"""%s"""' % (INDENT, node.doc) or ''
return '\n%sdef %s(%s):%s\n%s' % (decorate, node.name, node.args.accept(self),
- docs, self._stmt_list(node.body))
+ docs, self._stmt_list(node.body))
def visit_genexpr(self, node):
"""return an astroid.GenExpr node as string"""
- return '(%s %s)' % (node.elt.accept(self), ' '.join([n.accept(self)
- for n in node.generators]))
+ return '(%s %s)' % (node.elt.accept(self),
+ ' '.join([n.accept(self) for n in node.generators]))
def visit_getattr(self, node):
"""return an astroid.Getattr node as string"""
@@ -292,7 +293,8 @@ class AsStringVisitor(object):
def visit_ifexp(self, node):
"""return an astroid.IfExp node as string"""
return '%s if %s else %s' % (node.body.accept(self),
- node.test.accept(self), node.orelse.accept(self))
+ node.test.accept(self),
+ node.orelse.accept(self))
def visit_import(self, node):
"""return an astroid.Import node as string"""
@@ -304,7 +306,8 @@ class AsStringVisitor(object):
def visit_lambda(self, node):
"""return an astroid.Lambda node as string"""
- return 'lambda %s: %s' % (node.args.accept(self), node.body.accept(self))
+ return 'lambda %s: %s' % (node.args.accept(self),
+ node.body.accept(self))
def visit_list(self, node):
"""return an astroid.List node as string"""
@@ -312,8 +315,8 @@ class AsStringVisitor(object):
def visit_listcomp(self, node):
"""return an astroid.ListComp node as string"""
- return '[%s %s]' % (node.elt.accept(self), ' '.join([n.accept(self)
- for n in node.generators]))
+ return '[%s %s]' % (node.elt.accept(self),
+ ' '.join([n.accept(self) for n in node.generators]))
def visit_module(self, node):
"""return an astroid.Module node as string"""
@@ -343,10 +346,10 @@ class AsStringVisitor(object):
if node.inst:
if node.tback:
return 'raise %s, %s, %s' % (node.exc.accept(self),
- node.inst.accept(self),
- node.tback.accept(self))
+ node.inst.accept(self),
+ node.tback.accept(self))
return 'raise %s, %s' % (node.exc.accept(self),
- node.inst.accept(self))
+ node.inst.accept(self))
return 'raise %s' % node.exc.accept(self)
return 'raise'
@@ -367,8 +370,8 @@ class AsStringVisitor(object):
def visit_setcomp(self, node):
"""return an astroid.SetComp node as string"""
- return '{%s %s}' % (node.elt.accept(self), ' '.join([n.accept(self)
- for n in node.generators]))
+ return '{%s %s}' % (node.elt.accept(self),
+ ' '.join([n.accept(self) for n in node.generators]))
def visit_slice(self, node):
"""return a astroid.Slice node as string"""
@@ -385,7 +388,7 @@ class AsStringVisitor(object):
def visit_tryexcept(self, node):
"""return an astroid.TryExcept node as string"""
- trys = ['try:\n%s' % self._stmt_list( node.body)]
+ trys = ['try:\n%s' % self._stmt_list(node.body)]
for handler in node.handlers:
trys.append(handler.accept(self))
if node.orelse:
@@ -394,13 +397,13 @@ class AsStringVisitor(object):
def visit_tryfinally(self, node):
"""return an astroid.TryFinally node as string"""
- return 'try:\n%s\nfinally:\n%s' % (self._stmt_list( node.body),
- self._stmt_list(node.finalbody))
+ return 'try:\n%s\nfinally:\n%s' % (self._stmt_list(node.body),
+ self._stmt_list(node.finalbody))
def visit_tuple(self, node):
"""return an astroid.Tuple node as string"""
if len(node.elts) == 1:
- return '(%s, )' % node.elts[0].accept(self)
+ return '(%s, )' % node.elts[0].accept(self)
return '(%s)' % ', '.join([child.accept(self) for child in node.elts])
def visit_unaryop(self, node):
@@ -424,7 +427,7 @@ class AsStringVisitor(object):
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))
+ return 'with %s:\n%s' % (items, self._stmt_list(node.body))
def visit_yield(self, node):
"""yield an ast.Yield node as string"""
@@ -443,7 +446,7 @@ class AsStringVisitor3k(AsStringVisitor):
if node.type:
if node.name:
excs = 'except %s as %s' % (node.type.accept(self),
- node.name.accept(self))
+ node.name.accept(self))
else:
excs = 'except %s' % node.type.accept(self)
else:
diff --git a/bases.py b/bases.py
index fc4f572f..e8544714 100644
--- a/bases.py
+++ b/bases.py
@@ -72,7 +72,7 @@ class InferenceContext(object):
name = self.lookupname
if (node, name) in self.path:
raise StopIteration()
- self.path.add( (node, name) )
+ self.path.add((node, name))
def clone(self):
# XXX copy lookupname/callcontext ?
@@ -266,7 +266,7 @@ class UnboundMethod(Proxy):
class BoundMethod(UnboundMethod):
"""a special node representing a method bound to an instance"""
- def __init__(self, proxy, bound):
+ def __init__(self, proxy, bound):
UnboundMethod.__init__(self, proxy)
self.bound = bound
@@ -388,14 +388,13 @@ class NodeNG(object):
def __repr__(self):
return '<%s(%s) l.%s [%s] at 0x%x>' % (self.__class__.__name__,
- self._repr_name(),
- self.fromlineno,
- self.root().name,
- id(self))
+ self._repr_name(),
+ self.fromlineno,
+ self.root().name,
+ id(self))
def accept(self, visitor):
- klass = self.__class__.__name__
func = getattr(visitor, "visit_" + self.__class__.__name__.lower())
return func(self)
diff --git a/builder.py b/builder.py
index 22606d29..692016a3 100644
--- a/builder.py
+++ b/builder.py
@@ -42,12 +42,12 @@ if sys.version_info >= (3, 0):
from tokenize import detect_encoding
def open_source_file(filename):
- with open(filename, 'bU') as byte_stream:
+ with open(filename, 'rb') as byte_stream:
encoding = detect_encoding(byte_stream.readline)[0]
- stream = open(filename, 'U', encoding=encoding)
+ stream = open(filename, 'rU', encoding=encoding)
try:
data = stream.read()
- except UnicodeError, uex: # wrong encodingg
+ except UnicodeError: # wrong encodingg
# detect_encoding returns utf-8 if no encoding specified
msg = 'Wrong (%s) or no encoding specified' % encoding
raise AstroidBuildingException(msg)
@@ -56,7 +56,7 @@ if sys.version_info >= (3, 0):
else:
import re
- _ENCODING_RGX = re.compile("\s*#+.*coding[:=]\s*([-\w.]+)")
+ _ENCODING_RGX = re.compile(r"\s*#+.*coding[:=]\s*([-\w.]+)")
def _guess_encoding(string):
"""get encoding from a python file as string or return None if not found
@@ -115,7 +115,7 @@ class AstroidBuilder(InspectBuilder):
path is expected to be a python source file
"""
try:
- stream, encoding, data = open_source_file(path)
+ _, encoding, data = open_source_file(path)
except IOError, exc:
msg = 'Unable to load file %r (%s)' % (path, exc)
raise AstroidBuildingException(msg)
diff --git a/inference.py b/inference.py
index 549e9a1d..5bdb0fc5 100644
--- a/inference.py
+++ b/inference.py
@@ -25,16 +25,17 @@ from itertools import chain
from astroid import nodes
from astroid.manager import AstroidManager
-from astroid.exceptions import (AstroidError,
- InferenceError, NoDefault, NotFoundError, UnresolvableName)
-from astroid.bases import YES, Instance, InferenceContext, \
- _infer_stmts, copy_context, path_wrapper, raise_if_nothing_infered
+from astroid.exceptions import (AstroidError, InferenceError, NoDefault,
+ NotFoundError, UnresolvableName)
+from astroid.bases import (YES, Instance, InferenceContext,
+ _infer_stmts, copy_context, path_wrapper,
+ raise_if_nothing_infered)
from astroid.protocols import _arguments_infer_argname
MANAGER = AstroidManager()
-class CallContext:
+class CallContext(object):
"""when inferring a function call, this class is used to remember values
given as argument
"""
@@ -307,7 +308,7 @@ BIN_OP_METHOD = {'+': '__add__',
'^': '__xor__',
'<<': '__lshift__',
'>>': '__rshift__',
- }
+ }
def _infer_binop(operator, operand1, operand2, context, failures=None):
if operand1 is YES:
@@ -381,7 +382,7 @@ def infer_empty_node(self, context=None):
else:
try:
for infered in MANAGER.infer_ast_from_something(self.object,
- context=context):
+ context=context):
yield infered
except AstroidError:
yield YES
diff --git a/inspector.py b/inspector.py
index 8fe0190c..1fc31926 100644
--- a/inspector.py
+++ b/inspector.py
@@ -30,7 +30,7 @@ from astroid.exceptions import InferenceError
from astroid.utils import LocalsVisitor
from astroid.modutils import get_module_part, is_relative, is_standard_module
-class IdGeneratorMixIn:
+class IdGeneratorMixIn(object):
"""
Mixin adding the ability to generate integer uid
"""
diff --git a/manager.py b/manager.py
index 5f03b75a..fde52e2b 100644
--- a/manager.py
+++ b/manager.py
@@ -75,7 +75,7 @@ class AstroidManager(OptionsProviderMixIn):
{'default': "No Name", 'type' : 'string', 'short': 'p',
'metavar' : '<project name>',
'help' : 'set the project name.'}),
- )
+ )
brain = {}
def __init__(self):
self.__dict__ = AstroidManager.brain
@@ -107,7 +107,7 @@ class AstroidManager(OptionsProviderMixIn):
elif fallback and modname:
return self.ast_from_module_name(modname)
raise AstroidBuildingException('unable to get astroid for file %s' %
- filepath)
+ filepath)
def ast_from_module_name(self, modname, context_file=None):
"""given a module name, return the astroid object"""
@@ -150,7 +150,7 @@ class AstroidManager(OptionsProviderMixIn):
importer = zipimport.zipimporter(eggpath + ext)
zmodname = resource.replace('/', '.')
if importer.is_package(resource):
- zmodname = zmodname + '.__init__'
+ zmodname = zmodname + '.__init__'
module = builder.string_build(importer.get_source(resource),
zmodname, filepath)
return module
@@ -273,11 +273,11 @@ class AstroidManager(OptionsProviderMixIn):
The transform function may return a value which is then used to
substitute the original node in the tree.
"""
- self.transforms.setdefault(node_class, []).append( (transform, predicate) )
+ self.transforms.setdefault(node_class, []).append((transform, predicate))
def unregister_transform(self, node_class, transform, predicate=None):
"""Unregister the given transform."""
- self.transforms[node_class].remove( (transform, predicate) )
+ self.transforms[node_class].remove((transform, predicate))
def transform(self, node):
"""Call matching transforms for the given node if any and return the
diff --git a/mixins.py b/mixins.py
index e4623136..f9037245 100644
--- a/mixins.py
+++ b/mixins.py
@@ -19,7 +19,7 @@
"""
from astroid.exceptions import (AstroidBuildingException, InferenceError,
- NotFoundError)
+ NotFoundError)
class BlockRangeMixIn(object):
@@ -120,5 +120,3 @@ class FromImportMixIn(FilterStmtsMixin):
return name
raise NotFoundError(asname)
-
-
diff --git a/modutils.py b/modutils.py
index dfdad24b..1f4a4fc5 100644
--- a/modutils.py
+++ b/modutils.py
@@ -32,9 +32,9 @@ __docformat__ = "restructuredtext en"
import sys
import os
-from os.path import splitext, join, abspath, isdir, dirname, exists, basename
+from os.path import splitext, join, abspath, isdir, dirname, exists
from imp import find_module, load_module, C_BUILTIN, PY_COMPILED, PKG_DIRECTORY
-from distutils.sysconfig import get_config_var, get_python_lib, get_python_version
+from distutils.sysconfig import get_python_lib
from distutils.errors import DistutilsPlatformError
try:
@@ -44,7 +44,7 @@ except ImportError:
ZIPFILE = object()
-from logilab.common import STD_BLACKLIST, _handle_blacklist
+from logilab.common import _handle_blacklist
# Notes about STD_LIB_DIR
# Consider arch-specific installation for STD_LIB_DIR definition
@@ -148,8 +148,8 @@ def load_module_from_modpath(parts, path=None, use_sys=1):
setattr(prevmodule, part, module)
_file = getattr(module, '__file__', '')
if not _file and len(modpath) != len(parts):
- raise ImportError('no module in %s' % '.'.join(parts[len(modpath):]) )
- path = [dirname( _file )]
+ raise ImportError('no module in %s' % '.'.join(parts[len(modpath):]))
+ path = [dirname(_file)]
prevmodule = module
return module
@@ -326,8 +326,8 @@ def get_module_part(dotted_name, context_file=None):
context_file = dirname(context_file)
for i in range(starti, len(parts)):
try:
- file_from_modpath(parts[starti:i+1],
- path=path, context_file=context_file)
+ file_from_modpath(parts[starti:i+1], path=path,
+ context_file=context_file)
except ImportError:
if not i >= max(1, len(parts) - 2):
raise
@@ -419,7 +419,7 @@ def is_standard_module(modname, std_path=(STD_LIB_DIR,)):
modname = modname.split('.')[0]
try:
filename = file_from_modpath([modname])
- except ImportError, ex:
+ except ImportError:
# import failed, i'm probably not so wrong by supposing it's
# not standard...
return False
@@ -503,7 +503,7 @@ def _search_zip(modpath, pic):
raise ImportError('No module named %s' % '.'.join(modpath))
-def _abspath(path, _abspathcache={}):
+def _abspath(path, _abspathcache={}): #pylint: disable=dangerous-default-value
"""abspath with caching"""
# _module_file calls abspath on every path in sys.path every time it's
# called; on a larger codebase this easily adds up to half a second just
diff --git a/node_classes.py b/node_classes.py
index 5a70e7e9..6d597458 100644
--- a/node_classes.py
+++ b/node_classes.py
@@ -22,9 +22,9 @@ import sys
from astroid.exceptions import NoDefault
from astroid.bases import (NodeNG, Statement, Instance, InferenceContext,
- _infer_stmts, YES, BUILTINS)
-from astroid.mixins import BlockRangeMixIn, AssignTypeMixin, \
- ParentAssignTypeMixin, FromImportMixIn
+ _infer_stmts, YES, BUILTINS)
+from astroid.mixins import (BlockRangeMixIn, AssignTypeMixin,
+ ParentAssignTypeMixin, FromImportMixIn)
PY3K = sys.version_info >= (3, 0)
@@ -84,16 +84,16 @@ def are_exclusive(stmt1, stmt2, exceptions=None):
# nodes are in exclusive branches
if isinstance(node, If) and exceptions is None:
if (node.locate_child(previous)[1]
- is not node.locate_child(children[node])[1]):
+ is not node.locate_child(children[node])[1]):
return True
elif isinstance(node, TryExcept):
c2attr, c2node = node.locate_child(previous)
c1attr, c1node = node.locate_child(children[node])
if c1node is not c2node:
if ((c2attr == 'body' and c1attr == 'handlers' and children[node].catch(exceptions)) or
- (c2attr == 'handlers' and c1attr == 'body' and previous.catch(exceptions)) or
- (c2attr == 'handlers' and c1attr == 'orelse') or
- (c2attr == 'orelse' and c1attr == 'handlers')):
+ (c2attr == 'handlers' and c1attr == 'body' and previous.catch(exceptions)) or
+ (c2attr == 'handlers' and c1attr == 'orelse') or
+ (c2attr == 'orelse' and c1attr == 'handlers')):
return True
elif c2attr == 'handlers' and c1attr == 'handlers':
return previous is not children[node]
@@ -110,13 +110,13 @@ class LookupMixIn(object):
def lookup(self, name):
"""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)
+ 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
+ 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
"""
return self.scope().scope_lookup(self, name)
@@ -444,7 +444,7 @@ class Compare(NodeNG):
class Comprehension(NodeNG):
"""class representing a Comprehension node"""
- _astroid_fields = ('target', 'iter' ,'ifs')
+ _astroid_fields = ('target', 'iter', 'ifs')
target = None
iter = None
ifs = None
@@ -528,7 +528,7 @@ class Dict(NodeNG, Instance):
self.items = []
else:
self.items = [(const_factory(k), const_factory(v))
- for k,v in items.iteritems()]
+ for k, v in items.iteritems()]
def pytype(self):
return '%s.dict' % BUILTINS
@@ -554,7 +554,8 @@ class Dict(NodeNG, Instance):
for inferedkey in key.infer(context):
if inferedkey is YES:
continue
- if isinstance(inferedkey, Const) and inferedkey.value == lookup_key:
+ if isinstance(inferedkey, Const) \
+ and inferedkey.value == lookup_key:
return value
# This should raise KeyError, but all call sites only catch
# IndexError. Let's leave it like that for now.
@@ -632,7 +633,7 @@ class For(BlockRangeMixIn, AssignTypeMixin, Statement):
class From(FromImportMixIn, Statement):
"""class representing a From node"""
- def __init__(self, fromname, names, level=0):
+ def __init__(self, fromname, names, level=0):
self.modname = fromname
self.names = names
self.level = level
@@ -841,7 +842,7 @@ class TryFinally(BlockRangeMixIn, Statement):
child = self.body[0]
# py2.5 try: except: finally:
if (isinstance(child, TryExcept) and child.fromlineno == self.fromlineno
- and lineno > self.fromlineno and lineno <= child.tolineno):
+ and lineno > self.fromlineno and lineno <= child.tolineno):
return child.block_range(lineno)
return self._elsed_block_range(lineno, self.finalbody)
@@ -910,7 +911,7 @@ class Yield(NodeNG):
value = None
class YieldFrom(Yield):
- """ Class representing a YieldFrom node. """
+ """ Class representing a YieldFrom node. """
# constants ##############################################################
diff --git a/protocols.py b/protocols.py
index e66b802c..7ce1faa6 100644
--- a/protocols.py
+++ b/protocols.py
@@ -70,7 +70,7 @@ BIN_OP_IMPL = {'+': lambda a, b: a + b,
'^': lambda a, b: a ^ b,
'<<': lambda a, b: a << b,
'>>': lambda a, b: a >> b,
- }
+ }
for key, impl in BIN_OP_IMPL.items():
BIN_OP_IMPL[key+'='] = impl
@@ -166,7 +166,7 @@ def _resolve_looppart(parts, asspath, context):
assigned = stmt.getitem(index, context)
except (AttributeError, IndexError):
continue
- except TypeError, exc: # stmt is unsubscriptable Const
+ except TypeError: # stmt is unsubscriptable Const
continue
if not asspath:
# we achieved to resolved the assignment path,
diff --git a/raw_building.py b/raw_building.py
index c2739df9..e245f912 100644
--- a/raw_building.py
+++ b/raw_building.py
@@ -28,7 +28,7 @@ from inspect import (getargspec, isdatadescriptor, isfunction, ismethod,
from astroid.node_classes import CONST_CLS
from astroid.nodes import (Module, Class, Const, const_factory, From,
- Function, EmptyNode, Name, Arguments)
+ Function, EmptyNode, Name, Arguments)
from astroid.bases import BUILTINS, Generator
from astroid.manager import AstroidManager
MANAGER = AstroidManager()
@@ -258,9 +258,9 @@ class InspectBuilder(object):
attach_dummy_node(node, name, member)
else:
object_build_function(node, member, name)
- elif isbuiltin(member):
+ elif isbuiltin(member):
if (not _io_discrepancy(member) and
- self.imported_member(node, member, name)):
+ self.imported_member(node, member, name)):
#if obj is object:
# print 'skippp', obj, name, member
continue
diff --git a/rebuilder.py b/rebuilder.py
index 9567d186..8fa7ee92 100644
--- a/rebuilder.py
+++ b/rebuilder.py
@@ -20,8 +20,8 @@ order to get a single Astroid representation
"""
import sys
-from warnings import warn
-from _ast import (Expr as Discard, Str, Name, Attribute,
+from _ast import (
+ Expr as Discard, Str,
# binary operators
Add, Div, FloorDiv, Mod, Mult, Pow, Sub, BitAnd, BitOr, BitXor,
LShift, RShift,
@@ -47,15 +47,18 @@ _BIN_OP_CLASSES = {Add: '+',
Pow: '**',
Sub: '-',
LShift: '<<',
- RShift: '>>'}
+ RShift: '>>',
+ }
_BOOL_OP_CLASSES = {And: 'and',
- Or: 'or'}
+ Or: 'or',
+ }
_UNARY_OP_CLASSES = {UAdd: '+',
USub: '-',
Not: 'not',
- Invert: '~'}
+ Invert: '~',
+ }
_CMP_OP_CLASSES = {Eq: '==',
Gt: '>',
@@ -66,11 +69,13 @@ _CMP_OP_CLASSES = {Eq: '==',
Lt: '<',
LtE: '<=',
NotEq: '!=',
- NotIn: 'not in'}
+ NotIn: 'not in',
+ }
CONST_NAME_TRANSFORMS = {'None': None,
'True': True,
- 'False': False}
+ 'False': False,
+ }
REDIRECT = {'arguments': 'Arguments',
'Attribute': 'Getattr',
@@ -86,7 +91,7 @@ REDIRECT = {'arguments': 'Arguments',
'ImportFrom': 'From',
'keyword': 'Keyword',
'Repr': 'Backquote',
- }
+ }
PY3K = sys.version_info >= (3, 0)
PY34 = sys.version_info >= (3, 4)
@@ -240,8 +245,8 @@ class TreeRebuilder(object):
# set some function or metaclass infos XXX explain ?
klass = newnode.parent.frame()
if (isinstance(klass, new.Class)
- and isinstance(newnode.value, new.CallFunc)
- and isinstance(newnode.value.func, new.Name)):
+ and isinstance(newnode.value, new.CallFunc)
+ and isinstance(newnode.value.func, new.Name)):
func_name = newnode.value.func.name
for ass_node in newnode.targets:
try:
@@ -355,7 +360,7 @@ class TreeRebuilder(object):
_lineno_parent(node, newnode, parent)
newnode.left = self.visit(node.left, newnode)
newnode.ops = [(_CMP_OP_CLASSES[op.__class__], self.visit(expr, newnode))
- for (op, expr) in zip(node.ops, node.comparators)]
+ for (op, expr) in zip(node.ops, node.comparators)]
newnode.set_line_info(newnode.last_child())
return newnode
@@ -380,7 +385,7 @@ class TreeRebuilder(object):
if 'decorators' in node._fields: # py < 2.6, i.e. 2.5
decorators = node.decorators
else:
- decorators= node.decorator_list
+ decorators = node.decorator_list
newnode.nodes = [self.visit(child, newnode) for child in decorators]
newnode.set_line_info(newnode.last_child())
return newnode
@@ -400,7 +405,7 @@ class TreeRebuilder(object):
newnode = new.Dict()
_lineno_parent(node, newnode, parent)
newnode.items = [(self.visit(key, newnode), self.visit(value, newnode))
- for key, value in zip(node.keys, node.values)]
+ for key, value in zip(node.keys, node.values)]
newnode.set_line_info(newnode.last_child())
return newnode
diff --git a/scoped_nodes.py b/scoped_nodes.py
index 9ec9a91a..2f12b065 100644
--- a/scoped_nodes.py
+++ b/scoped_nodes.py
@@ -485,7 +485,6 @@ def _infer_decorator_callchain(node):
end result is a static or a classmethod.
"""
current = node
- ignored = set((None, YES))
while True:
if isinstance(current, CallFunc):
try:
@@ -502,14 +501,14 @@ def _infer_decorator_callchain(node):
result = current.infer_call_result(current.parent).next()
except InferenceError:
return
- if isinstance(result, (Function, CallFunc)):
+ if isinstance(result, (Function, CallFunc)):
current = result
else:
if isinstance(result, Instance):
result = result._proxied
if isinstance(result, Class):
if (result.name == 'classmethod' and
- result.root().name == BUILTINS):
+ result.root().name == BUILTINS):
return 'classmethod'
elif (result.name == 'staticmethod' and
result.root().name == BUILTINS):
@@ -522,7 +521,7 @@ def _infer_decorator_callchain(node):
return
else:
return
-
+
def _function_type(self):
"""
Function type, possible values are:
@@ -548,7 +547,7 @@ def _function_type(self):
for ancestor in infered.ancestors():
if isinstance(ancestor, Class):
if (ancestor.name == 'classmethod' and
- ancestor.root().name == BUILTINS):
+ ancestor.root().name == BUILTINS):
return 'classmethod'
elif (ancestor.name == 'staticmethod' and
ancestor.root().name == BUILTINS):
@@ -809,12 +808,12 @@ def _class_type(klass, ancestors=None):
for base in klass.ancestors(recurs=False):
name = _class_type(base, ancestors)
if name != 'class':
- if name == 'metaclass' and not _is_metaclass(klass):
- # don't propagate it if the current class
- # can't be a metaclass
- continue
- klass._type = base.type
- break
+ if name == 'metaclass' and not _is_metaclass(klass):
+ # don't propagate it if the current class
+ # can't be a metaclass
+ continue
+ klass._type = base.type
+ break
if klass._type is None:
klass._type = 'class'
return klass._type
@@ -929,7 +928,7 @@ class Class(Statement, LocalsDictNodeNG, FilterStmtsMixin):
result.parent = caller.parent
yield result
else:
- yield Instance(self)
+ yield Instance(self)
def scope_lookup(self, node, name, offset=0):
if node in self.bases:
@@ -1187,7 +1186,7 @@ class Class(Statement, LocalsDictNodeNG, FilterStmtsMixin):
return None
elif '__metaclass__' in self.root().locals:
assignments = [ass for ass in self.root().locals['__metaclass__']
- if ass.lineno < self.lineno]
+ if ass.lineno < self.lineno]
if not assignments:
return None
assignment = assignments[-1]
@@ -1255,7 +1254,7 @@ class Class(Statement, LocalsDictNodeNG, FilterStmtsMixin):
if infered is YES:
continue
if (not isinstance(infered, Const) or
- not isinstance(infered.value, str)):
+ not isinstance(infered.value, str)):
continue
if not infered.value:
continue
diff --git a/test_utils.py b/test_utils.py
index 144d19fd..f9f4d53f 100644
--- a/test_utils.py
+++ b/test_utils.py
@@ -27,8 +27,8 @@ def _extract_expressions(node):
expression can be found.
"""
if (isinstance(node, nodes.CallFunc)
- and isinstance(node.func, nodes.Name)
- and node.func.name == _TRANSIENT_FUNCTION):
+ and isinstance(node.func, nodes.Name)
+ and node.func.name == _TRANSIENT_FUNCTION):
real_expr = node.args[0]
real_expr.parent = node.parent
# Search for node in all _astng_fields (the fields checked when
@@ -128,7 +128,7 @@ def extract_node(code, module_name=''):
If no statements or expressions are selected, the last toplevel
statement will be returned.
- If the selected statement is a discard statement, (i.e. an expression
+ If the selected statement is a discard statement, (i.e. an expression
turned into a statement), the wrapped expression is returned instead.
For convenience, singleton lists are unpacked.
diff --git a/utils.py b/utils.py
index 1cd0e778..936c8b5a 100644
--- a/utils.py
+++ b/utils.py
@@ -25,7 +25,7 @@ from astroid.exceptions import AstroidBuildingException
from astroid.builder import parse
-class ASTWalker:
+class ASTWalker(object):
"""a walker visiting a tree in preorder, calling on the handler:
* visit_<class name> on entering a node, where class name is the class of
@@ -98,7 +98,7 @@ class LocalsVisitor(ASTWalker):
if methods[0] is not None:
methods[0](node)
if 'locals' in node.__dict__: # skip Instance and other proxy
- for name, local_node in node.items():
+ for local_node in node.values():
self.visit(local_node)
if methods[1] is not None:
return methods[1](node)
@@ -112,12 +112,14 @@ def _check_children(node):
print "Hm, child of %s is None" % node
continue
if not hasattr(child, 'parent'):
- print " ERROR: %s has child %s %x with no parent" % (node, child, id(child))
+ print " ERROR: %s has child %s %x with no parent" % (
+ node, child, id(child))
elif not child.parent:
- print " ERROR: %s has child %s %x with parent %r" % (node, child, id(child), child.parent)
+ print " ERROR: %s has child %s %x with parent %r" % (
+ node, child, id(child), child.parent)
elif child.parent is not node:
- print " ERROR: %s %x has child %s %x with wrong parent %s" % (node,
- id(node), child, id(child), child.parent)
+ print " ERROR: %s %x has child %s %x with wrong parent %s" % (
+ node, id(node), child, id(child), child.parent)
else:
ok = True
if not ok:
@@ -145,7 +147,7 @@ class TreeTester(object):
Module()
body = [
Print()
- dest =
+ dest =
values = [
]
]
@@ -180,8 +182,8 @@ class TreeTester(object):
if _done is None:
_done = set()
if node in _done:
- self._string += '\nloop in tree: %r (%s)' % (node,
- getattr(node, 'lineno', None))
+ self._string += '\nloop in tree: %r (%s)' % (
+ node, getattr(node, 'lineno', None))
return
_done.add(node)
self._string += '\n' + indent + '<%s>' % node.__class__.__name__
@@ -197,7 +199,7 @@ class TreeTester(object):
continue
if a in ("lineno", "col_offset") and not self.lineno:
continue
- self._string +='\n' + indent + a + " = " + repr(attr)
+ self._string += '\n' + indent + a + " = " + repr(attr)
for field in node._fields or ():
attr = node_dict[field]
if attr is None: