Skip to content

Update hooks and use autopep8 + add-trailing-comma instead of black #1990

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 13 additions & 10 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
repos:
- repo: https://github.com/asottile/add-trailing-comma
rev: v3.2.0
hooks:
- id: add-trailing-comma
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
rev: v5.0.0
hooks:
- id: check-yaml
- id: debug-statements
- id: end-of-file-fixer
- id: trailing-whitespace
exclude: ^tests/fixtures/
- repo: https://github.com/asottile/setup-cfg-fmt
rev: v2.5.0
rev: v2.8.0
hooks:
- id: setup-cfg-fmt
- repo: https://github.com/asottile/reorder-python-imports
rev: v3.14.0
rev: v3.15.0
hooks:
- id: reorder-python-imports
args: [
Expand All @@ -21,21 +25,20 @@ repos:
--add-import, 'from __future__ import annotations',
]
- repo: https://github.com/asottile/pyupgrade
rev: v3.19.1
rev: v3.20.0
hooks:
- id: pyupgrade
args: [--py39-plus]
- repo: https://github.com/psf/black
rev: 23.12.1
- repo: https://github.com/hhatto/autopep8
rev: v2.3.2
hooks:
- id: black
args: [--line-length=79]
- id: autopep8
- repo: https://github.com/PyCQA/flake8
rev: 7.0.0
rev: 7.3.0
hooks:
- id: flake8
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.15.0
rev: v1.17.0
hooks:
- id: mypy
exclude: ^(docs/|example-plugin/)
1 change: 0 additions & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ classifiers =
Environment :: Console
Framework :: Flake8
Intended Audience :: Developers
License :: OSI Approved :: MIT License
Programming Language :: Python
Programming Language :: Python :: 3
Programming Language :: Python :: 3 :: Only
Expand Down
2 changes: 1 addition & 1 deletion src/flake8/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,5 +66,5 @@ def configure_logging(
LOG.addHandler(handler)
LOG.setLevel(log_level)
LOG.debug(
"Added a %s logging handler to logger root at %s", filename, __name__
"Added a %s logging handler to logger root at %s", filename, __name__,
)
4 changes: 2 additions & 2 deletions src/flake8/api/legacy.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ def excluded(path: str) -> bool:
stdin_display_name=self.options.stdin_display_name,
filename_patterns=self.options.filename,
exclude=self.options.exclude,
)
),
)
return not paths

Expand All @@ -153,7 +153,7 @@ def init_report(
if not issubclass(reporter, formatter.BaseFormatter):
raise ValueError(
"Report should be subclass of "
"flake8.formatter.BaseFormatter."
"flake8.formatter.BaseFormatter.",
)
self._application.formatter = reporter(self.options)
self._application.guide = None
Expand Down
16 changes: 8 additions & 8 deletions src/flake8/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@

@contextlib.contextmanager
def _mp_prefork(
plugins: Checkers, options: argparse.Namespace
plugins: Checkers, options: argparse.Namespace,
) -> Generator[None]:
# we can save significant startup work w/ `fork` multiprocessing
global _mp
Expand All @@ -77,7 +77,7 @@ def _mp_run(filename: str) -> tuple[str, Results, dict[str, int]]:
assert _mp is not None, _mp
plugins, options = _mp
return FileChecker(
filename=filename, plugins=plugins, options=options
filename=filename, plugins=plugins, options=options,
).run_checks()


Expand Down Expand Up @@ -137,7 +137,7 @@ def _job_count(self) -> int:
if utils.is_using_stdin(self.options.filenames):
LOG.warning(
"The --jobs option is not compatible with supplying "
"input using - . Ignoring --jobs arguments."
"input using - . Ignoring --jobs arguments.",
)
return 0

Expand Down Expand Up @@ -252,7 +252,7 @@ def start(self) -> None:
stdin_display_name=self.options.stdin_display_name,
filename_patterns=self.options.filename,
exclude=self.exclude,
)
),
)
self.jobs = min(len(self.filenames), self.jobs)

Expand Down Expand Up @@ -332,11 +332,11 @@ def run_check(self, plugin: LoadedPlugin, **arguments: Any) -> Any:
assert self.processor is not None, self.filename
try:
params = self.processor.keyword_arguments_for(
plugin.parameters, arguments
plugin.parameters, arguments,
)
except AttributeError as ae:
raise exceptions.PluginRequestedUnknownParameters(
plugin_name=plugin.display_name, exception=ae
plugin_name=plugin.display_name, exception=ae,
)
try:
return plugin.obj(**arguments, **params)
Expand Down Expand Up @@ -548,7 +548,7 @@ def handle_newline(self, token_type: int) -> None:
self.run_logical_checks()

def check_physical_eol(
self, token: tokenize.TokenInfo, prev_physical: str
self, token: tokenize.TokenInfo, prev_physical: str,
) -> None:
"""Run physical checks if and only if it is at the end of the line."""
assert self.processor is not None
Expand Down Expand Up @@ -598,7 +598,7 @@ def _try_initialize_processpool(


def find_offset(
offset: int, mapping: processor._LogicalMapping
offset: int, mapping: processor._LogicalMapping,
) -> tuple[int, int]:
"""Find the offset tuple for a single offset."""
if isinstance(offset, tuple):
Expand Down
2 changes: 1 addition & 1 deletion src/flake8/formatting/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ def format(self, error: Violation) -> str | None:
The formatted error string.
"""
raise NotImplementedError(
"Subclass of BaseFormatter did not implement" " format."
"Subclass of BaseFormatter did not implement" " format.",
)

def show_statistics(self, statistics: Statistics) -> None:
Expand Down
2 changes: 1 addition & 1 deletion src/flake8/main/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def make_guide(self) -> None:
assert self.formatter is not None
assert self.options is not None
self.guide = style_guide.StyleGuideManager(
self.options, self.formatter
self.options, self.formatter,
)

def make_file_checker_manager(self, argv: Sequence[str]) -> None:
Expand Down
2 changes: 1 addition & 1 deletion src/flake8/main/debug.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def information(version: str, plugins: Plugins) -> dict[str, Any]:
(loaded.plugin.package, loaded.plugin.version)
for loaded in plugins.all_plugins()
if loaded.plugin.package not in {"flake8", "local"}
}
},
)
return {
"version": version,
Expand Down
2 changes: 1 addition & 1 deletion src/flake8/main/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def stage1_arg_parser() -> argparse.ArgumentParser:
)

parser.add_argument(
"--output-file", default=None, help="Redirect report to a file."
"--output-file", default=None, help="Redirect report to a file.",
)

# Config file options
Expand Down
6 changes: 3 additions & 3 deletions src/flake8/options/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def load_config(
if config is not None:
if not cfg.read(config, encoding="UTF-8"):
raise exceptions.ExecutionError(
f"The specified config file does not exist: {config}"
f"The specified config file does not exist: {config}",
)
cfg_dir = os.path.dirname(config)
else:
Expand All @@ -89,7 +89,7 @@ def load_config(
for filename in extra:
if not cfg.read(filename, encoding="UTF-8"):
raise exceptions.ExecutionError(
f"The specified config file does not exist: {filename}"
f"The specified config file does not exist: {filename}",
)

return cfg, cfg_dir
Expand Down Expand Up @@ -131,7 +131,7 @@ def parse_config(
raise ValueError(
f"Error code {error_code!r} "
f"supplied to {option_name!r} option "
f"does not match {VALID_CODE_PREFIX.pattern!r}"
f"does not match {VALID_CODE_PREFIX.pattern!r}",
)

assert option.config_name is not None
Expand Down
2 changes: 1 addition & 1 deletion src/flake8/options/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ def __init__(
if long_option_name is _ARG.NO:
raise ValueError(
"When specifying parse_from_config=True, "
"a long_option_name must also be specified."
"a long_option_name must also be specified.",
)
self.config_name = long_option_name[2:].replace("-", "_")

Expand Down
10 changes: 5 additions & 5 deletions src/flake8/plugins/finder.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,8 @@ def versions_str(self) -> str:
f"{loaded.plugin.package}: {loaded.plugin.version}"
for loaded in self.all_plugins()
if loaded.plugin.package not in {"flake8", "local"}
}
)
},
),
)


Expand Down Expand Up @@ -167,7 +167,7 @@ def _flake8_plugins(
# ideally pycodestyle's plugin entrypoints would exactly represent
# the codes they produce...
yield Plugin(
pycodestyle_meta["name"], pycodestyle_meta["version"], ep
pycodestyle_meta["name"], pycodestyle_meta["version"], ep,
)
else:
yield Plugin(name, version, ep)
Expand Down Expand Up @@ -240,7 +240,7 @@ def _check_required_plugins(
f"required plugins were not installed!\n"
f"- installed: {', '.join(sorted(plugin_names))}\n"
f"- expected: {', '.join(sorted(expected_names))}\n"
f"- missing: {', '.join(sorted(missing_plugins))}"
f"- missing: {', '.join(sorted(missing_plugins))}",
)


Expand Down Expand Up @@ -338,7 +338,7 @@ def _classify_plugins(
if not VALID_CODE_PREFIX.match(loaded.entry_name):
raise ExecutionError(
f"plugin code for `{loaded.display_name}` does not match "
f"{VALID_CODE_PREFIX.pattern}"
f"{VALID_CODE_PREFIX.pattern}",
)

return Plugins(
Expand Down
2 changes: 1 addition & 1 deletion src/flake8/plugins/pyflakes.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ class FlakesChecker(pyflakes.checker.Checker):
def __init__(self, tree: ast.AST, filename: str) -> None:
"""Initialize the PyFlakes plugin with an AST tree and filename."""
super().__init__(
tree, filename=filename, withDoctest=self.with_doctest
tree, filename=filename, withDoctest=self.with_doctest,
)

@classmethod
Expand Down
10 changes: 5 additions & 5 deletions src/flake8/processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
NEWLINE = frozenset([tokenize.NL, tokenize.NEWLINE])

SKIP_TOKENS = frozenset(
[tokenize.NL, tokenize.NEWLINE, tokenize.INDENT, tokenize.DEDENT]
[tokenize.NL, tokenize.NEWLINE, tokenize.INDENT, tokenize.DEDENT],
)

_LogicalMapping = list[tuple[int, tuple[int, int]]]
Expand Down Expand Up @@ -173,7 +173,7 @@ def update_checker_state_for(self, plugin: LoadedPlugin) -> None:
"""Update the checker_state attribute for the plugin."""
if "checker_state" in plugin.parameters:
self.checker_state = self._checker_states.setdefault(
plugin.entry_name, {}
plugin.entry_name, {},
)

def next_logical_line(self) -> None:
Expand Down Expand Up @@ -280,7 +280,7 @@ def generate_tokens(self) -> Generator[tokenize.TokenInfo]:

def _noqa_line_range(self, min_line: int, max_line: int) -> dict[int, str]:
line_range = range(min_line, max_line + 1)
joined = "".join(self.lines[min_line - 1 : max_line])
joined = "".join(self.lines[min_line - 1: max_line])
return dict.fromkeys(line_range, joined)

@functools.cached_property
Expand Down Expand Up @@ -367,7 +367,7 @@ def should_ignore_file(self) -> bool:
elif any(defaults.NOQA_FILE.search(line) for line in self.lines):
LOG.warning(
"Detected `flake8: noqa` on line with code. To ignore an "
"error on a line use `noqa` instead."
"error on a line use `noqa` instead.",
)
return False
else:
Expand All @@ -388,7 +388,7 @@ def strip_utf_bom(self) -> None:

def is_eol_token(token: tokenize.TokenInfo) -> bool:
"""Check if the token is an end-of-line token."""
return token[0] in NEWLINE or token[4][token[3][1] :].lstrip() == "\\\n"
return token[0] in NEWLINE or token[4][token[3][1]:].lstrip() == "\\\n"


def is_multiline_string(token: tokenize.TokenInfo) -> bool:
Expand Down
4 changes: 2 additions & 2 deletions src/flake8/statistics.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def record(self, error: Violation) -> None:
self._store[key].increment()

def statistics_for(
self, prefix: str, filename: str | None = None
self, prefix: str, filename: str | None = None,
) -> Generator[Statistic]:
"""Generate statistics for the prefix and filename.

Expand Down Expand Up @@ -108,7 +108,7 @@ class Statistic:
"""

def __init__(
self, error_code: str, filename: str, message: str, count: int
self, error_code: str, filename: str, message: str, count: int,
) -> None:
"""Initialize our Statistic."""
self.error_code = error_code
Expand Down
10 changes: 5 additions & 5 deletions src/flake8/style_guide.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ def __init__(
self.decider = decider or DecisionEngine(options)
self.style_guides: list[StyleGuide] = []
self.default_style_guide = StyleGuide(
options, formatter, self.stats, decider=decider
options, formatter, self.stats, decider=decider,
)
self.style_guides = [
self.default_style_guide,
Expand All @@ -228,7 +228,7 @@ def __init__(
self.style_guide_for = functools.cache(self._style_guide_for)

def populate_style_guides_with(
self, options: argparse.Namespace
self, options: argparse.Namespace,
) -> Generator[StyleGuide]:
"""Generate style guides from the per-file-ignores option.

Expand All @@ -240,7 +240,7 @@ def populate_style_guides_with(
per_file = utils.parse_files_to_codes_mapping(options.per_file_ignores)
for filename, violations in per_file:
yield self.default_style_guide.copy(
filename=filename, extend_ignore_with=violations
filename=filename, extend_ignore_with=violations,
)

def _style_guide_for(self, filename: str) -> StyleGuide:
Expand Down Expand Up @@ -288,7 +288,7 @@ def handle_error(
"""
guide = self.style_guide_for(filename)
return guide.handle_error(
code, filename, line_number, column_number, text, physical_line
code, filename, line_number, column_number, text, physical_line,
)


Expand Down Expand Up @@ -330,7 +330,7 @@ def copy(
options.extend_ignore = options.extend_ignore or []
options.extend_ignore.extend(extend_ignore_with or [])
return StyleGuide(
options, self.formatter, self.stats, filename=filename
options, self.formatter, self.stats, filename=filename,
)

@contextlib.contextmanager
Expand Down
Loading