Make pylint happier

This commit is contained in:
Ian Cordasco 2016-02-19 15:10:46 -06:00
parent 85c199ea34
commit 69b8be71dc
11 changed files with 64 additions and 47 deletions

View file

@ -10,8 +10,6 @@ This module
""" """
import logging import logging
import sys
try: try:
from logging import NullHandler from logging import NullHandler
except ImportError: except ImportError:
@ -21,6 +19,7 @@ except ImportError:
def emit(self, record): def emit(self, record):
"""Do nothing.""" """Do nothing."""
pass pass
import sys
LOG = logging.getLogger(__name__) LOG = logging.getLogger(__name__)
LOG.addHandler(NullHandler()) LOG.addHandler(NullHandler())
@ -51,7 +50,6 @@ def configure_logging(verbosity, filename=None,
If the name is "stdout" or "stderr" this will log to the appropriate If the name is "stdout" or "stderr" this will log to the appropriate
stream. stream.
""" """
global LOG
if verbosity <= 0: if verbosity <= 0:
return return
if verbosity > 2: if verbosity > 2:
@ -60,12 +58,14 @@ def configure_logging(verbosity, filename=None,
log_level = _VERBOSITY_TO_LOG_LEVEL[verbosity] log_level = _VERBOSITY_TO_LOG_LEVEL[verbosity]
if not filename or filename in ('stderr', 'stdout'): if not filename or filename in ('stderr', 'stdout'):
handler = logging.StreamHandler(getattr(sys, filename)) fileobj = getattr(sys, filename or 'stderr')
handler = logging.StreamHandler
else: else:
handler = logging.FileHandler(filename) fileobj = filename
handler = logging.FileHandler
handler.setFormatter(logging.Formatter(logformat)) handler.setFormatter(logging.Formatter(logformat))
LOG.addHandler(handler) LOG.addHandler(handler(fileobj))
LOG.setLevel(log_level) LOG.setLevel(log_level)
LOG.debug('Added a %s logging handler to logger root at %s', LOG.debug('Added a %s logging handler to logger root at %s',
filename, __name__) filename, __name__)

View file

@ -18,6 +18,8 @@ class SimpleFormatter(base.BaseFormatter):
""" """
error_format = None
def format(self, error): def format(self, error):
"""Format and write error out. """Format and write error out.

View file

@ -174,10 +174,11 @@ def main(argv=None):
# Parse out our options from our found config files and user-provided CLI # Parse out our options from our found config files and user-provided CLI
# options # options
options, args = aggregator.aggregate_options(option_manager) options, args = aggregator.aggregate_options(option_manager, argv)
# formatter = formatting_plugins.get( formatter = formatting_plugins.get(
# options.format, formatting_plugins['default'] options.format, formatting_plugins['default']
# ).execute(options) ).execute(options)
# listener_trie = listening_plugins.build_notifier() listener_trie = listening_plugins.build_notifier()
# guide = style_guide.StyleGuide(options, args, listener_trie, formatter) guide = style_guide.StyleGuide(options, args, listener_trie, formatter)
guide.handle_error('E111', 'stdin', 1, 1, 'faketext')

View file

@ -71,5 +71,4 @@ def aggregate_options(manager, arglist=None, values=None):
setattr(default_values, dest_name, value) setattr(default_values, dest_name, value)
# Finally parse the command-line options # Finally parse the command-line options
final_values, args = manager.parse_args(arglist, default_values) return manager.parse_args(arglist, default_values)
return final_values, args

View file

@ -66,7 +66,7 @@ class ConfigFileFinder(object):
LOG.debug('Found cli configuration files: %s', found_files) LOG.debug('Found cli configuration files: %s', found_files)
return config return config
def generate_possible_local_config_files(self): def generate_possible_local_files(self):
"""Find and generate all local config files.""" """Find and generate all local config files."""
tail = self.tail tail = self.tail
parent = self.parent parent = self.parent
@ -84,7 +84,7 @@ class ConfigFileFinder(object):
"""Find all local config files which actually exist. """Find all local config files which actually exist.
Filter results from Filter results from
:meth:`~ConfigFileFinder.generate_possible_local_config_files` based :meth:`~ConfigFileFinder.generate_possible_local_files` based
on whether the filename exists or not. on whether the filename exists or not.
:returns: :returns:
@ -93,11 +93,12 @@ class ConfigFileFinder(object):
:rtype: :rtype:
[str] [str]
""" """
exists = os.path.exists
return [ return [
filename filename
for filename in self.generate_possible_local_config_files() for filename in self.generate_possible_local_files()
if os.path.exists(filename) if os.path.exists(filename)
] + list(filter(os.path.exists, self.extra_config_files)) ] + [f for f in self.extra_config_files if exists(f)]
def local_configs(self): def local_configs(self):
"""Parse all local config files into one config object.""" """Parse all local config files into one config object."""

View file

@ -1,6 +1,6 @@
"""Option handling and Option management logic.""" """Option handling and Option management logic."""
import logging import logging
import optparse import optparse # pylint: disable=deprecated-module
from flake8 import utils from flake8 import utils
@ -18,8 +18,7 @@ class Option(object):
metavar=None, metavar=None,
# Options below here are specific to Flake8 # Options below here are specific to Flake8
parse_from_config=False, comma_separated_list=False, parse_from_config=False, comma_separated_list=False,
normalize_paths=False, normalize_paths=False):
):
"""Initialize an Option instance wrapping optparse.Option. """Initialize an Option instance wrapping optparse.Option.
The following are all passed directly through to optparse. The following are all passed directly through to optparse.
@ -69,12 +68,17 @@ class Option(object):
""" """
self.short_option_name = short_option_name self.short_option_name = short_option_name
self.long_option_name = long_option_name self.long_option_name = long_option_name
self.option_args = filter(None, (short_option_name, long_option_name)) self.option_args = [
x for x in (short_option_name, long_option_name) if x is not None
]
self.option_kwargs = { self.option_kwargs = {
'action': action, 'action': action,
'default': default, 'default': default,
'type': type, 'type': type,
'dest': self._make_dest(dest), 'dest': self._make_dest(dest),
'nargs': nargs,
'const': const,
'choices': choices,
'callback': callback, 'callback': callback,
'callback_args': callback_args, 'callback_args': callback_args,
'callback_kwargs': callback_kwargs, 'callback_kwargs': callback_kwargs,
@ -97,6 +101,8 @@ class Option(object):
'a long_option_name must also be specified.') 'a long_option_name must also be specified.')
self.config_name = long_option_name[2:].replace('-', '_') self.config_name = long_option_name[2:].replace('-', '_')
self._opt = None
def __repr__(self): def __repr__(self):
"""Simple representation of an Option class.""" """Simple representation of an Option class."""
return ( return (
@ -129,7 +135,7 @@ class Option(object):
def to_optparse(self): def to_optparse(self):
"""Convert a Flake8 Option to an optparse Option.""" """Convert a Flake8 Option to an optparse Option."""
if not hasattr(self, '_opt'): if self._opt is None:
self._opt = optparse.Option(*self.option_args, self._opt = optparse.Option(*self.option_args,
**self.option_kwargs) **self.option_kwargs)
return self._opt return self._opt

View file

@ -57,7 +57,7 @@ class Plugin(object):
def execute(self, *args, **kwargs): def execute(self, *args, **kwargs):
r"""Call the plugin with \*args and \*\*kwargs.""" r"""Call the plugin with \*args and \*\*kwargs."""
return self.plugin(*args, **kwargs) return self.plugin(*args, **kwargs) # pylint: disable=not-callable
def _load(self, verify_requirements): def _load(self, verify_requirements):
# Avoid relying on hasattr() here. # Avoid relying on hasattr() here.
@ -134,7 +134,7 @@ class Plugin(object):
) )
class PluginManager(object): class PluginManager(object): # pylint: disable=too-few-public-methods
"""Find and manage plugins consistently.""" """Find and manage plugins consistently."""
def __init__(self, namespace, verify_requirements=False): def __init__(self, namespace, verify_requirements=False):
@ -188,6 +188,8 @@ class PluginManager(object):
class PluginTypeManager(object): class PluginTypeManager(object):
"""Parent class for most of the specific plugin types.""" """Parent class for most of the specific plugin types."""
namespace = None
def __init__(self): def __init__(self):
"""Initialize the plugin type's manager.""" """Initialize the plugin type's manager."""
self.manager = PluginManager(self.namespace) self.manager = PluginManager(self.namespace)
@ -232,6 +234,7 @@ class PluginTypeManager(object):
@staticmethod @staticmethod
def _generate_call_function(method_name, optmanager, *args, **kwargs): def _generate_call_function(method_name, optmanager, *args, **kwargs):
def generated_function(plugin): def generated_function(plugin):
"""Function that attempts to call a specific method on a plugin."""
method = getattr(plugin, method_name, None) method = getattr(plugin, method_name, None)
if (method is not None and if (method is not None and
isinstance(method, collections.Callable)): isinstance(method, collections.Callable)):
@ -244,6 +247,7 @@ class PluginTypeManager(object):
return return
def load_plugin(plugin): def load_plugin(plugin):
"""Call each plugin's load_plugin method."""
return plugin.load_plugin() return plugin.load_plugin()
plugins = list(self.manager.map(load_plugin)) plugins = list(self.manager.map(load_plugin))
@ -269,7 +273,7 @@ class PluginTypeManager(object):
list(self.manager.map(call_provide_options)) list(self.manager.map(call_provide_options))
class NotifierBuilder(object): class NotifierBuilderMixin(object): # pylint: disable=too-few-public-methods
"""Mixin class that builds a Notifier from a PluginManager.""" """Mixin class that builds a Notifier from a PluginManager."""
def build_notifier(self): def build_notifier(self):
@ -293,7 +297,7 @@ class Checkers(PluginTypeManager):
namespace = 'flake8.extension' namespace = 'flake8.extension'
class Listeners(PluginTypeManager, NotifierBuilder): class Listeners(PluginTypeManager, NotifierBuilderMixin):
"""All of the listeners registered through entry-points.""" """All of the listeners registered through entry-points."""
namespace = 'flake8.listen' namespace = 'flake8.listen'

View file

@ -23,7 +23,7 @@ def patch_pyflakes():
'F402 ImportShadowedByLoopVar', 'F402 ImportShadowedByLoopVar',
'F403 ImportStarUsed', 'F403 ImportStarUsed',
'F404 LateFutureImport', 'F404 LateFutureImport',
'F810 Redefined', # XXX Obsolete? 'F810 Redefined',
'F811 RedefinedWhileUnused', 'F811 RedefinedWhileUnused',
'F812 RedefinedInListComp', 'F812 RedefinedInListComp',
'F821 UndefinedName', 'F821 UndefinedName',
@ -48,23 +48,23 @@ class FlakesChecker(pyflakes.checker.Checker):
def __init__(self, tree, filename): def __init__(self, tree, filename):
"""Initialize the PyFlakes plugin with an AST tree and filename.""" """Initialize the PyFlakes plugin with an AST tree and filename."""
filename = utils.normalize_paths(filename)[0] filename = utils.normalize_paths(filename)[0]
withDoctest = self.withDoctest with_doctest = self.with_doctest
included_by = [include for include in self.include_in_doctest included_by = [include for include in self.include_in_doctest
if include != '' and filename.startswith(include)] if include != '' and filename.startswith(include)]
if included_by: if included_by:
withDoctest = True with_doctest = True
for exclude in self.exclude_from_doctest: for exclude in self.exclude_from_doctest:
if exclude != '' and filename.startswith(exclude): if exclude != '' and filename.startswith(exclude):
withDoctest = False with_doctest = False
overlaped_by = [include for include in included_by overlaped_by = [include for include in included_by
if include.startswith(exclude)] if include.startswith(exclude)]
if overlaped_by: if overlaped_by:
withDoctest = True with_doctest = True
super(FlakesChecker, self).__init__(tree, filename, super(FlakesChecker, self).__init__(tree, filename,
withDoctest=withDoctest) withDoctest=with_doctest)
@classmethod @classmethod
def add_options(cls, parser): def add_options(cls, parser):
@ -98,7 +98,7 @@ class FlakesChecker(pyflakes.checker.Checker):
"""Parse option values from Flake8's OptionManager.""" """Parse option values from Flake8's OptionManager."""
if options.builtins: if options.builtins:
cls.builtIns = cls.builtIns.union(options.builtins) cls.builtIns = cls.builtIns.union(options.builtins)
cls.withDoctest = options.doctests cls.with_doctest = options.doctests
included_files = [] included_files = []
for included_file in options.include_in_doctest: for included_file in options.include_in_doctest:
@ -131,6 +131,9 @@ class FlakesChecker(pyflakes.checker.Checker):
def run(self): def run(self):
"""Run the plugin.""" """Run the plugin."""
for m in self.messages: for message in self.messages:
col = getattr(m, 'col', 0) col = getattr(message, 'col', 0)
yield m.lineno, col, (m.flake8_msg % m.message_args), m.__class__ yield (message.lineno,
col,
(message.flake8_msg % message.message_args),
message.__class__)

View file

@ -145,15 +145,15 @@ class StyleGuide(object):
code, selected, ignored) code, selected, ignored)
if ((selected is Selected.Explicitly or if ((selected is Selected.Explicitly or
selected is Selected.Implicitly) and selected is Selected.Implicitly) and
ignored is Selected.Implicitly): ignored is Selected.Implicitly):
decision = Decision.Selected decision = Decision.Selected
elif (selected is Selected.Explicitly and elif (selected is Selected.Explicitly and
ignored is Ignored.Explicitly): ignored is Ignored.Explicitly):
decision = self._decision_for(code) decision = self._decision_for(code)
elif (selected is Ignored.Implicitly or elif (selected is Ignored.Implicitly or
ignored is Ignored.Explicitly): ignored is Ignored.Explicitly):
decision = Decision.Ignored decision = Decision.Ignored # pylint: disable=R0204
self._decision_cache[code] = decision self._decision_cache[code] = decision
LOG.debug('"%s" will be "%s"', code, decision) LOG.debug('"%s" will be "%s"', code, decision)

View file

@ -33,7 +33,8 @@ def normalize_paths(paths, parent=os.curdir):
:rtype: :rtype:
[str] [str]
""" """
return [normalize_path(p) for p in parse_comma_separated_list(paths)] return [normalize_path(p, parent)
for p in parse_comma_separated_list(paths)]
def normalize_path(path, parent=os.curdir): def normalize_path(path, parent=os.curdir):
@ -57,8 +58,8 @@ def stdin_get_value():
if cached_value is None: if cached_value is None:
stdin_value = sys.stdin.read() stdin_value = sys.stdin.read()
if sys.version_info < (3, 0): if sys.version_info < (3, 0):
cached_value = io.BytesIO(stdin_value) cached_type = io.BytesIO
else: else:
cached_value = io.StringIO(stdin_value) cached_type = io.StringIO
stdin_get_value.cached_stdin = cached_value stdin_get_value.cached_stdin = cached_type(stdin_value)
return cached_value.getvalue() return cached_value.getvalue()

View file

@ -68,11 +68,11 @@ def test_cli_config():
os.path.abspath('tox.ini'), os.path.abspath('tox.ini'),
os.path.abspath('.flake8')]), os.path.abspath('.flake8')]),
]) ])
def test_generate_possible_local_config_files(args, expected): def test_generate_possible_local_files(args, expected):
"""Verify generation of all possible config paths.""" """Verify generation of all possible config paths."""
finder = config.ConfigFileFinder('flake8', args, []) finder = config.ConfigFileFinder('flake8', args, [])
assert (list(finder.generate_possible_local_config_files()) == assert (list(finder.generate_possible_local_files()) ==
expected) expected)