summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSylvain Th?nault <sylvain.thenault@logilab.fr>2013-12-22 23:41:57 +0100
committerSylvain Th?nault <sylvain.thenault@logilab.fr>2013-12-22 23:41:57 +0100
commitd8895fcb65ecd958b627298b32b0592565ef137e (patch)
tree57cdbc1a28493d1f131fa2b4a8a3ff6611c7fa2b
parentd3f5227f8903cf72d7de78d0c2a9fc2948b19ca9 (diff)
downloadpylint-d8895fcb65ecd958b627298b32b0592565ef137e.tar.gz
various pylint fixes
-rw-r--r--ChangeLog16
-rw-r--r--checkers/base.py4
-rw-r--r--checkers/classes.py8
-rw-r--r--checkers/design_analysis.py2
-rw-r--r--checkers/exceptions.py14
-rw-r--r--checkers/format.py8
-rw-r--r--checkers/imports.py2
-rw-r--r--checkers/logging.py34
-rw-r--r--checkers/raw_metrics.py4
-rw-r--r--checkers/similar.py18
-rw-r--r--checkers/stdlib.py2
-rw-r--r--checkers/strings.py2
-rw-r--r--checkers/typecheck.py4
-rw-r--r--checkers/utils.py57
-rwxr-xr-xepylint.py33
-rw-r--r--gui.py140
-rw-r--r--lint.py93
-rw-r--r--pyreverse/diadefslib.py2
-rw-r--r--pyreverse/diagrams.py4
-rw-r--r--pyreverse/main.py6
-rw-r--r--pyreverse/utils.py6
-rw-r--r--pyreverse/writer.py28
-rw-r--r--setup.py34
-rw-r--r--testutils.py10
-rw-r--r--utils.py18
25 files changed, 293 insertions, 256 deletions
diff --git a/ChangeLog b/ChangeLog
index f4073c3..497b28d 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -36,7 +36,9 @@ ChangeLog for Pylint
* Added a new warning, 'non-iterator-returned', for non-iterators
returned by '__iter__'.
- * Add new warning for unpacking non-sequences in assignments.
+ * Add new checks for unpacking non-sequences in assignments
+ (unpacking-non-sequence) as well as unbalanced tuple unpacking
+ (unbalanced-tuple-unpacking).
* useless-else-on-loop not emited if there is a break in the
else clause of inner loop (#117).
@@ -47,7 +49,19 @@ ChangeLog for Pylint
current implementation. Deactivate it until we have something
better. See #112 for instance.
+ * Use attribute regexp for properties in python3, as in python2
+ * Create the PYLINTHOME directory when needed, it might fail and lead to
+ spurious warnings on import of pylint.config.
+
+ * Fix setup.py so that pylint properly install on Windows when using python3
+
+ * Various documentation fixes and enhancements
+
+ * Added a __main__.py file so you can run "python -m pylint"
+
+ * Fix issue #55 (false-positive trailing-whitespace on Windows)
+
2013-08-06 -- 1.0.0
* Add check for the use of 'exec' function
diff --git a/checkers/base.py b/checkers/base.py
index 7aa9213..d2be803 100644
--- a/checkers/base.py
+++ b/checkers/base.py
@@ -257,7 +257,7 @@ class BasicErrorChecker(_BasicChecker):
not (v is None or
(isinstance(v, astroid.Const) and v.value is None) or
(isinstance(v, astroid.Name) and v.name == 'None')
- ) ]:
+ )]:
self.add_message('return-in-init', node=node)
elif node.is_generator():
# make sure we don't mix non-None returns and yields
@@ -434,7 +434,7 @@ functions, methods
'used, separated by a comma'}
),
)
- reports = ( ('RP0101', 'Statistics by type', report_by_type_stats), )
+ reports = (('RP0101', 'Statistics by type', report_by_type_stats),)
def __init__(self, linter):
_BasicChecker.__init__(self, linter)
diff --git a/checkers/classes.py b/checkers/classes.py
index fd76146..fc09021 100644
--- a/checkers/classes.py
+++ b/checkers/classes.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2003-2012 LOGILAB S.A. (Paris, FRANCE).
+# Copyright (c) 2003-2013 LOGILAB S.A. (Paris, FRANCE).
# http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This program is free software; you can redistribute it and/or modify it under
@@ -183,7 +183,7 @@ class ClassChecker(BaseChecker):
options = (('ignore-iface-methods',
{'default' : (#zope interface
'isImplementedBy', 'deferred', 'extends', 'names',
- 'namesAndDescriptions', 'queryDescriptionFor', 'getBases',
+ 'namesAndDescriptions', 'queryDescriptionFor', 'getBases',
'getDescriptionFor', 'getDoc', 'getName', 'getTaggedValue',
'getTaggedValueTags', 'isEqualOrExtendedBy', 'setTaggedValue',
'isImplementedByInstancesOf',
@@ -355,10 +355,10 @@ a metaclass class method.'}
positional = sum(1 for arg in node.args.args if arg.name != 'self')
if positional < 3 and not node.args.vararg:
self.add_message('bad-context-manager',
- node=node)
+ node=node)
elif positional > 3:
self.add_message('bad-context-manager',
- node=node)
+ node=node)
def leave_function(self, node):
"""on method node, check if this method couldn't be a function
diff --git a/checkers/design_analysis.py b/checkers/design_analysis.py
index ca201f3..11defbf 100644
--- a/checkers/design_analysis.py
+++ b/checkers/design_analysis.py
@@ -332,7 +332,7 @@ class MisdesignChecker(BaseChecker):
"""increments the branches counter"""
branches = 1
# don't double count If nodes coming from some 'elif'
- if node.orelse and (len(node.orelse)>1 or
+ if node.orelse and (len(node.orelse) > 1 or
not isinstance(node.orelse[0], If)):
branches += 1
self._inc_branch(branches)
diff --git a/checkers/exceptions.py b/checkers/exceptions.py
index 8ac00a5..9843001 100644
--- a/checkers/exceptions.py
+++ b/checkers/exceptions.py
@@ -50,7 +50,7 @@ MSGS = {
'catching-non-exception',
'Used when a class which doesn\'t inherit from \
BaseException is used as an exception in an except clause.'),
-
+
'W0701': ('Raising a string exception',
'raising-string',
'Used when a string exception is raised.'),
@@ -141,10 +141,10 @@ class ExceptionsChecker(BaseChecker):
isinstance(expr, (astroid.List, astroid.Dict, astroid.Tuple,
astroid.Module, astroid.Function)):
self.add_message('E0702', node=node, args=expr.name)
- elif ( (isinstance(expr, astroid.Name) and expr.name == 'NotImplemented')
- or (isinstance(expr, astroid.CallFunc) and
- isinstance(expr.func, astroid.Name) and
- expr.func.name == 'NotImplemented') ):
+ elif ((isinstance(expr, astroid.Name) and expr.name == 'NotImplemented')
+ or (isinstance(expr, astroid.CallFunc) and
+ isinstance(expr.func, astroid.Name) and
+ expr.func.name == 'NotImplemented')):
self.add_message('E0711', node=node)
elif isinstance(expr, astroid.BinOp) and expr.op == '%':
self.add_message('W0701', node=node)
@@ -211,10 +211,10 @@ class ExceptionsChecker(BaseChecker):
and exc.root().name == EXCEPTIONS_MODULE
and nb_handlers == 1 and not is_raising(handler.body)):
self.add_message('W0703', args=exc.name, node=handler.type)
-
+
if (not inherit_from_std_ex(exc) and
exc.root().name != BUILTINS_NAME):
- self.add_message('catching-non-exception',
+ self.add_message('catching-non-exception',
node=handler.type,
args=(exc.name, ))
diff --git a/checkers/format.py b/checkers/format.py
index 45a7477..aab2320 100644
--- a/checkers/format.py
+++ b/checkers/format.py
@@ -214,7 +214,6 @@ class FormatChecker(BaseTokenChecker):
if tokens[start+1][1] != '(':
return
- found_comma = False
found_and_or = False
depth = 0
keyword_token = tokens[start][1]
@@ -302,7 +301,7 @@ class FormatChecker(BaseTokenChecker):
else:
self._check_space(tokens, i, (_MUST, _MUST))
- def _open_lambda(self, unused_tokens, unused_i):
+ def _open_lambda(self, tokens, i): # pylint:disable=unused-argument
self._bracket_stack.append('lambda')
def _handle_colon(self, tokens, i):
@@ -357,7 +356,6 @@ class FormatChecker(BaseTokenChecker):
pairs = [(tokens[i-1], tokens[i]), (tokens[i], tokens[i+1])]
for other_idx, (policy, token_pair) in enumerate(zip(policies, pairs)):
- current_idx = 1 - other_idx
if token_pair[other_idx][0] in _EOL or policy == _IGNORE:
continue
@@ -503,7 +501,7 @@ class FormatChecker(BaseTokenChecker):
if line_num > self.config.max_module_lines:
self.add_message('C0302', args=line_num, line=1)
- @check_messages('C0321' ,'C03232', 'C0323', 'C0324')
+ @check_messages('C0321', 'C03232', 'C0323', 'C0324')
def visit_default(self, node):
"""check the node line number and check it if not yet done"""
if not node.is_statement:
@@ -608,7 +606,7 @@ class FormatChecker(BaseTokenChecker):
self.add_message('W0312', args=args, line=line_num)
return level
suppl += string[0]
- string = string [1:]
+ string = string[1:]
if level != expected or suppl:
i_type = 'spaces'
if indent[0] == '\t':
diff --git a/checkers/imports.py b/checkers/imports.py
index 7068dcb..b0a9872 100644
--- a/checkers/imports.py
+++ b/checkers/imports.py
@@ -93,7 +93,7 @@ def dependencies_graph(filename, dep_info):
"""write dependencies as a dot (graphviz) file
"""
done = {}
- printer = DotBackend(filename[:-4], rankdir = "LR")
+ printer = DotBackend(filename[:-4], rankdir='LR')
printer.emit('URL="." node[shape="box"]')
for modname, dependencies in sorted(dep_info.iteritems()):
done[modname] = 1
diff --git a/checkers/logging.py b/checkers/logging.py
index 6986ca4..d1f9d36 100644
--- a/checkers/logging.py
+++ b/checkers/logging.py
@@ -91,7 +91,7 @@ class LoggingChecker(checkers.BaseChecker):
and ancestor.parent.name == 'logging')))]
except astroid.exceptions.InferenceError:
return
- if (node.func.expr.name != self._logging_name and not logger_class):
+ if node.func.expr.name != self._logging_name and not logger_class:
return
self._check_convenience_methods(node)
self._check_log_methods(node)
@@ -129,7 +129,7 @@ class LoggingChecker(checkers.BaseChecker):
node: AST node to be checked.
format_arg: Index of the format string in the node arguments.
"""
- num_args = self._count_supplied_tokens(node.args[format_arg + 1:])
+ num_args = _count_supplied_tokens(node.args[format_arg + 1:])
if not num_args:
# If no args were supplied, then all format strings are valid -
# don't check any further.
@@ -147,9 +147,10 @@ class LoggingChecker(checkers.BaseChecker):
# Keyword checking on logging strings is complicated by
# special keywords - out of scope.
return
- except utils.UnsupportedFormatCharacter, e:
- c = format_string[e.index]
- self.add_message('E1200', node=node, args=(c, ord(c), e.index))
+ except utils.UnsupportedFormatCharacter, ex:
+ char = format_string[ex.index]
+ self.add_message('E1200', node=node,
+ args=(char, ord(char), ex.index))
return
except utils.IncompleteFormatString:
self.add_message('E1201', node=node)
@@ -159,20 +160,21 @@ class LoggingChecker(checkers.BaseChecker):
elif num_args < required_num_args:
self.add_message('E1206', node=node)
- def _count_supplied_tokens(self, args):
- """Counts the number of tokens in an args list.
- The Python log functions allow for special keyword arguments: func,
- exc_info and extra. To handle these cases correctly, we only count
- arguments that aren't keywords.
+def _count_supplied_tokens(args):
+ """Counts the number of tokens in an args list.
- Args:
- args: List of AST nodes that are arguments for a log format string.
+ The Python log functions allow for special keyword arguments: func,
+ exc_info and extra. To handle these cases correctly, we only count
+ arguments that aren't keywords.
- Returns:
- Number of AST nodes that aren't keywords.
- """
- return sum(1 for arg in args if not isinstance(arg, astroid.Keyword))
+ Args:
+ args: List of AST nodes that are arguments for a log format string.
+
+ Returns:
+ Number of AST nodes that aren't keywords.
+ """
+ return sum(1 for arg in args if not isinstance(arg, astroid.Keyword))
def register(linter):
diff --git a/checkers/raw_metrics.py b/checkers/raw_metrics.py
index a8e4367..23e45b0 100644
--- a/checkers/raw_metrics.py
+++ b/checkers/raw_metrics.py
@@ -68,11 +68,11 @@ class RawMetricsChecker(BaseTokenChecker):
# configuration section name
name = 'metrics'
# configuration options
- options = ( )
+ options = ()
# messages
msgs = {}
# reports
- reports = ( ('RP0701', 'Raw metrics', report_raw_stats), )
+ reports = (('RP0701', 'Raw metrics', report_raw_stats),)
def __init__(self, linter):
BaseTokenChecker.__init__(self, linter)
diff --git a/checkers/similar.py b/checkers/similar.py
index 26b3725..8d755fa 100644
--- a/checkers/similar.py
+++ b/checkers/similar.py
@@ -63,15 +63,15 @@ class Similar(object):
duplicate = no_duplicates.setdefault(num, [])
for couples in duplicate:
if (lineset1, idx1) in couples or (lineset2, idx2) in couples:
- couples.add( (lineset1, idx1) )
- couples.add( (lineset2, idx2) )
+ couples.add((lineset1, idx1))
+ couples.add((lineset2, idx2))
break
else:
- duplicate.append( set([(lineset1, idx1), (lineset2, idx2)]) )
+ duplicate.append(set([(lineset1, idx1), (lineset2, idx2)]))
sims = []
for num, ensembles in no_duplicates.iteritems():
for couples in ensembles:
- sims.append( (num, couples) )
+ sims.append((num, couples))
sims.sort()
sims.reverse()
return sims
@@ -104,7 +104,7 @@ class Similar(object):
while index1 < len(lineset1):
skip = 1
num = 0
- for index2 in find( lineset1[index1] ):
+ for index2 in find(lineset1[index1]):
non_blank = 0
for num, ((_, line1), (_, line2)) in enumerate(
izip(lines1(index1), lines2(index2))):
@@ -210,7 +210,7 @@ class LineSet(object):
index = {}
for line_no, line in enumerate(self._stripped_lines):
if line:
- index.setdefault(line, []).append( line_no )
+ index.setdefault(line, []).append(line_no)
return index
@@ -260,7 +260,7 @@ class SimilarChecker(BaseChecker, Similar):
),
)
# reports
- reports = ( ('RP0801', 'Duplication', report_similarities), )
+ reports = (('RP0801', 'Duplication', report_similarities),)
def __init__(self, linter=None):
BaseChecker.__init__(self, linter)
@@ -349,9 +349,9 @@ def Run(argv=None):
usage()
elif opt in ('-i', '--ignore-comments'):
ignore_comments = True
- elif opt in ('--ignore-docstrings'):
+ elif opt in ('--ignore-docstrings',):
ignore_docstrings = True
- elif opt in ('--ignore-imports'):
+ elif opt in ('--ignore-imports',):
ignore_imports = True
if not args:
usage(1)
diff --git a/checkers/stdlib.py b/checkers/stdlib.py
index 07e1fbe..b63760c 100644
--- a/checkers/stdlib.py
+++ b/checkers/stdlib.py
@@ -21,7 +21,7 @@ import sys
import astroid
from pylint.interfaces import IAstroidChecker
-from pylint.checkers import BaseChecker, BaseTokenChecker
+from pylint.checkers import BaseChecker
from pylint.checkers import utils
_VALID_OPEN_MODE_REGEX = r'^(r?U|[rwa]\+?b?)$'
diff --git a/checkers/strings.py b/checkers/strings.py
index 42563da..b2dd167 100644
--- a/checkers/strings.py
+++ b/checkers/strings.py
@@ -233,7 +233,7 @@ class StringConstantChecker(BaseTokenChecker):
if c in '\'\"':
quote_char = c
break
- prefix = token[:i].lower() # markers like u, b, r.
+ prefix = token[:i].lower() # markers like u, b, r.
after_prefix = token[i:]
if after_prefix[:3] == after_prefix[-3:] == 3 * quote_char:
string_body = after_prefix[3:-3]
diff --git a/checkers/typecheck.py b/checkers/typecheck.py
index 6988359..2e3785e 100644
--- a/checkers/typecheck.py
+++ b/checkers/typecheck.py
@@ -1,4 +1,4 @@
-# Copyright (c) 2006-2010 LOGILAB S.A. (Paris, FRANCE).
+# Copyright (c) 2006-2013 LOGILAB S.A. (Paris, FRANCE).
# http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This program is free software; you can redistribute it and/or modify it under
@@ -292,7 +292,7 @@ accessed. Python regular expressions are accepted.'}
# Built-in functions have no argument information.
return
- if len( called.argnames() ) != len( set( called.argnames() ) ):
+ if len(called.argnames()) != len(set(called.argnames())):
# Duplicate parameter name (see E9801). We can't really make sense
# of the function call in this case, so just return.
return
diff --git a/checkers/utils.py b/checkers/utils.py
index 72a9733..53b40a6 100644
--- a/checkers/utils.py
+++ b/checkers/utils.py
@@ -69,8 +69,9 @@ def clobber_in_except(node):
scope, stmts = node.lookup(name)
if (stmts and
not isinstance(stmts[0].ass_type(),
- (astroid.Assign, astroid.AugAssign, astroid.ExceptHandler))):
- return (True, (name, 'outer scope (line %s)' % (stmts[0].fromlineno,)))
+ (astroid.Assign, astroid.AugAssign,
+ astroid.ExceptHandler))):
+ return (True, (name, 'outer scope (line %s)' % stmts[0].fromlineno))
return (False, None)
@@ -164,7 +165,7 @@ def is_defined_before(var_node):
break
elif isinstance(_node, astroid.ExceptHandler):
if isinstance(_node.name, astroid.AssName):
- ass_node=_node.name
+ ass_node = _node.name
if ass_node.name == varname:
return True
_node = _node.parent
@@ -176,7 +177,7 @@ def is_defined_before(var_node):
for ass_node in _node.nodes_of_class(astroid.AssName):
if ass_node.name == varname:
return True
- for imp_node in _node.nodes_of_class( (astroid.From, astroid.Import)):
+ for imp_node in _node.nodes_of_class((astroid.From, astroid.Import)):
if varname in [name[1] or name[0] for name in imp_node.names]:
return True
_node = _node.previous_sibling()
@@ -301,52 +302,52 @@ def parse_format_string(format_string):
return (i, format_string[i])
i = 0
while i < len(format_string):
- c = format_string[i]
- if c == '%':
- i, c = next_char(i)
+ char = format_string[i]
+ if char == '%':
+ i, char = next_char(i)
# Parse the mapping key (optional).
key = None
- if c == '(':
+ if char == '(':
depth = 1
- i, c = next_char(i)
+ i, char = next_char(i)
key_start = i
while depth != 0:
- if c == '(':
+ if char == '(':
depth += 1
- elif c == ')':
+ elif char == ')':
depth -= 1
- i, c = next_char(i)
+ i, char = next_char(i)
key_end = i - 1
key = format_string[key_start:key_end]
# Parse the conversion flags (optional).
- while c in '#0- +':
- i, c = next_char(i)
+ while char in '#0- +':
+ i, char = next_char(i)
# Parse the minimum field width (optional).
- if c == '*':
+ if char == '*':
num_args += 1
- i, c = next_char(i)
+ i, char = next_char(i)
else:
- while c in string.digits:
- i, c = next_char(i)
+ while char in string.digits:
+ i, char = next_char(i)
# Parse the precision (optional).
- if c == '.':
- i, c = next_char(i)
- if c == '*':
+ if char == '.':
+ i, char = next_char(i)
+ if char == '*':
num_args += 1
- i, c = next_char(i)
+ i, char = next_char(i)
else:
- while c in string.digits:
- i, c = next_char(i)
+ while char in string.digits:
+ i, char = next_char(i)
# Parse the length modifier (optional).
- if c in 'hlL':
- i, c = next_char(i)
+ if char in 'hlL':
+ i, char = next_char(i)
# Parse the conversion type (mandatory).
- if c not in 'diouxXeEfFgGcrs%':
+ if char not in 'diouxXeEfFgGcrs%':
raise UnsupportedFormatCharacter(i)
if key:
keys.add(key)
- elif c != '%':
+ elif char != '%':
num_args += 1
i += 1
return keys, num_args
diff --git a/epylint.py b/epylint.py
index b782245..24baa61 100755
--- a/epylint.py
+++ b/epylint.py
@@ -47,6 +47,7 @@ its output.
"""
import sys, os, re
+import os.path as osp
from subprocess import Popen, PIPE
@@ -67,34 +68,36 @@ def lint(filename, options=None):
the tree)
"""
# traverse downwards until we are out of a python package
- fullPath = os.path.abspath(filename)
- parentPath, childPath = os.path.dirname(fullPath), os.path.basename(fullPath)
+ full_path = osp.abspath(filename)
+ parent_path = osp.dirname(full_path)
+ child_path = osp.basename(full_path)
- while parentPath != "/" and os.path.exists(os.path.join(parentPath, '__init__.py')):
- childPath = os.path.join(os.path.basename(parentPath), childPath)
- parentPath = os.path.dirname(parentPath)
+ while parent_path != "/" and osp.exists(osp.join(parent_path, '__init__.py')):
+ child_path = osp.join(osp.basename(parent_path), child_path)
+ parent_path = osp.dirname(parent_path)
# Start pylint
# Ensure we use the python and pylint associated with the running epylint
- from pylint import lint
- lintPath = lint.__file__
+ from pylint import lint as lint_mod
+ lint_path = lint_mod.__file__
options = options or ['--disable=C,R,I']
- cmd = [sys.executable, lintPath] + options + ['--msg-template',
- '{path}:{line}: [{symbol}, {obj}] {msg}', '-r', 'n', childPath]
- process = Popen(cmd, stdout=PIPE, cwd=parentPath, universal_newlines=True)
+ cmd = [sys.executable, lint_path] + options + ['--msg-template',
+ '{path}:{line}: [{symbol}, {obj}] {msg}', '-r', 'n', child_path]
+ process = Popen(cmd, stdout=PIPE, cwd=parent_path, universal_newlines=True)
# The parseable line format is '%(path)s:%(line)s: [%(sigle)s%(obj)s] %(msg)s'
# NOTE: This would be cleaner if we added an Emacs reporter to pylint.reporters.text ..
regex = re.compile(r"\[(?P<type>[WE])(?P<remainder>.*?)\]")
- def _replacement(mObj):
+ def _replacement(match_object):
"Alter to include 'Error' or 'Warning'"
- if mObj.group("type") == "W":
+ if match_object.group("type") == "W":
replacement = "Warning"
else:
replacement = "Error"
# replace as "Warning (W0511, funcName): Warning Text"
- return "%s (%s%s):" % (replacement, mObj.group("type"), mObj.group("remainder"))
+ return "%s (%s%s):" % (replacement, match_object.group("type"),
+ match_object.group("remainder"))
for line in process.stdout:
# remove pylintrc warning
@@ -103,7 +106,7 @@ def lint(filename, options=None):
line = regex.sub(_replacement, line, 1)
# modify the file name thats output to reverse the path traversal we made
parts = line.split(":")
- if parts and parts[0] == childPath:
+ if parts and parts[0] == child_path:
line = ":".join([filename] + parts[1:])
print line,
@@ -167,7 +170,7 @@ def Run():
if len(sys.argv) == 1:
print "Usage: %s <filename> [options]" % sys.argv[0]
sys.exit(1)
- elif not os.path.exists(sys.argv[1]):
+ elif not osp.exists(sys.argv[1]):
print "%s does not exist" % sys.argv[1]
sys.exit(1)
else:
diff --git a/gui.py b/gui.py
index 06e7391..1011ceb 100644
--- a/gui.py
+++ b/gui.py
@@ -56,19 +56,19 @@ class BasicStream(object):
self.contents = []
self.outdict = {}
self.currout = None
- self.nextTitle = None
+ self.next_title = None
def write(self, text):
"""write text to the stream"""
if re.match('^--+$', text.strip()) or re.match('^==+$', text.strip()):
if self.currout:
- self.outdict[self.currout].remove(self.nextTitle)
+ self.outdict[self.currout].remove(self.next_title)
self.outdict[self.currout].pop()
- self.currout = self.nextTitle
+ self.currout = self.next_title
self.outdict[self.currout] = ['']
if text.strip():
- self.nextTitle = text.strip()
+ self.next_title = text.strip()
if text.startswith(os.linesep):
self.contents.append('')
@@ -85,8 +85,8 @@ class BasicStream(object):
def fix_contents(self):
"""finalize what the contents of the dict should look like before output"""
for item in self.outdict:
- numEmpty = self.outdict[item].count('')
- for _ in xrange(numEmpty):
+ num_empty = self.outdict[item].count('')
+ for _ in xrange(num_empty):
self.outdict[item].remove('')
if self.outdict[item]:
self.outdict[item].pop(0)
@@ -105,7 +105,7 @@ class BasicStream(object):
self.contents = []
self.outdict = {}
self.currout = None
- self.nextTitle = None
+ self.next_title = None
class LintGui(object):
@@ -126,7 +126,7 @@ class LintGui(object):
self.tabs = {}
self.report_stream = BasicStream(self)
#gui objects
- self.lbMessages = None
+ self.lb_messages = None
self.showhistory = None
self.results = None
self.btnRun = None
@@ -171,14 +171,14 @@ class LintGui(object):
rightscrollbar.pack(side=RIGHT, fill=Y)
bottomscrollbar = Scrollbar(msg_frame, orient=HORIZONTAL)
bottomscrollbar.pack(side=BOTTOM, fill=X)
- self.lbMessages = Listbox(msg_frame,
+ self.lb_messages = Listbox(msg_frame,
yscrollcommand=rightscrollbar.set,
xscrollcommand=bottomscrollbar.set,
bg="white")
- self.lbMessages.bind("<Double-Button-1>", self.show_sourcefile)
- self.lbMessages.pack(expand=True, fill=BOTH)
- rightscrollbar.config(command=self.lbMessages.yview)
- bottomscrollbar.config(command=self.lbMessages.xview)
+ self.lb_messages.bind("<Double-Button-1>", self.show_sourcefile)
+ self.lb_messages.pack(expand=True, fill=BOTH)
+ rightscrollbar.config(command=self.lb_messages.yview)
+ bottomscrollbar.config(command=self.lb_messages.xview)
#History ListBoxes
rightscrollbar2 = Scrollbar(history_frame)
@@ -199,18 +199,18 @@ class LintGui(object):
self.status = Label(self.root, text="", bd=1, relief=SUNKEN, anchor=W)
self.status.pack(side=BOTTOM, fill=X)
- #labels
- self.lblRatingLabel = Label(rating_frame, text='Rating:')
- self.lblRatingLabel.pack(side=LEFT)
- self.lblRating = Label(rating_frame, textvariable=self.rating)
- self.lblRating.pack(side=LEFT)
+ #labelbl_ratingls
+ lbl_rating_label = Label(rating_frame, text='Rating:')
+ lbl_rating_label.pack(side=LEFT)
+ lbl_rating = Label(rating_frame, textvariable=self.rating)
+ lbl_rating.pack(side=LEFT)
Label(mid_frame, text='Recently Used:').pack(side=LEFT)
Label(top_frame, text='Module or package').pack(side=LEFT)
#file textbox
- self.txtModule = Entry(top_frame, background='white')
- self.txtModule.bind('<Return>', self.run_lint)
- self.txtModule.pack(side=LEFT, expand=True, fill=X)
+ self.txt_module = Entry(top_frame, background='white')
+ self.txt_module.bind('<Return>', self.run_lint)
+ self.txt_module.pack(side=LEFT, expand=True, fill=X)
#results box
rightscrollbar = Scrollbar(res_frame)
@@ -228,7 +228,7 @@ class LintGui(object):
#buttons
Button(top_frame, text='Open', command=self.file_open).pack(side=LEFT)
Button(top_frame, text='Open Package',
- command=(lambda : self.file_open(package=True))).pack(side=LEFT)
+ command=(lambda: self.file_open(package=True))).pack(side=LEFT)
self.btnRun = Button(top_frame, text='Run', command=self.run_lint)
self.btnRun.pack(side=LEFT)
@@ -269,45 +269,53 @@ class LintGui(object):
#check boxes
self.box = StringVar()
# XXX should be generated
- report = Radiobutton(radio_frame, text="Report", variable=self.box,
- value="Report", command=self.refresh_results_window)
- rawMet = Radiobutton(radio_frame, text="Raw metrics", variable=self.box,
- value="Raw metrics", command=self.refresh_results_window)
- dup = Radiobutton(radio_frame, text="Duplication", variable=self.box,
- value="Duplication", command=self.refresh_results_window)
- ext = Radiobutton(radio_frame, text="External dependencies",
- variable=self.box, value="External dependencies",
- command=self.refresh_results_window)
- stat = Radiobutton(radio_frame, text="Statistics by type",
- variable=self.box, value="Statistics by type",
- command=self.refresh_results_window)
- msgCat = Radiobutton(radio_frame, text="Messages by category",
- variable=self.box, value="Messages by category",
- command=self.refresh_results_window)
- msg = Radiobutton(radio_frame, text="Messages", variable=self.box,
- value="Messages", command=self.refresh_results_window)
- sourceFile = Radiobutton(radio_frame, text="Source File", variable=self.box,
- value="Source File", command=self.refresh_results_window)
+ report = Radiobutton(
+ radio_frame, text="Report", variable=self.box,
+ value="Report", command=self.refresh_results_window)
+ raw_met = Radiobutton(
+ radio_frame, text="Raw metrics", variable=self.box,
+ value="Raw metrics", command=self.refresh_results_window)
+ dup = Radiobutton(
+ radio_frame, text="Duplication", variable=self.box,
+ value="Duplication", command=self.refresh_results_window)
+ ext = Radiobutton(
+ radio_frame, text="External dependencies",
+ variable=self.box, value="External dependencies",
+ command=self.refresh_results_window)
+ stat = Radiobutton(
+ radio_frame, text="Statistics by type",
+ variable=self.box, value="Statistics by type",
+ command=self.refresh_results_window)
+ msg_cat = Radiobutton(
+ radio_frame, text="Messages by category",
+ variable=self.box, value="Messages by category",
+ command=self.refresh_results_window)
+ msg = Radiobutton(
+ radio_frame, text="Messages", variable=self.box,
+ value="Messages", command=self.refresh_results_window)
+ source_file = Radiobutton(
+ radio_frame, text="Source File", variable=self.box,
+ value="Source File", command=self.refresh_results_window)
report.select()
report.grid(column=0, row=0, sticky=W)
- rawMet.grid(column=1, row=0, sticky=W)
+ raw_met.grid(column=1, row=0, sticky=W)
dup.grid(column=2, row=0, sticky=W)
msg.grid(column=3, row=0, sticky=W)
stat.grid(column=0, row=1, sticky=W)
- msgCat.grid(column=1, row=1, sticky=W)
+ msg_cat.grid(column=1, row=1, sticky=W)
ext.grid(column=2, row=1, sticky=W)
- sourceFile.grid(column=3, row=1, sticky=W)
+ source_file.grid(column=3, row=1, sticky=W)
#dictionary for check boxes and associated error term
self.msg_type_dict = {
- 'I' : lambda : self.information_box.get() == 1,
- 'C' : lambda : self.convention_box.get() == 1,
- 'R' : lambda : self.refactor_box.get() == 1,
- 'E' : lambda : self.error_box.get() == 1,
- 'W' : lambda : self.warning_box.get() == 1,
- 'F' : lambda : self.fatal_box.get() == 1
+ 'I': lambda: self.information_box.get() == 1,
+ 'C': lambda: self.convention_box.get() == 1,
+ 'R': lambda: self.refactor_box.get() == 1,
+ 'E': lambda: self.error_box.get() == 1,
+ 'W': lambda: self.warning_box.get() == 1,
+ 'F': lambda: self.fatal_box.get() == 1
}
- self.txtModule.focus_set()
+ self.txt_module.focus_set()
def select_recent_file(self, event):
@@ -318,21 +326,21 @@ class LintGui(object):
selected = self.showhistory.curselection()
item = self.showhistory.get(selected)
#update module
- self.txtModule.delete(0, END)
- self.txtModule.insert(0, item)
+ self.txt_module.delete(0, END)
+ self.txt_module.insert(0, item)
def refresh_msg_window(self):
"""refresh the message window with current output"""
#clear the window
- self.lbMessages.delete(0, END)
+ self.lb_messages.delete(0, END)
self.visible_msgs = []
for msg in self.msgs:
- if (self.msg_type_dict.get(msg.C)()):
+ if self.msg_type_dict.get(msg.C)():
self.visible_msgs.append(msg)
msg_str = convert_to_string(msg)
- self.lbMessages.insert(END, msg_str)
+ self.lb_messages.insert(END, msg_str)
fg_color = COLORS.get(msg_str[:3], 'black')
- self.lbMessages.itemconfigure(END, fg=fg_color)
+ self.lb_messages.itemconfigure(END, fg=fg_color)
def refresh_results_window(self):
"""refresh the results window with current output"""
@@ -357,12 +365,12 @@ class LintGui(object):
self.msgs.append(msg)
#displaying msg if message type is selected in check box
- if (self.msg_type_dict.get(msg.C)()):
+ if self.msg_type_dict.get(msg.C)():
self.visible_msgs.append(msg)
msg_str = convert_to_string(msg)
- self.lbMessages.insert(END, msg_str)
+ self.lb_messages.insert(END, msg_str)
fg_color = COLORS.get(msg_str[:3], 'black')
- self.lbMessages.itemconfigure(END, fg=fg_color)
+ self.lb_messages.itemconfigure(END, fg=fg_color)
except Queue.Empty:
pass
@@ -399,12 +407,12 @@ class LintGui(object):
if filename == ():
return
- self.txtModule.delete(0, END)
- self.txtModule.insert(0, filename)
+ self.txt_module.delete(0, END)
+ self.txt_module.insert(0, filename)
def update_filenames(self):
"""update the list of recent filenames"""
- filename = self.txtModule.get()
+ filename = self.txt_module.get()
if not filename:
filename = os.getcwd()
if filename+'\n' in self.filenames:
@@ -437,14 +445,14 @@ class LintGui(object):
self.update_filenames()
self.root.configure(cursor='watch')
self.reporter = GUIReporter(self, output=self.report_stream)
- module = self.txtModule.get()
+ module = self.txt_module.get()
if not module:
module = os.getcwd()
#cleaning up msgs and windows
self.msgs = []
self.visible_msgs = []
- self.lbMessages.delete(0, END)
+ self.lb_messages.delete(0, END)
self.tabs = {}
self.results.delete(0, END)
self.btnRun.config(state=DISABLED)
@@ -464,7 +472,7 @@ class LintGui(object):
self.root.configure(cursor='')
def show_sourcefile(self, event=None):
- selected = self.lbMessages.curselection()
+ selected = self.lb_messages.curselection()
if not selected:
return
diff --git a/lint.py b/lint.py
index 2621240..4cf5059 100644
--- a/lint.py
+++ b/lint.py
@@ -82,48 +82,49 @@ MSGS = {
module (unable to find it for instance).'),
'F0002': ('%s: %s',
'astroid-error',
- 'Used when an unexpected error occurred while building the Astroid \
- representation. This is usually accompanied by a traceback. \
- Please report such errors !'),
+ 'Used when an unexpected error occurred while building the '
+ 'Astroid representation. This is usually accompanied by a '
+ 'traceback. Please report such errors !'),
'F0003': ('ignored builtin module %s',
'ignored-builtin-module',
- 'Used to indicate that the user asked to analyze a builtin module \
- which has been skipped.'),
+ 'Used to indicate that the user asked to analyze a builtin '
+ 'module which has been skipped.'),
'F0004': ('unexpected inferred value %s',
'unexpected-inferred-value',
- 'Used to indicate that some value of an unexpected type has been \
- inferred.'),
+ 'Used to indicate that some value of an unexpected type has been '
+ 'inferred.'),
'F0010': ('error while code parsing: %s',
'parse-error',
- 'Used when an exception occured while building the Astroid \
- representation which could be handled by astroid.'),
+ 'Used when an exception occured while building the Astroid '
+ 'representation which could be handled by astroid.'),
'I0001': ('Unable to run raw checkers on built-in module %s',
'raw-checker-failed',
- 'Used to inform that a built-in module has not been checked \
- using the raw checkers.'),
+ 'Used to inform that a built-in module has not been checked '
+ 'using the raw checkers.'),
'I0010': ('Unable to consider inline option %r',
'bad-inline-option',
- 'Used when an inline option is either badly formatted or can\'t \
- be used inside modules.'),
+ 'Used when an inline option is either badly formatted or can\'t '
+ 'be used inside modules.'),
'I0011': ('Locally disabling %s',
'locally-disabled',
- 'Used when an inline option disables a message or a messages \
- category.'),
+ 'Used when an inline option disables a message or a messages '
+ 'category.'),
'I0012': ('Locally enabling %s',
'locally-enabled',
- 'Used when an inline option enables a message or a messages \
- category.'),
+ 'Used when an inline option enables a message or a messages '
+ 'category.'),
'I0013': ('Ignoring entire file',
'file-ignored',
'Used to inform that the file will not be checked'),
- 'I0014': ('Used deprecated directive "pylint:disable-all" or "pylint:disable=all"',
+ 'I0014': ('Used deprecated directive "pylint:disable-all" or '
+ '"pylint:disable=all"',
'deprecated-disable-all',
'You should preferably use "pylint:skip-file" as this directive '
- 'has a less confusing name. Do this only if you are sure that all '
- 'people running Pylint on your code have version >= 0.26'),
+ 'has a less confusing name. Do this only if you are sure that '
+ 'all people running Pylint on your code have version >= 0.26'),
'I0020': ('Suppressed %s (from line %d)',
'suppressed-message',
'A message was triggered on a line, but suppressed explicitly '
@@ -181,8 +182,8 @@ class PyLinter(OptionsManagerMixIn, MessagesHandlerMixIn, ReportsHandlerMixIn,
return (('ignore',
{'type' : 'csv', 'metavar' : '<file>[,<file>...]',
'dest' : 'black_list', 'default' : ('CVS',),
- 'help' : 'Add files or directories to the blacklist. \
-They should be base names, not paths.'}),
+ 'help' : 'Add files or directories to the blacklist. '
+ 'They should be base names, not paths.'}),
('persistent',
{'default': True, 'type' : 'yn', 'metavar' : '<y_or_n>',
'level': 1,
@@ -191,8 +192,9 @@ They should be base names, not paths.'}),
('load-plugins',
{'type' : 'csv', 'metavar' : '<modules>', 'default' : (),
'level': 1,
- 'help' : 'List of plugins (as comma separated values of \
-python modules names) to load, usually to register additional checkers.'}),
+ 'help' : 'List of plugins (as comma separated values of '
+ 'python modules names) to load, usually to register '
+ 'additional checkers.'}),
('output-format',
{'default': 'text', 'type': 'string', 'metavar' : '<format>',
@@ -206,22 +208,23 @@ python modules names) to load, usually to register additional checkers.'}),
('files-output',
{'default': 0, 'type' : 'yn', 'metavar' : '<y_or_n>',
'group': 'Reports', 'level': 1,
- 'help' : 'Put messages in a separate file for each module / \
-package specified on the command line instead of printing them on stdout. \
-Reports (if any) will be written in a file name "pylint_global.[txt|html]".'}),
+ 'help' : 'Put messages in a separate file for each module / '
+ 'package specified on the command line instead of printing '
+ 'them on stdout. Reports (if any) will be written in a file '
+ 'name "pylint_global.[txt|html]".'}),
('reports',
{'default': 1, 'type' : 'yn', 'metavar' : '<y_or_n>',
'short': 'r',
'group': 'Reports',
- 'help' : 'Tells whether to display a full report or only the\
- messages'}),
+ 'help' : 'Tells whether to display a full report or only the '
+ 'messages'}),
('evaluation',
{'type' : 'string', 'metavar' : '<python_expression>',
'group': 'Reports', 'level': 1,
- 'default': '10.0 - ((float(5 * error + warning + refactor + \
-convention) / statement) * 10)',
+ 'default': '10.0 - ((float(5 * error + warning + refactor + '
+ 'convention) / statement) * 10)',
'help' : 'Python expression which should return a note less \
than 10 (10 is the highest note). You have access to the variables errors \
warning, statement which respectively contain the number of errors / warnings\
@@ -231,8 +234,8 @@ warning, statement which respectively contain the number of errors / warnings\
('comment',
{'default': 0, 'type' : 'yn', 'metavar' : '<y_or_n>',
'group': 'Reports', 'level': 1,
- 'help' : 'Add a comment according to your evaluation note. \
-This is used by the global evaluation report (RP0004).'}),
+ 'help' : 'Add a comment according to your evaluation note. '
+ 'This is used by the global evaluation report (RP0004).'}),
('enable',
{'type' : 'csv', 'metavar': '<msg ids>',
@@ -276,7 +279,8 @@ This is used by the global evaluation report (RP0004).'}),
('Reports', 'Options related to output formating and reporting'),
)
- def __init__(self, options=(), reporter=None, option_groups=(), pylintrc=None):
+ def __init__(self, options=(), reporter=None, option_groups=(),
+ pylintrc=None):
# some stuff has to be done before ancestors initialization...
#
# checkers / reporter / astroid manager
@@ -373,7 +377,8 @@ This is used by the global evaluation report (RP0004).'}),
"""overridden from configuration.OptionsProviderMixin to handle some
special options
"""
- if optname in self._options_methods or optname in self._bw_options_methods:
+ if optname in self._options_methods or \
+ optname in self._bw_options_methods:
if value:
try:
meth = self._options_methods[optname]
@@ -383,9 +388,9 @@ This is used by the global evaluation report (RP0004).'}),
optname, optname.split('-')[0]), DeprecationWarning)
value = check_csv(None, optname, value)
if isinstance(value, (list, tuple)):
- for _id in value :
+ for _id in value:
meth(_id)
- else :
+ else:
meth(value)
elif optname == 'output-format':
self._reporter_name = value
@@ -456,7 +461,8 @@ This is used by the global evaluation report (RP0004).'}),
match = OPTION_RGX.search(line)
if match is None:
continue
- if match.group(1).strip() == "disable-all" or match.group(1).strip() == 'skip-file':
+ if match.group(1).strip() == "disable-all" or \
+ match.group(1).strip() == 'skip-file':
if match.group(1).strip() == "disable-all":
self.add_message('I0014', line=start[0])
self.add_message('I0013', line=start[0])
@@ -566,7 +572,7 @@ This is used by the global evaluation report (RP0004).'}),
checker.active_msgs = messages
return neededcheckers
- def should_analyze_file(self, modname, path):
+ def should_analyze_file(self, modname, path): # pylint: disable=unused-argument
"""Returns whether or not a module should be checked.
This implementation returns True for all inputs, indicating that all
@@ -710,8 +716,8 @@ This is used by the global evaluation report (RP0004).'}),
def open(self):
"""initialize counters"""
- self.stats = { 'by_module' : {},
- 'by_msg' : {},
+ self.stats = {'by_module' : {},
+ 'by_msg' : {},
}
for msg_cat in MSG_TYPES.itervalues():
self.stats[msg_cat] = 0
@@ -944,7 +950,7 @@ them in the generated configuration.'''}),
('generate-man',
{'action' : 'callback', 'callback' : self.cb_generate_manpage,
'group': 'Commands',
- 'help' : "Generate pylint's man page.",'hide': True}),
+ 'help' : "Generate pylint's man page.", 'hide': True}),
('errors-only',
{'action' : 'callback', 'callback' : self.cb_error_mode,
@@ -1024,7 +1030,8 @@ are done by default'''}),
if self.linter.config.profile:
print >> sys.stderr, '** profiled run'
import cProfile, pstats
- cProfile.runctx('linter.check(%r)' % args, globals(), locals(), 'stones.prof' )
+ cProfile.runctx('linter.check(%r)' % args, globals(), locals(),
+ 'stones.prof')
data = pstats.Stats('stones.prof')
data.strip_dirs()
data.sort_stats('time', 'calls')
diff --git a/pyreverse/diadefslib.py b/pyreverse/diadefslib.py
index da21e1f..795be8b 100644
--- a/pyreverse/diadefslib.py
+++ b/pyreverse/diadefslib.py
@@ -41,7 +41,7 @@ class DiaDefGenerator(object):
"""get title for objects"""
title = node.name
if self.module_names:
- title = '%s.%s' % (node.root().name, title)
+ title = '%s.%s' % (node.root().name, title)
return title
def _set_option(self, option):
diff --git a/pyreverse/diagrams.py b/pyreverse/diagrams.py
index 288ce0f..360fdb1 100644
--- a/pyreverse/diagrams.py
+++ b/pyreverse/diagrams.py
@@ -172,7 +172,7 @@ class ClassDiagram(Figure, FilterMixIn):
for value in values:
if value is astroid.YES:
continue
- if isinstance( value, astroid.Instance):
+ if isinstance(value, astroid.Instance):
value = value._proxied
try:
ass_obj = self.object_from_node(value)
@@ -218,7 +218,7 @@ class PackageDiagram(ClassDiagram):
"""add dependencies created by from-imports
"""
mod_name = node.root().name
- obj = self.module( mod_name )
+ obj = self.module(mod_name)
if from_module not in obj.node.depends:
obj.node.depends.append(from_module)
diff --git a/pyreverse/main.py b/pyreverse/main.py
index cdd6607..5b9e8df 100644
--- a/pyreverse/main.py
+++ b/pyreverse/main.py
@@ -1,4 +1,4 @@
-# # Copyright (c) 2000-2012 LOGILAB S.A. (Paris, FRANCE).
+# # Copyright (c) 2000-2013 LOGILAB S.A. (Paris, FRANCE).
# http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This program is free software; you can redistribute it and/or modify it under
@@ -48,11 +48,11 @@ dict(short='c', action="append", metavar="<class>", dest="classes", default=[],
this uses by default the options -ASmy")),
("show-ancestors",
-dict(short="a", action="store", metavar='<ancestor>', type='int',
+dict(short="a", action="store", metavar='<ancestor>', type='int',
help='show <ancestor> generations of ancestor classes not in <projects>')),
("all-ancestors",
dict(short="A", default=None,
- help="show all ancestors off all classes in <projects>") ),
+ help="show all ancestors off all classes in <projects>")),
("show-associated",
dict(short='s', action="store", metavar='<ass_level>', type='int',
help='show <ass_level> levels of associated classes not in <projects>')),
diff --git a/pyreverse/utils.py b/pyreverse/utils.py
index 976f704..ea90e05 100644
--- a/pyreverse/utils.py
+++ b/pyreverse/utils.py
@@ -106,8 +106,8 @@ MODES = {
'SPECIAL' : _SPECIAL,
'OTHER' : _PROTECTED + _PRIVATE,
}
-VIS_MOD = {'special': _SPECIAL, 'protected': _PROTECTED, \
- 'private': _PRIVATE, 'public': 0 }
+VIS_MOD = {'special': _SPECIAL, 'protected': _PROTECTED,
+ 'private': _PRIVATE, 'public': 0}
class FilterMixIn(object):
"""filter nodes according to a mode and nodes' visibility
@@ -127,5 +127,5 @@ class FilterMixIn(object):
"""return true if the node should be treated
"""
visibility = get_visibility(getattr(node, 'name', node))
- return not (self.__mode & VIS_MOD[visibility] )
+ return not (self.__mode & VIS_MOD[visibility])
diff --git a/pyreverse/writer.py b/pyreverse/writer.py
index 446d6d6..d4b9937 100644
--- a/pyreverse/writer.py
+++ b/pyreverse/writer.py
@@ -57,20 +57,20 @@ class DiagramWriter(object):
"""write a class diagram"""
# sorted to get predictable (hence testable) results
for i, obj in enumerate(sorted(diagram.objects, key=lambda x: x.title)):
- self.printer.emit_node(i, **self.get_values(obj) )
+ self.printer.emit_node(i, **self.get_values(obj))
obj.fig_id = i
# inheritance links
for rel in diagram.get_relationships('specialization'):
self.printer.emit_edge(rel.from_object.fig_id, rel.to_object.fig_id,
- **self.inh_edges)
+ **self.inh_edges)
# implementation links
for rel in diagram.get_relationships('implements'):
self.printer.emit_edge(rel.from_object.fig_id, rel.to_object.fig_id,
- **self.imp_edges)
+ **self.imp_edges)
# generate associations
for rel in diagram.get_relationships('association'):
self.printer.emit_edge(rel.from_object.fig_id, rel.to_object.fig_id,
- label=rel.name, **self.ass_edges)
+ label=rel.name, **self.ass_edges)
def set_printer(self, file_name, basename):
"""set printer"""
@@ -95,10 +95,11 @@ class DotWriter(DiagramWriter):
def __init__(self, config):
styles = [dict(arrowtail='none', arrowhead="open"),
- dict(arrowtail = "none", arrowhead='empty'),
- dict(arrowtail="node", arrowhead='empty', style='dashed'),
+ dict(arrowtail='none', arrowhead='empty'),
+ dict(arrowtail='node', arrowhead='empty', style='dashed'),
dict(fontcolor='green', arrowtail='none',
- arrowhead='diamond', style='solid') ]
+ arrowhead='diamond', style='solid'),
+ ]
DiagramWriter.__init__(self, config, styles)
def set_printer(self, file_name, basename):
@@ -119,15 +120,15 @@ class DotWriter(DiagramWriter):
"""
label = obj.title
if obj.shape == 'interface':
- label = u"«interface»\\n%s" % label
+ label = u'«interface»\\n%s' % label
if not self.config.only_classnames:
- label = r"%s|%s\l|" % (label, r"\l".join(obj.attrs) )
+ label = r'%s|%s\l|' % (label, r'\l'.join(obj.attrs))
for func in obj.methods:
label = r'%s%s()\l' % (label, func.name)
label = '{%s}' % label
if is_exception(obj.node):
- return dict(fontcolor="red", label=label, shape="record")
- return dict(label=label, shape="record")
+ return dict(fontcolor='red', label=label, shape='record')
+ return dict(label=label, shape='record')
def close_graph(self):
"""print the dot graph into <file_name>"""
@@ -145,7 +146,8 @@ class VCGWriter(DiagramWriter):
dict(arrowstyle='solid', backarrowstyle='none',
linestyle='dotted', backarrowsize=10),
dict(arrowstyle='solid', backarrowstyle='none',
- textcolor='green') ]
+ textcolor='green'),
+ ]
DiagramWriter.__init__(self, config, styles)
def set_printer(self, file_name, basename):
@@ -180,7 +182,7 @@ class VCGWriter(DiagramWriter):
methods = [func.name for func in obj.methods]
# box width for UML like diagram
maxlen = max(len(name) for name in [obj.title] + methods + attrs)
- line = "_" * (maxlen + 2)
+ line = '_' * (maxlen + 2)
label = r'%s\n\f%s' % (label, line)
for attr in attrs:
label = r'%s\n\f08%s' % (label, attr)
diff --git a/setup.py b/setup.py
index c5286f5..e4b0ae8 100644
--- a/setup.py
+++ b/setup.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=W0404,W0622,W0704,W0613
-# copyright 2003-2012 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
+# copyright 2003-2013 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This file is part of pylint.
@@ -39,9 +39,11 @@ except ImportError:
USE_SETUPTOOLS = 0
try:
+ # pylint: disable=no-name-in-module
# python3
from distutils.command.build_py import build_py_2to3 as build_py
except ImportError:
+ # pylint: disable=no-name-in-module
# python2.x
from distutils.command.build_py import build_py
@@ -133,6 +135,7 @@ class MyInstallLib(install_lib.install_lib):
if sys.version_info >= (3, 0):
# process manually python file in include_dirs (test data)
+ # pylint: disable=no-name-in-module
from distutils.util import run_2to3
print('running 2to3 on', dest)
run_2to3([dest])
@@ -167,21 +170,20 @@ def install(**kwargs):
'symilar = pylint:run_symilar',
]}
kwargs['packages'] = packages
- return setup(name = distname,
- version = version,
- license = license,
- description = description,
- long_description = long_description,
- author = author,
- author_email = author_email,
- url = web,
- scripts = ensure_scripts(scripts),
- data_files = data_files,
- ext_modules = ext_modules,
- cmdclass = {'install_lib': MyInstallLib,
- 'build_py': build_py},
- **kwargs
- )
+ return setup(name=distname,
+ version=version,
+ license=license,
+ description=description,
+ long_description=long_description,
+ author=author,
+ author_email=author_email,
+ url=web,
+ scripts=ensure_scripts(scripts),
+ data_files=data_files,
+ ext_modules=ext_modules,
+ cmdclass={'install_lib': MyInstallLib,
+ 'build_py': build_py},
+ **kwargs)
if __name__ == '__main__' :
install()
diff --git a/testutils.py b/testutils.py
index 2c80f2a..77eaffe 100644
--- a/testutils.py
+++ b/testutils.py
@@ -150,7 +150,7 @@ class CheckerTestCase(testlib.TestCase):
def setUp(self):
self.linter = UnittestLinter()
- self.checker = self.CHECKER_CLASS(self.linter)
+ self.checker = self.CHECKER_CLASS(self.linter) # pylint: disable=not-callable
for key, value in self.CONFIG.iteritems():
setattr(self.checker.config, key, value)
self.checker.open()
@@ -213,10 +213,10 @@ class LintTestUsingModule(testlib.TestCase):
_TEST_TYPE = 'module'
def shortDescription(self):
- values = { 'mode' : self._TEST_TYPE,
- 'input': self.module,
- 'pkg': self.package,
- 'cls': self.__class__.__name__}
+ values = {'mode' : self._TEST_TYPE,
+ 'input': self.module,
+ 'pkg': self.package,
+ 'cls': self.__class__.__name__}
if self.package == self.DEFAULT_PACKAGE:
msg = '%(mode)s test of input file "%(input)s" (%(cls)s)'
diff --git a/utils.py b/utils.py
index 05e8b41..59e22a5 100644
--- a/utils.py
+++ b/utils.py
@@ -195,7 +195,7 @@ class MessagesHandlerMixIn(object):
# version). It contains the 1:1 mapping from symbolic names
# to message definition objects.
self._messages = {}
- # Maps alternative names (numeric IDs, deprecated names) to
+ # Maps alternative names (numeric IDs, deprecated names) to
# message definitions. May contain several names for each definition
# object.
self._alternative_names = {}
@@ -499,7 +499,7 @@ class MessagesHandlerMixIn(object):
print title
print '~' * len(title)
for msgid, msg in sorted(msgs.iteritems(),
- key=lambda (k,v): (_MSG_ORDER.index(k[0]), k)):
+ key=lambda (k, v): (_MSG_ORDER.index(k[0]), k)):
msg = build_message_def(checker, msgid, msg)
print msg.format_help(checkerref=False)
print
@@ -542,7 +542,7 @@ class ReportsHandlerMixIn(object):
checker is the checker defining the report
"""
reportid = reportid.upper()
- self._reports.setdefault(checker, []).append( (reportid, r_title, r_cb) )
+ self._reports.setdefault(checker, []).append((reportid, r_title, r_cb))
def enable_report(self, reportid):
"""disable the report of the given id"""
@@ -612,24 +612,24 @@ def expand_modules(files_or_modules, black_list):
try:
filepath = file_from_modpath(modname.split('.'))
if filepath is None:
- errors.append( {'key' : 'F0003', 'mod': modname} )
+ errors.append({'key' : 'F0003', 'mod': modname})
continue
except (ImportError, SyntaxError), ex:
# FIXME p3k : the SyntaxError is a Python bug and should be
# removed as soon as possible http://bugs.python.org/issue10588
- errors.append( {'key': 'F0001', 'mod': modname, 'ex': ex} )
+ errors.append({'key': 'F0001', 'mod': modname, 'ex': ex})
continue
filepath = normpath(filepath)
- result.append( {'path': filepath, 'name': modname,
- 'basepath': filepath, 'basename': modname} )
+ result.append({'path': filepath, 'name': modname,
+ 'basepath': filepath, 'basename': modname})
if not (modname.endswith('.__init__') or modname == '__init__') \
and '__init__.py' in filepath:
for subfilepath in get_module_files(dirname(filepath), black_list):
if filepath == subfilepath:
continue
submodname = '.'.join(modpath_from_file(subfilepath))
- result.append( {'path': subfilepath, 'name': submodname,
- 'basepath': filepath, 'basename': modname} )
+ result.append({'path': subfilepath, 'name': submodname,
+ 'basepath': filepath, 'basename': modname})
return result, errors