From 87905818fb8f7e00ddfb16b7110476f4476514cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dani=C3=ABl=20van=20Noord?= <13665637+DanielNoord@users.noreply.github.com> Date: Thu, 16 Jul 2026 23:55:58 +0200 Subject: [PATCH] Fix `mypy` issues uncovered by compiling with `mypyc` --- isort/exceptions.py | 6 ++++-- isort/files.py | 6 +++--- isort/io.py | 2 +- isort/main.py | 10 +++++----- isort/output.py | 15 ++++++++------- isort/settings.py | 6 +++--- isort/wrap.py | 4 ++-- pyproject.toml | 1 + tests/unit/test_regressions.py | 5 ++--- tests/unit/test_settings.py | 2 +- tox.ini | 2 +- 11 files changed, 31 insertions(+), 28 deletions(-) diff --git a/isort/exceptions.py b/isort/exceptions.py index f8729ed9a..5e60435d1 100644 --- a/isort/exceptions.py +++ b/isort/exceptions.py @@ -1,5 +1,7 @@ """All isort specific exception classes should be defined here""" +from __future__ import annotations + from functools import partial from pathlib import Path from typing import Any @@ -10,14 +12,14 @@ class ISortError(Exception): """Base isort exception object from which all isort sourced exceptions should inherit""" - def __reduce__(self): # type: ignore + def __reduce__(self) -> tuple[partial[ISortError], tuple[()]]: return (partial(type(self), **self.__dict__), ()) class InvalidSettingsPath(ISortError): """Raised when a settings path is provided that is neither a valid file or directory""" - def __init__(self, settings_path: str): + def __init__(self, settings_path: str | Path): super().__init__( f"isort was told to use the settings_path: {settings_path} as the base directory or " "file that represents the starting point of config file discovery, but it does not " diff --git a/isort/files.py b/isort/files.py index 11830681f..f3d59e178 100644 --- a/isort/files.py +++ b/isort/files.py @@ -6,8 +6,8 @@ def find( - paths: Iterable[str], config: Config, skipped: list[str], broken: list[str] -) -> Iterator[str]: + paths: Iterable[str | Path], config: Config, skipped: list[str], broken: list[str] +) -> Iterator[str | Path]: """Finds and provides an iterator for all Python source files defined in paths.""" visited_dirs: set[Path] = set() @@ -36,6 +36,6 @@ def find( else: yield filepath elif not os.path.exists(path): - broken.append(path) + broken.append(str(path)) else: yield path diff --git a/isort/io.py b/isort/io.py index 338ed0865..a8d760611 100644 --- a/isort/io.py +++ b/isort/io.py @@ -43,7 +43,7 @@ def _open(filename: str | Path) -> TextIOWrapper: encoding = File.detect_encoding(filename, buffer.readline) buffer.seek(0) text = TextIOWrapper(buffer, encoding, line_buffering=True, newline="") - text.mode = "r" # type: ignore + text.mode = "r" # type: ignore[misc] return text except Exception: buffer.close() diff --git a/isort/main.py b/isort/main.py index 3ad35766a..056e20b38 100644 --- a/isort/main.py +++ b/isort/main.py @@ -5,7 +5,7 @@ import json import os import sys -from collections.abc import Sequence +from collections.abc import Iterator, Sequence from contextlib import AbstractContextManager, nullcontext from gettext import gettext as _ from io import TextIOWrapper @@ -46,7 +46,7 @@ def __init__(self, incorrectly_sorted: bool, skipped: bool, supported_encoding: def sort_imports( - file_name: str, + file_name: str | Path, config: Config, check: bool = False, ask_to_apply: bool = False, @@ -90,7 +90,7 @@ def sort_imports( def _print_hard_fail( - config: Config, offending_file: str | None = None, message: str | None = None + config: Config, offending_file: str | Path | None = None, message: str | None = None ) -> None: """Fail on unrecoverable exception with custom message.""" message = message or ( @@ -1134,7 +1134,7 @@ def main(argv: Sequence[str] | None = None, stdin: TextIOWrapper | None = None) with executor_ctx as executor: if executor is not None: - attempt_iterator = executor.imap( + attempt_iterator: Iterator[SortAttempt | None] = executor.imap( functools.partial( sort_imports, config=config, @@ -1150,7 +1150,7 @@ def main(argv: Sequence[str] | None = None, stdin: TextIOWrapper | None = None) else: # https://github.com/python/typeshed/pull/2814 attempt_iterator = ( - sort_imports( # type: ignore + sort_imports( file_name, config=config, check=check, diff --git a/isort/output.py b/isort/output.py index bfbaee37a..7fa6e3e6f 100644 --- a/isort/output.py +++ b/isort/output.py @@ -6,7 +6,7 @@ from isort.format import format_simplified -from . import _parse_utils, parse, sorting, wrap +from . import _parse_utils, parse, sorting, wrap, wrap_modes from .comments import add_to_line as with_comments from .identify import STATEMENT_DECLARATIONS from .place import module_with_reason @@ -522,7 +522,7 @@ def _with_from_imports( ) if opening_comment: lines[0] += opening_comment - if config.multi_line_output == wrap.Modes.NOQA: # type: ignore[attr-defined] # noqa: E501 + if config.multi_line_output == wrap_modes.WrapModes.NOQA: lines[0] = wrap.line(lines[0], parsed.line_separator, config) output.append(parsed.line_separator.join(lines)) else: @@ -561,7 +561,7 @@ def _with_from_imports( # keep the name in the main list and hoist the comment to the statement. if ( comment.lower().startswith("noqa") - and config.multi_line_output == wrap.Modes.HANGING_INDENT # type: ignore[attr-defined] # noqa: E501 + and config.multi_line_output == wrap_modes.WrapModes.HANGING_INDENT ): comments = list(comments) if comments else [] comments.append(comment) @@ -621,7 +621,8 @@ def _with_from_imports( if ( len(import_statement) > config.line_length and len(from_import_section) > 0 - and config.multi_line_output not in (wrap.Modes.GRID, wrap.Modes.VERTICAL) # type: ignore # noqa: E501 + and config.multi_line_output + not in (wrap_modes.WrapModes.GRID, wrap_modes.WrapModes.VERTICAL) ): do_multiline_reformat = True @@ -660,14 +661,14 @@ def _with_from_imports( line_separator=parsed.line_separator, config=config, ) - if config.multi_line_output == wrap.Modes.GRID: # type: ignore + if config.multi_line_output == wrap_modes.WrapModes.GRID: other_import_statement = wrap.import_statement( import_start=import_start, from_imports=from_import_section, comments=comments, line_separator=parsed.line_separator, config=config, - multi_line_output=wrap.Modes.VERTICAL_GRID, # type: ignore + multi_line_output=wrap_modes.WrapModes.VERTICAL_GRID, ) if ( max( @@ -762,7 +763,7 @@ def _with_straight_imports( removed=config.ignore_comments, comment_prefix=config.comment_prefix, ) - if config.multi_line_output == wrap.Modes.NOQA: # type: ignore[attr-defined] + if config.multi_line_output == wrap_modes.WrapModes.NOQA: line_content = wrap.line(line_content, parsed.line_separator, config) output.append(line_content) diff --git a/isort/settings.py b/isort/settings.py index 1370e5b36..c75697fcf 100644 --- a/isort/settings.py +++ b/isort/settings.py @@ -278,7 +278,7 @@ class Config(_Config): def __init__( self, settings_file: str = "", - settings_path: str = "", + settings_path: str | Path = "", config: _Config | None = None, **config_overrides: Any, ): @@ -711,7 +711,7 @@ def _get_str_to_type_converter(setting_name: str) -> Callable[[str], Any] | type return type_converter -def _as_list(value: str) -> list[str]: +def _as_list(value: str | list[str]) -> list[str]: if isinstance(value, list): return [item.strip() for item in value] filtered = [item.strip() for item in value.replace("\n", ",").split(",") if item.strip()] @@ -867,7 +867,7 @@ def _get_config_data(file_path: str, sections: tuple[str, ...]) -> dict[str, Any if existing_value_type is tuple: settings[key] = tuple(_as_list(value)) elif existing_value_type is frozenset: - settings[key] = frozenset(_as_list(settings.get(key))) # type: ignore + settings[key] = frozenset(_as_list(settings.get(key))) # type: ignore[arg-type] elif existing_value_type is bool: # Only some configuration formats support native boolean values. if not isinstance(value, bool): diff --git a/isort/wrap.py b/isort/wrap.py index 89b0cb1fb..62ea31dbb 100644 --- a/isort/wrap.py +++ b/isort/wrap.py @@ -33,7 +33,7 @@ def import_statement( white_space=dynamic_indent, indent=indent, line_length=line_length, - comments=comments or (), + comments=comments or [], line_separator=line_separator, comment_prefix=config.comment_prefix, include_trailing_comma=include_trailing_comma, @@ -56,7 +56,7 @@ def import_statement( white_space=dynamic_indent, indent=indent, line_length=line_length, - comments=comments or (), + comments=comments or [], line_separator=line_separator, comment_prefix=config.comment_prefix, include_trailing_comma=include_trailing_comma, diff --git a/pyproject.toml b/pyproject.toml index 25e2b983f..da8665369 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -138,6 +138,7 @@ per-file-ignores = [ python_version = "3.10" strict = true follow_imports = "silent" +packages = ["isort", "tests"] exclude = "isort/_vendored|tests/unit/example_projects|tests/unit/example_crlf_file.py" [[tool.mypy.overrides]] diff --git a/tests/unit/test_regressions.py b/tests/unit/test_regressions.py index 6fbfae1f3..da00a5dd3 100644 --- a/tests/unit/test_regressions.py +++ b/tests/unit/test_regressions.py @@ -5,6 +5,7 @@ import pytest import isort +import isort.sections from isort.main import main @@ -235,9 +236,7 @@ def test_ensure_sre_parse_is_identified_as_stdlib_issue_1304(): """Ensure sre_parse is identified as STDLIB. See: https://github.com/pycqa/isort/issues/1304. """ - assert ( - isort.place_module("sre_parse") == isort.place_module("sre") == isort.settings.STDLIB # type: ignore # noqa - ) + assert isort.place_module("sre_parse") == isort.place_module("sre") == isort.sections.STDLIB def test_add_imports_shouldnt_move_lower_comments_issue_1300(): diff --git a/tests/unit/test_settings.py b/tests/unit/test_settings.py index d8b72ad6c..dbfc518a6 100644 --- a/tests/unit/test_settings.py +++ b/tests/unit/test_settings.py @@ -107,7 +107,7 @@ def test_deprecated_multi_line_output(self): def test_as_list(): - assert settings._as_list([" one "]) == ["one"] # type: ignore + assert settings._as_list([" one "]) == ["one"] assert settings._as_list("one,two") == ["one", "two"] diff --git a/tox.ini b/tox.ini index 648f46f55..bdda20dca 100644 --- a/tox.ini +++ b/tox.ini @@ -54,7 +54,7 @@ dependency_groups = dev commands = cruft check - mypy -p isort -p tests + mypy isort --profile hug --check --diff isort/ tests/ scripts/ isort --profile hug --check --diff example_isort_formatting_plugin/ isort --profile hug --check --diff example_isort_sorting_plugin/