automatic: pyupgrade --py36-plus

This commit is contained in:
Anthony Sottile 2021-03-29 17:43:42 -07:00
parent 8cc3fc01e8
commit 358ae85120
51 changed files with 185 additions and 149 deletions

View file

@ -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

View file

@ -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)
]

View file

@ -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.

View file

@ -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."""

View file

@ -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()."""

View file

@ -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

View file

@ -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__):

View file

@ -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

View file

@ -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."""

View file

@ -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):

View file

@ -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

View file

@ -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

View file

@ -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__(

View file

@ -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

View file

@ -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,

View file

@ -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):

View file

@ -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

View file

@ -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,
)

View file

@ -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):