diff options
| author | Anthony Sottile <asottile@umich.edu> | 2021-03-29 17:43:42 -0700 |
|---|---|---|
| committer | Anthony Sottile <asottile@umich.edu> | 2021-03-30 17:37:13 -0700 |
| commit | 358ae85120b5336f6abf574688b1f7290b3c8cc4 (patch) | |
| tree | b19e95f7eac533e223fd20950c99f67f92f9df10 | |
| parent | 8cc3fc01e8d06b2eb6fa59332b598b2c638a4d40 (diff) | |
| download | flake8-358ae85120b5336f6abf574688b1f7290b3c8cc4.tar.gz | |
automatic: pyupgrade --py36-plus
51 files changed, 185 insertions, 149 deletions
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 4db0949..7ab32ea 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,3 +1,4 @@ +exclude: ^tests/fixtures/example-code/ repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v2.3.0 @@ -7,6 +8,11 @@ repos: - id: end-of-file-fixer - id: trailing-whitespace exclude: ^tests/fixtures/diffs/ +- repo: https://github.com/asottile/reorder_python_imports + rev: v2.4.0 + hooks: + - id: reorder-python-imports + args: [--application-directories, '.:src', --py36-plus] - repo: https://github.com/psf/black rev: 20.8b1 hooks: @@ -17,6 +23,7 @@ repos: rev: v2.11.0 hooks: - id: pyupgrade + args: [--py36-plus] - repo: https://github.com/pre-commit/mirrors-mypy rev: v0.720 hooks: diff --git a/docs/source/conf.py b/docs/source/conf.py index dd2003f..97860c9 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # flake8 documentation build configuration file, created by # sphinx-quickstart on Tue Jan 19 07:14:10 2016. @@ -11,9 +10,8 @@ # # All configuration values have a default; values that are commented out # serve to show the default. - -import sys import os +import sys # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the @@ -53,11 +51,12 @@ source_suffix = '.rst' master_doc = 'index' # General information about the project. -project = u'flake8' -copyright = u'2016, Ian Stapleton Cordasco' -author = u'Ian Stapleton Cordasco' +project = 'flake8' +copyright = '2016, Ian Stapleton Cordasco' +author = 'Ian Stapleton Cordasco' import flake8 + # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. @@ -234,8 +233,8 @@ latex_elements = { # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ - (master_doc, 'flake8.tex', u'flake8 Documentation', - u'Ian Stapleton Cordasco', 'manual'), + (master_doc, 'flake8.tex', 'flake8 Documentation', + 'Ian Stapleton Cordasco', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of @@ -264,7 +263,7 @@ latex_documents = [ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - ('manpage', 'flake8', u'Flake8 Command Line Documentation', + ('manpage', 'flake8', 'Flake8 Command Line Documentation', [author], 1) ] @@ -278,7 +277,7 @@ man_pages = [ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - ('index', 'Flake8', u'Flake8 Documentation', u'Tarek Ziade', + ('index', 'Flake8', 'Flake8 Documentation', 'Tarek Ziade', 'Flake8', 'Code checking using pycodestyle, pyflakes and mccabe', 'Miscellaneous'), ] diff --git a/example-plugin/setup.py b/example-plugin/setup.py index 80911a2..0facd57 100644 --- a/example-plugin/setup.py +++ b/example-plugin/setup.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import setuptools setuptools.setup( diff --git a/example-plugin/src/flake8_example_plugin/__init__.py b/example-plugin/src/flake8_example_plugin/__init__.py index 33d76f3..420ce73 100644 --- a/example-plugin/src/flake8_example_plugin/__init__.py +++ b/example-plugin/src/flake8_example_plugin/__init__.py @@ -1,7 +1,6 @@ """Module for an example Flake8 plugin.""" - -from .on_by_default import ExampleOne from .off_by_default import ExampleTwo +from .on_by_default import ExampleOne __all__ = ( 'ExampleOne', diff --git a/example-plugin/src/flake8_example_plugin/off_by_default.py b/example-plugin/src/flake8_example_plugin/off_by_default.py index d768328..50afa81 100644 --- a/example-plugin/src/flake8_example_plugin/off_by_default.py +++ b/example-plugin/src/flake8_example_plugin/off_by_default.py @@ -1,7 +1,7 @@ """Our first example plugin.""" -class ExampleTwo(object): +class ExampleTwo: """Second Example Plugin.""" name = 'off-by-default-example-plugin' version = '1.0.0' diff --git a/example-plugin/src/flake8_example_plugin/on_by_default.py b/example-plugin/src/flake8_example_plugin/on_by_default.py index a324297..c748822 100644 --- a/example-plugin/src/flake8_example_plugin/on_by_default.py +++ b/example-plugin/src/flake8_example_plugin/on_by_default.py @@ -1,7 +1,7 @@ """Our first example plugin.""" -class ExampleOne(object): +class ExampleOne: """First Example Plugin.""" name = 'on-by-default-example-plugin' version = '1.0.0' @@ -11,5 +11,4 @@ class ExampleOne(object): def run(self): """Do nothing.""" - for message in []: - yield message + yield from [] @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """Packaging logic for Flake8.""" import os import sys diff --git a/src/flake8/_compat.py b/src/flake8/_compat.py index 85af0a3..640f2bd 100644 --- a/src/flake8/_compat.py +++ b/src/flake8/_compat.py @@ -1,10 +1,6 @@ """Expose backports in a single place.""" import sys - -if sys.version_info >= (3,): # pragma: no cover (PY3+) - from functools import lru_cache -else: # pragma: no cover (<PY3) - from functools32 import lru_cache +from functools import lru_cache if sys.version_info >= (3, 8): # pragma: no cover (PY38+) import importlib.metadata as importlib_metadata diff --git a/src/flake8/api/legacy.py b/src/flake8/api/legacy.py index 7923698..f046b5c 100644 --- a/src/flake8/api/legacy.py +++ b/src/flake8/api/legacy.py @@ -60,7 +60,7 @@ def get_style_guide(**kwargs): return StyleGuide(application) -class StyleGuide(object): +class StyleGuide: """Public facing object that mimic's Flake8 2.0's StyleGuide. .. note:: @@ -170,7 +170,7 @@ class StyleGuide(object): return self.check_files([filename]) -class Report(object): +class Report: """Public facing object that mimic's Flake8 2.0's API. .. note:: @@ -210,6 +210,6 @@ class Report(object): list """ return [ - "{} {} {}".format(s.count, s.error_code, s.message) + f"{s.count} {s.error_code} {s.message}" for s in self._stats.statistics_for(violation) ] diff --git a/src/flake8/checker.py b/src/flake8/checker.py index 82ce090..a9abd21 100644 --- a/src/flake8/checker.py +++ b/src/flake8/checker.py @@ -6,18 +6,21 @@ import logging import signal import sys import tokenize -from typing import Dict, List, Optional, Tuple - -try: - import multiprocessing.pool -except ImportError: - multiprocessing = None # type: ignore +from typing import Dict +from typing import List +from typing import Optional +from typing import Tuple from flake8 import defaults from flake8 import exceptions from flake8 import processor from flake8 import utils +try: + import multiprocessing.pool +except ImportError: + multiprocessing = None # type: ignore + LOG = logging.getLogger(__name__) SERIAL_RETRY_ERRNOS = { @@ -48,7 +51,7 @@ def _multiprocessing_is_fork(): # type () -> bool return multiprocessing and not utils.is_windows() -class Manager(object): +class Manager: """Manage the parallelism and checker instances for each plugin and file. This class will be responsible for the following: @@ -337,7 +340,7 @@ class Manager(object): self._process_statistics() -class FileChecker(object): +class FileChecker: """Manage running checks for a file and aggregate the results.""" def __init__(self, filename, checks, options): @@ -375,13 +378,13 @@ class FileChecker(object): def __repr__(self): # type: () -> str """Provide helpful debugging representation.""" - return "FileChecker for {}".format(self.filename) + return f"FileChecker for {self.filename}" def _make_processor(self): # type: () -> Optional[processor.FileProcessor] try: return processor.FileProcessor(self.filename, self.options) - except IOError as e: + except OSError as e: # If we can not read the file due to an IOError (e.g., the file # does not exist or we do not have the permissions to open it) # then we need to format that exception for the user. diff --git a/src/flake8/exceptions.py b/src/flake8/exceptions.py index e1b0539..bcc29de 100644 --- a/src/flake8/exceptions.py +++ b/src/flake8/exceptions.py @@ -24,7 +24,7 @@ class FailedToLoadPlugin(Flake8Exception): """Initialize our FailedToLoadPlugin exception.""" self.plugin_name = plugin_name self.original_exception = exception - super(FailedToLoadPlugin, self).__init__(plugin_name, exception) + super().__init__(plugin_name, exception) def __str__(self): # type: () -> str """Format our exception message.""" @@ -46,7 +46,7 @@ class InvalidSyntax(Flake8Exception): self.error_code = "E902" self.line_number = 1 self.column_number = 0 - super(InvalidSyntax, self).__init__(exception) + super().__init__(exception) def __str__(self): # type: () -> str """Format our exception message.""" @@ -63,9 +63,7 @@ class PluginRequestedUnknownParameters(Flake8Exception): """Pop certain keyword arguments for initialization.""" self.plugin = plugin self.original_exception = exception - super(PluginRequestedUnknownParameters, self).__init__( - plugin, exception - ) + super().__init__(plugin, exception) def __str__(self): # type: () -> str """Format our exception message.""" @@ -85,7 +83,7 @@ class PluginExecutionFailed(Flake8Exception): """Utilize keyword arguments for message generation.""" self.plugin = plugin self.original_exception = exception - super(PluginExecutionFailed, self).__init__(plugin, exception) + super().__init__(plugin, exception) def __str__(self): # type: () -> str """Format our exception message.""" diff --git a/src/flake8/formatting/base.py b/src/flake8/formatting/base.py index ae78f49..89789b5 100644 --- a/src/flake8/formatting/base.py +++ b/src/flake8/formatting/base.py @@ -1,15 +1,16 @@ """The base class and interface for all formatting plugins.""" -from __future__ import print_function - import argparse -from typing import IO, List, Optional, Tuple +from typing import IO +from typing import List +from typing import Optional +from typing import Tuple if False: # `typing.TYPE_CHECKING` was introduced in 3.5.2 from flake8.statistics import Statistics from flake8.style_guide import Violation -class BaseFormatter(object): +class BaseFormatter: """Class defining the formatter interface. .. attribute:: options @@ -179,7 +180,7 @@ class BaseFormatter(object): ) # Physical lines have a newline at the end, no need to add an extra # one - return "{}{}^".format(error.physical_line, indent) + return f"{error.physical_line}{indent}^" def _write(self, output): # type: (str) -> None """Handle logic of whether to use an output file or print().""" diff --git a/src/flake8/formatting/default.py b/src/flake8/formatting/default.py index 55a5d01..0ff5a9b 100644 --- a/src/flake8/formatting/default.py +++ b/src/flake8/formatting/default.py @@ -1,5 +1,6 @@ """Default formatting class for Flake8.""" -from typing import Optional, Set +from typing import Optional +from typing import Set from flake8.formatting import base @@ -77,7 +78,7 @@ class FilenameOnly(SimpleFormatter): """Ensure we only print each error once.""" if error.filename not in self.filenames_already_printed: self.filenames_already_printed.add(error.filename) - return super(FilenameOnly, self).format(error) + return super().format(error) else: return None diff --git a/src/flake8/main/application.py b/src/flake8/main/application.py index a247062..f5e3f10 100644 --- a/src/flake8/main/application.py +++ b/src/flake8/main/application.py @@ -1,11 +1,13 @@ """Module containing the application logic for Flake8.""" -from __future__ import print_function - import argparse import logging import sys import time -from typing import Dict, List, Optional, Set, Tuple +from typing import Dict +from typing import List +from typing import Optional +from typing import Set +from typing import Tuple import flake8 from flake8 import checker @@ -14,19 +16,21 @@ from flake8 import exceptions from flake8 import style_guide from flake8 import utils from flake8.main import options -from flake8.options import aggregator, config +from flake8.options import aggregator +from flake8.options import config from flake8.options import manager from flake8.plugins import manager as plugin_manager if False: # `typing.TYPE_CHECKING` was introduced in 3.5.2 from typing import Type # `typing.Type` was introduced in 3.5.2 + from flake8.formatting.base import BaseFormatter LOG = logging.getLogger(__name__) -class Application(object): +class Application: """Abstract our application into a class.""" def __init__(self, program="flake8", version=flake8.__version__): diff --git a/src/flake8/main/cli.py b/src/flake8/main/cli.py index 1bc9155..9456ae2 100644 --- a/src/flake8/main/cli.py +++ b/src/flake8/main/cli.py @@ -1,6 +1,7 @@ """Command-line implementation of flake8.""" import sys -from typing import List, Optional +from typing import List +from typing import Optional from flake8.main import application diff --git a/src/flake8/main/debug.py b/src/flake8/main/debug.py index 83a5a11..923c894 100644 --- a/src/flake8/main/debug.py +++ b/src/flake8/main/debug.py @@ -1,10 +1,9 @@ """Module containing the logic for our debugging logic.""" -from __future__ import print_function - import argparse import json import platform -from typing import Dict, List +from typing import Dict +from typing import List class DebugAction(argparse.Action): @@ -17,7 +16,7 @@ class DebugAction(argparse.Action): used to delay response. """ self._option_manager = kwargs.pop("option_manager") - super(DebugAction, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def __call__(self, parser, namespace, values, option_string=None): """Perform the argparse action for printing debug information.""" diff --git a/src/flake8/main/options.py b/src/flake8/main/options.py index fdde9e1..acadbb1 100644 --- a/src/flake8/main/options.py +++ b/src/flake8/main/options.py @@ -78,7 +78,7 @@ class JobsArgument: self.n_jobs = int(arg) else: raise argparse.ArgumentTypeError( - "{!r} must be 'auto' or an integer.".format(arg), + f"{arg!r} must be 'auto' or an integer.", ) def __str__(self): diff --git a/src/flake8/options/aggregator.py b/src/flake8/options/aggregator.py index bdcd6a3..0ab7357 100644 --- a/src/flake8/options/aggregator.py +++ b/src/flake8/options/aggregator.py @@ -5,7 +5,8 @@ applies the user-specified command-line configuration on top of it. """ import argparse import logging -from typing import List, Tuple +from typing import List +from typing import Tuple from flake8.options import config from flake8.options.manager import OptionManager diff --git a/src/flake8/options/config.py b/src/flake8/options/config.py index 3dbaae7..dccc622 100644 --- a/src/flake8/options/config.py +++ b/src/flake8/options/config.py @@ -3,7 +3,9 @@ import collections import configparser import logging import os.path -from typing import List, Optional, Tuple +from typing import List +from typing import Optional +from typing import Tuple from flake8 import utils @@ -12,7 +14,7 @@ LOG = logging.getLogger(__name__) __all__ = ("ConfigFileFinder", "MergedConfigParser") -class ConfigFileFinder(object): +class ConfigFileFinder: """Encapsulate the logic for finding and reading config files.""" def __init__( @@ -154,7 +156,7 @@ class ConfigFileFinder(object): return config -class MergedConfigParser(object): +class MergedConfigParser: """Encapsulate merging different types of configuration files. This parses out the options registered that were specified in the diff --git a/src/flake8/options/manager.py b/src/flake8/options/manager.py index 09bf862..5e0fee2 100644 --- a/src/flake8/options/manager.py +++ b/src/flake8/options/manager.py @@ -5,14 +5,23 @@ import contextlib import enum import functools import logging -from typing import Any, Callable, cast, Dict, Generator, List, Mapping -from typing import Optional, Sequence, Set, Tuple, Union +from typing import Any +from typing import Callable +from typing import cast +from typing import Dict +from typing import Generator +from typing import List +from typing import Mapping +from typing import Optional +from typing import Sequence +from typing import Set +from typing import Tuple +from typing import Union from flake8 import utils if False: # TYPE_CHECKING - from typing import NoReturn - from typing import Type + from typing import NoReturn, Type LOG = logging.getLogger(__name__) @@ -41,7 +50,7 @@ class _CallbackAction(argparse.Action): self._callback = kwargs.pop("callback") self._callback_args = kwargs.pop("callback_args", ()) self._callback_kwargs = kwargs.pop("callback_kwargs", {}) - super(_CallbackAction, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def __call__( self, @@ -61,7 +70,7 @@ class _CallbackAction(argparse.Action): values, parser, *self._callback_args, - **self._callback_kwargs + **self._callback_kwargs, ) @@ -70,7 +79,7 @@ def _flake8_normalize(value, *args, **kwargs): comma_separated_list = kwargs.pop("comma_separated_list", False) normalize_paths = kwargs.pop("normalize_paths", False) if kwargs: - raise TypeError("Unexpected keyword args: {}".format(kwargs)) + raise TypeError(f"Unexpected keyword args: {kwargs}") ret = value # type: Union[str, List[str]] if comma_separated_list and isinstance(ret, utils.string_types): @@ -85,7 +94,7 @@ def _flake8_normalize(value, *args, **kwargs): return ret -class Option(object): +class Option: """Our wrapper around an argparse argument parsers to add features.""" def __init__( @@ -284,7 +293,7 @@ class Option(object): for arg in self.option_args: parts.append(arg) for k, v in self.filtered_option_kwargs.items(): - parts.append("{}={!r}".format(k, v)) + parts.append(f"{k}={v!r}") return "Option({})".format(", ".join(parts)) def normalize(self, value, *normalize_args): @@ -337,7 +346,7 @@ PluginVersion = collections.namedtuple( ) -class OptionManager(object): +class OptionManager: """Manage Options and OptionParser while adding post-processing.""" def __init__( diff --git a/src/flake8/plugins/manager.py b/src/flake8/plugins/manager.py index 4f482dd..ab4cbd8 100644 --- a/src/flake8/plugins/manager.py +++ b/src/flake8/plugins/manager.py @@ -1,6 +1,10 @@ """Plugin loading and management logic and classes.""" import logging -from typing import Any, Dict, List, Optional, Set +from typing import Any +from typing import Dict +from typing import List +from typing import Optional +from typing import Set from flake8 import exceptions from flake8 import utils @@ -13,7 +17,7 @@ __all__ = ("Checkers", "Plugin", "PluginManager", "ReportFormatters") NO_GROUP_FOUND = object() -class Plugin(object): +class Plugin: """Wrap an EntryPoint from setuptools and other logic.""" def __init__(self, name, entry_point, local=False): @@ -219,7 +223,7 @@ class Plugin(object): self.disable(optmanager) -class PluginManager(object): # pylint: disable=too-few-public-methods +class PluginManager: # pylint: disable=too-few-public-methods """Find and manage plugins consistently.""" def __init__(self, namespace, local_plugins=None): @@ -342,7 +346,7 @@ def version_for(plugin): return getattr(module, "__version__", None) -class PluginTypeManager(object): +class PluginTypeManager: """Parent class for most of the specific plugin types.""" namespace = None # type: str diff --git a/src/flake8/plugins/pyflakes.py b/src/flake8/plugins/pyflakes.py index e845483..5d51799 100644 --- a/src/flake8/plugins/pyflakes.py +++ b/src/flake8/plugins/pyflakes.py @@ -1,6 +1,4 @@ """Plugin built-in to Flake8 to treat pyflakes as a plugin.""" -# -*- coding: utf-8 -*- -from __future__ import absolute_import import os from typing import List @@ -10,7 +8,6 @@ import pyflakes.checker from flake8 import utils - FLAKE8_PYFLAKES_CODES = { "UnusedImport": "F401", "ImportShadowedByLoopVar": "F402", @@ -96,7 +93,7 @@ class FlakesChecker(pyflakes.checker.Checker): if overlaped_by: with_doctest = True - super(FlakesChecker, self).__init__( + super().__init__( tree, filename=filename, withDoctest=with_doctest, diff --git a/src/flake8/processor.py b/src/flake8/processor.py index 8ace9a3..30c49ac 100644 --- a/src/flake8/processor.py +++ b/src/flake8/processor.py @@ -5,7 +5,12 @@ import contextlib import logging import sys import tokenize -from typing import Any, Dict, Generator, List, Optional, Tuple +from typing import Any +from typing import Dict +from typing import Generator +from typing import List +from typing import Optional +from typing import Tuple import flake8 from flake8 import defaults @@ -25,7 +30,7 @@ _LogicalMapping = List[Tuple[int, Tuple[int, int]]] _Logical = Tuple[List[str], List[str], _LogicalMapping] -class FileProcessor(object): +class FileProcessor: """Processes a file and holdes state. This processes a file by generating tokens, logical and physical lines, @@ -349,7 +354,7 @@ class FileProcessor(object): def _readlines_py2(self): # type: () -> List[str] - with open(self.filename, "rU") as fd: + with open(self.filename) as fd: return fd.readlines() def _readlines_py3(self): diff --git a/src/flake8/statistics.py b/src/flake8/statistics.py index 100227f..c238b8d 100644 --- a/src/flake8/statistics.py +++ b/src/flake8/statistics.py @@ -1,12 +1,15 @@ """Statistic collection logic for Flake8.""" import collections -from typing import Dict, Generator, List, Optional +from typing import Dict +from typing import Generator +from typing import List +from typing import Optional if False: # `typing.TYPE_CHECKING` was introduced in 3.5.2 from flake8.style_guide import Violation -class Statistics(object): +class Statistics: """Manager of aggregated statistics for a run of Flake8.""" def __init__(self): # type: () -> None @@ -102,7 +105,7 @@ class Key(collections.namedtuple("Key", ["filename", "code"])): ) -class Statistic(object): +class Statistic: """Simple wrapper around the logic of each statistic. Instead of maintaining a simple but potentially hard to reason about diff --git a/src/flake8/style_guide.py b/src/flake8/style_guide.py index 9be0fe8..df2a036 100644 --- a/src/flake8/style_guide.py +++ b/src/flake8/style_guide.py @@ -7,8 +7,15 @@ import enum import itertools import linecache import logging -from typing import Dict, Generator, List, Match, Optional, Sequence, Set -from typing import Tuple, Union +from typing import Dict +from typing import Generator +from typing import List +from typing import Match +from typing import Optional +from typing import Sequence +from typing import Set +from typing import Tuple +from typing import Union from flake8 import defaults from flake8 import statistics @@ -142,7 +149,7 @@ class Violation(_Violation): return self.line_number in line_numbers -class DecisionEngine(object): +class DecisionEngine: """A class for managing the decision process around violations. This contains the logic for whether a violation should be reported or @@ -318,7 +325,7 @@ class DecisionEngine(object): return decision -class StyleGuideManager(object): +class StyleGuideManager: """Manage multiple style guides for a single run.""" def __init__( @@ -437,7 +444,7 @@ class StyleGuideManager(object): guide.add_diff_ranges(diffinfo) -class StyleGuide(object): +class StyleGuide: """Manage a Flake8 user's style guide.""" def __init__( @@ -463,7 +470,7 @@ class StyleGuide(object): def __repr__(self): # type: () -> str """Make it easier to debug which StyleGuide we're using.""" - return "<StyleGuide [{}]>".format(self.filename) + return f"<StyleGuide [{self.filename}]>" def copy(self, filename=None, extend_ignore_with=None): # type: (Optional[str], Optional[Sequence[str]]) -> StyleGuide @@ -499,7 +506,7 @@ class StyleGuide(object): return utils.matches_filename( filename, patterns=[self.filename], - log_message='{!r} does %(whether)smatch "%(path)s"'.format(self), + log_message=f'{self!r} does %(whether)smatch "%(path)s"', logger=LOG, ) diff --git a/src/flake8/utils.py b/src/flake8/utils.py index 893571e..cd1b036 100644 --- a/src/flake8/utils.py +++ b/src/flake8/utils.py @@ -9,8 +9,16 @@ import platform import re import sys import tokenize -from typing import Callable, Dict, Generator, List, Optional, Pattern -from typing import Sequence, Set, Tuple, Union +from typing import Callable +from typing import Dict +from typing import Generator +from typing import List +from typing import Optional +from typing import Pattern +from typing import Sequence +from typing import Set +from typing import Tuple +from typing import Union from flake8 import exceptions from flake8._compat import lru_cache @@ -21,7 +29,7 @@ if False: # `typing.TYPE_CHECKING` was introduced in 3.5.2 DIFF_HUNK_REGEXP = re.compile(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@.*$") COMMA_SEPARATED_LIST_RE = re.compile(r"[,\s]") LOCAL_PLUGIN_LIST_RE = re.compile(r"[,\t\n\r\f\v]") -string_types = (str, type(u"")) +string_types = (str, type("")) def parse_comma_separated_list(value, regexp=COMMA_SEPARATED_LIST_RE): @@ -204,18 +212,12 @@ def _stdin_get_value_py3(): # type: () -> str @lru_cache(maxsize=1) def stdin_get_value(): # type: () -> str """Get and cache it so plugins can use it.""" - if sys.version_info < (3,): - return sys.stdin.read() - else: - return _stdin_get_value_py3() + return _stdin_get_value_py3() def stdin_get_lines(): # type: () -> List[str] """Return lines of stdin split according to file splitting.""" - if sys.version_info < (3,): - return list(io.BytesIO(stdin_get_value())) - else: - return list(io.StringIO(stdin_get_value())) + return list(io.StringIO(stdin_get_value())) def parse_unified_diff(diff=None): diff --git a/tests/fixtures/example-code/inline-ignores/E501.py b/tests/fixtures/example-code/inline-ignores/E501.py index 62e5c0c..64a5dca 100644 --- a/tests/fixtures/example-code/inline-ignores/E501.py +++ b/tests/fixtures/example-code/inline-ignores/E501.py @@ -1,3 +1,4 @@ -from some.module.that.has.nested.sub.modules import ClassWithVeryVeryVeryVeryLongName # noqa: E501,F401 +from some.module.that.has.nested.sub.modules import \ + ClassWithVeryVeryVeryVeryLongName # noqa: E501,F401 # ClassWithVeryVeryVeryVeryLongName() diff --git a/tests/integration/subdir/aplugin.py b/tests/integration/subdir/aplugin.py index bc5f812..266e8d0 100644 --- a/tests/integration/subdir/aplugin.py +++ b/tests/integration/subdir/aplugin.py @@ -1,7 +1,7 @@ """Module that is off sys.path by default, for testing local-plugin-paths.""" -class ExtensionTestPlugin2(object): +class ExtensionTestPlugin2: """Extension test plugin in its own directory.""" name = 'ExtensionTestPlugin2' diff --git a/tests/integration/test_checker.py b/tests/integration/test_checker.py index 836b543..1254bf0 100644 --- a/tests/integration/test_checker.py +++ b/tests/integration/test_checker.py @@ -1,5 +1,6 @@ """Integration tests for the checker submodule.""" -import mock +from unittest import mock + import pytest from flake8 import checker @@ -20,7 +21,7 @@ EXPECTED_RESULT_PHYSICAL_LINE = ( ) -class PluginClass(object): +class PluginClass: """Simple file plugin class yielding the expected report.""" name = 'test' diff --git a/tests/integration/test_main.py b/tests/integration/test_main.py index e2f58c5..10ccc54 100644 --- a/tests/integration/test_main.py +++ b/tests/integration/test_main.py @@ -1,8 +1,8 @@ """Integration tests for the main entrypoint of flake8.""" import json import os +from unittest import mock -import mock import pytest from flake8 import utils @@ -280,13 +280,13 @@ def test_obtaining_args_from_sys_argv_when_not_explicity_provided(capsys): def test_cli_config_option_respected(tmp_path): """Test --config is used.""" config = tmp_path / "flake8.ini" - config.write_text(u"""\ + config.write_text("""\ [flake8] ignore = F401 """) py_file = tmp_path / "t.py" - py_file.write_text(u"import os\n") + py_file.write_text("import os\n") _call_main(["--config", str(config), str(py_file)]) @@ -294,13 +294,13 @@ ignore = F401 def test_cli_isolated_overrides_config_option(tmp_path): """Test --isolated overrides --config.""" config = tmp_path / "flake8.ini" - config.write_text(u"""\ + config.write_text("""\ [flake8] ignore = F401 """) py_file = tmp_path / "t.py" - py_file.write_text(u"import os\n") + py_file.write_text("import os\n") _call_main(["--isolated", "--config", str(config), str(py_file)], retv=1) diff --git a/tests/integration/test_plugins.py b/tests/integration/test_plugins.py index 859fb69..1b6203e 100644 --- a/tests/integration/test_plugins.py +++ b/tests/integration/test_plugins.py @@ -1,12 +1,11 @@ """Integration tests for plugin loading.""" from flake8.main import application - LOCAL_PLUGIN_CONFIG = 'tests/fixtures/config_files/local-plugin.ini' LOCAL_PLUGIN_PATH_CONFIG = 'tests/fixtures/config_files/local-plugin-path.ini' -class ExtensionTestPlugin(object): +class ExtensionTestPlugin: """Extension test plugin.""" name = 'ExtensionTestPlugin' @@ -24,7 +23,7 @@ class ExtensionTestPlugin(object): parser.add_option('--anopt') -class ReportTestPlugin(object): +class ReportTestPlugin: """Report test plugin.""" name = 'ReportTestPlugin' diff --git a/tests/unit/test_application.py b/tests/unit/test_application.py index 51adefb..d675eaa 100644 --- a/tests/unit/test_application.py +++ b/tests/unit/test_application.py @@ -1,8 +1,8 @@ """Tests for the Application class.""" import argparse import sys +from unittest import mock -import mock import pytest from flake8.main import application as app diff --git a/tests/unit/test_base_formatter.py b/tests/unit/test_base_formatter.py index ff2df7c..c48adf2 100644 --- a/tests/unit/test_base_formatter.py +++ b/tests/unit/test_base_formatter.py @@ -1,7 +1,7 @@ """Tests for the BaseFormatter object.""" import argparse +from unittest import mock -import mock import pytest from flake8 import style_guide diff --git a/tests/unit/test_checker_manager.py b/tests/unit/test_checker_manager.py index d3e7e61..b94d0c5 100644 --- a/tests/unit/test_checker_manager.py +++ b/tests/unit/test_checker_manager.py @@ -1,7 +1,7 @@ """Tests for the Manager object for FileCheckers.""" import errno +from unittest import mock -import mock import pytest from flake8 import checker diff --git a/tests/unit/test_config_file_finder.py b/tests/unit/test_config_file_finder.py index d21b03d..d31a692 100644 --- a/tests/unit/test_config_file_finder.py +++ b/tests/unit/test_config_file_finder.py @@ -1,9 +1,8 @@ -# -*- coding: utf-8 -*- """Tests for the ConfigFileFinder.""" import configparser import os +from unittest import mock -import mock import pytest from flake8.options import config diff --git a/tests/unit/test_debug.py b/tests/unit/test_debug.py index 6398cf9..bc31fec 100644 --- a/tests/unit/test_debug.py +++ b/tests/unit/test_debug.py @@ -1,5 +1,6 @@ """Tests for our debugging module.""" -import mock +from unittest import mock + import pytest from flake8.main import debug diff --git a/tests/unit/test_file_checker.py b/tests/unit/test_file_checker.py index c4ee2bf..2b80919 100644 --- a/tests/unit/test_file_checker.py +++ b/tests/unit/test_file_checker.py @@ -1,5 +1,6 @@ """Unit tests for the FileChecker class.""" -import mock +from unittest import mock + import pytest import flake8 @@ -50,7 +51,7 @@ def test_nonexistent_file(): def test_raises_exception_on_failed_plugin(tmp_path, default_options): """Checks that a failing plugin results in PluginExecutionFailed.""" foobar = tmp_path / 'foobar.py' - foobar.write_text(u"I exist!") # Create temp file + foobar.write_text("I exist!") # Create temp file plugin = { "name": "failure", "plugin_name": "failure", # Both are necessary diff --git a/tests/unit/test_file_processor.py b/tests/unit/test_file_processor.py index b72e064..ca7f4f6 100644 --- a/tests/unit/test_file_processor.py +++ b/tests/unit/test_file_processor.py @@ -1,8 +1,8 @@ """Tests for the FileProcessor class.""" import ast import tokenize +from unittest import mock -import mock import pytest from flake8 import processor @@ -46,7 +46,7 @@ def test_read_lines_unknown_encoding(tmpdir, default_options): @pytest.mark.parametrize('first_line', [ '\xEF\xBB\xBF"""Module docstring."""\n', - u'\uFEFF"""Module docstring."""\n', + '\uFEFF"""Module docstring."""\n', ]) def test_strip_utf_bom(first_line, default_options): r"""Verify that we strip '\xEF\xBB\xBF' from the first line.""" @@ -58,7 +58,7 @@ def test_strip_utf_bom(first_line, default_options): @pytest.mark.parametrize('lines, expected', [ (['\xEF\xBB\xBF"""Module docstring."""\n'], False), - ([u'\uFEFF"""Module docstring."""\n'], False), + (['\uFEFF"""Module docstring."""\n'], False), (['#!/usr/bin/python', '# flake8 is great', 'a = 1'], False), (['#!/usr/bin/python', '# flake8: noqa', 'a = 1'], True), (['#!/usr/bin/python', '# flake8:noqa', 'a = 1'], True), @@ -130,7 +130,7 @@ def test_noqa_line_for(default_options): ]) for i in range(1, 4): - assert file_processor.noqa_line_for(i) == 'Line {}\n'.format(i) + assert file_processor.noqa_line_for(i) == f'Line {i}\n' def test_noqa_line_for_continuation(default_options): @@ -182,7 +182,7 @@ def test_next_line(default_options): ]) for i in range(1, 4): - assert file_processor.next_line() == 'Line {}'.format(i) + assert file_processor.next_line() == f'Line {i}' assert file_processor.line_number == i diff --git a/tests/unit/test_get_local_plugins.py b/tests/unit/test_get_local_plugins.py index ec11998..0817550 100644 --- a/tests/unit/test_get_local_plugins.py +++ b/tests/unit/test_get_local_plugins.py @@ -1,5 +1,5 @@ """Tests for get_local_plugins.""" -import mock +from unittest import mock from flake8.options import config diff --git a/tests/unit/test_legacy_api.py b/tests/unit/test_legacy_api.py index 0ec839f..a1e7d50 100644 --- a/tests/unit/test_legacy_api.py +++ b/tests/unit/test_legacy_api.py @@ -1,8 +1,8 @@ """Tests for Flake8's legacy API.""" import argparse import os.path +from unittest import mock -import mock import pytest from flake8.api import legacy as api diff --git a/tests/unit/test_merged_config_parser.py b/tests/unit/test_merged_config_parser.py index d446ad8..8def01b 100644 --- a/tests/unit/test_merged_config_parser.py +++ b/tests/unit/test_merged_config_parser.py @@ -1,7 +1,7 @@ """Unit tests for flake8.options.config.MergedConfigParser.""" import os +from unittest import mock -import mock import pytest from flake8.options import config diff --git a/tests/unit/test_option.py b/tests/unit/test_option.py index ba6b672..fc0e288 100644 --- a/tests/unit/test_option.py +++ b/tests/unit/test_option.py @@ -1,7 +1,7 @@ """Unit tests for flake8.options.manager.Option.""" import functools +from unittest import mock -import mock import pytest from flake8.options import manager diff --git a/tests/unit/test_option_manager.py b/tests/unit/test_option_manager.py index 09714b9..4dcbaa8 100644 --- a/tests/unit/test_option_manager.py +++ b/tests/unit/test_option_manager.py @@ -1,8 +1,8 @@ """Unit tests for flake.options.manager.OptionManager.""" import argparse import os +from unittest import mock -import mock import pytest from flake8 import utils diff --git a/tests/unit/test_plugin.py b/tests/unit/test_plugin.py index 402eac8..204a4c2 100644 --- a/tests/unit/test_plugin.py +++ b/tests/unit/test_plugin.py @@ -1,7 +1,7 @@ """Tests for flake8.plugins.manager.Plugin.""" import argparse +from unittest import mock -import mock import pytest from flake8 import exceptions diff --git a/tests/unit/test_plugin_manager.py b/tests/unit/test_plugin_manager.py index 9ad6aba..55c3e24 100644 --- a/tests/unit/test_plugin_manager.py +++ b/tests/unit/test_plugin_manager.py @@ -1,5 +1,5 @@ """Tests for flake8.plugins.manager.PluginManager.""" -import mock +from unittest import mock from flake8._compat import importlib_metadata from flake8.plugins import manager diff --git a/tests/unit/test_plugin_type_manager.py b/tests/unit/test_plugin_type_manager.py index 939aa8c..9d00b78 100644 --- a/tests/unit/test_plugin_type_manager.py +++ b/tests/unit/test_plugin_type_manager.py @@ -1,5 +1,6 @@ """Tests for flake8.plugins.manager.PluginTypeManager.""" -import mock +from unittest import mock + import pytest from flake8 import exceptions diff --git a/tests/unit/test_statistics.py b/tests/unit/test_statistics.py index 16896f0..6aa4e6f 100644 --- a/tests/unit/test_statistics.py +++ b/tests/unit/test_statistics.py @@ -111,8 +111,8 @@ def test_statistic_for_retrieves_more_than_one_value(): """Show this works for more than a couple statistic values.""" aggregator = stats.Statistics() for i in range(50): - aggregator.record(make_error(code='E1{:02d}'.format(i))) - aggregator.record(make_error(code='W2{:02d}'.format(i))) + aggregator.record(make_error(code=f'E1{i:02d}')) + aggregator.record(make_error(code=f'W2{i:02d}')) statistics = list(aggregator.statistics_for('E')) assert len(statistics) == 50 diff --git a/tests/unit/test_style_guide.py b/tests/unit/test_style_guide.py index 5503d7e..ac781f3 100644 --- a/tests/unit/test_style_guide.py +++ b/tests/unit/test_style_guide.py @@ -1,7 +1,7 @@ """Tests for the flake8.style_guide.StyleGuide class.""" import argparse +from unittest import mock -import mock import pytest from flake8 import statistics diff --git a/tests/unit/test_utils.py b/tests/unit/test_utils.py index 4b89484..1befa8f 100644 --- a/tests/unit/test_utils.py +++ b/tests/unit/test_utils.py @@ -3,8 +3,8 @@ import io import logging import os import sys +from unittest import mock -import mock import pytest from flake8 import exceptions @@ -242,7 +242,7 @@ def test_filenames_from_exclude_doesnt_exclude_directory_names(tmpdir): def test_parameters_for_class_plugin(): """Verify that we can retrieve the parameters for a class plugin.""" - class FakeCheck(object): + class FakeCheck: def __init__(self, tree): raise NotImplementedError @@ -268,7 +268,7 @@ def test_parameters_for_function_plugin(): def read_diff_file(filename): """Read the diff file in its entirety.""" - with open(filename, 'r') as fd: + with open(filename) as fd: content = fd.read() return content diff --git a/tests/unit/test_violation.py b/tests/unit/test_violation.py index a3a56f0..284cd2a 100644 --- a/tests/unit/test_violation.py +++ b/tests/unit/test_violation.py @@ -1,5 +1,6 @@ """Tests for the flake8.style_guide.Violation class.""" -import mock +from unittest import mock + import pytest from flake8 import style_guide @@ -31,7 +31,6 @@ deps = flake8 flake8-bugbear flake8-docstrings>=1.3.1 - flake8-import-order>=0.9 flake8-typing-imports>=1.1 pep8-naming commands = @@ -141,5 +140,3 @@ exclude = .cache, .eggs max-complexity = 10 -import-order-style = google -application-import-names = flake8 |
