diff --git a/lib/ts_utils/utils.py b/lib/ts_utils/utils.py index da9b8b7be758..a91694909e9f 100644 --- a/lib/ts_utils/utils.py +++ b/lib/ts_utils/utils.py @@ -23,7 +23,7 @@ from termcolor import colored as colored # pyright: ignore[reportAssignmentType] except ImportError: - def colored(text: str, color: str | None = None, **kwargs: Any) -> str: # type: ignore[misc] # noqa: ARG001 + def colored(text: str, color: str | None = None, **kwargs: Any) -> str: # type: ignore[misc] # ruff: ignore[unused-function-argument] return text @@ -179,7 +179,7 @@ def parse_stdlib_versions_file() -> SupportedVersions: with VERSIONS_PATH.open(encoding="UTF-8") as f: for line in f: stripped_line = strip_comments(line) - if stripped_line == "": + if not stripped_line: continue m = VERSION_LINE_RE.match(stripped_line) assert m, f"invalid VERSIONS line: {stripped_line}" @@ -255,15 +255,21 @@ def allowlists(distribution_name: str) -> list[str]: # For details, see https://github.com/python/typeshed/pull/13620#discussion_r1990185997 # Python 3.12 added a cross-platform solution with `tempfile.NamedTemporaryFile("w+", delete_on_close=False)` if sys.platform != "win32": - NamedTemporaryFile = tempfile.NamedTemporaryFile # noqa: TID251 + # We ignore the Ruff error here because this defines the helper that callers should use + # instead of `tempfile.NamedTemporaryFile`, which is banned by `banned-api`. + # + NamedTemporaryFile = tempfile.NamedTemporaryFile # ruff: ignore[banned-api] else: - def NamedTemporaryFile(mode: OpenTextMode) -> TemporaryFileWrapper[str]: # noqa: N802 + def NamedTemporaryFile(mode: OpenTextMode) -> TemporaryFileWrapper[str]: # ruff: ignore[invalid-function-name] def close(self: TemporaryFileWrapper[str]) -> None: TemporaryFileWrapper.close(self) # pyright: ignore[reportUnknownMemberType] Path(self.name).unlink() - temp = tempfile.NamedTemporaryFile(mode, delete=False) # noqa: SIM115, TID251 + # We ignore the `banned-api` Ruff error here because this call is part of the helper that callers should use + # instead of `tempfile.NamedTemporaryFile`. + # + temp = tempfile.NamedTemporaryFile(mode, delete=False) # ruff: ignore[open-file-with-context-handler, banned-api] temp.close = MethodType(close, temp) # type: ignore[method-assign] return temp diff --git a/pyproject.toml b/pyproject.toml index c3a4fe66b780..e832d3f1f711 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -45,6 +45,7 @@ exclude = [ [tool.ruff.lint] future-annotations = true +preview = true # Disable all rules on test cases by default: # test cases often deliberately contain code # that might not be considered idiomatic or modern. @@ -89,126 +90,128 @@ select = [ "ANN2", # Most refurb rules are in preview and can be opinionated, # consider them individually as they come out of preview (last check: 0.13.1) - "FURB105", # Unnecessary empty string passed to `print` - "FURB116", # Replace `{function_name}` call with `{display}` - "FURB122", # Use of `{}.write` in a for loop - "FURB129", # Instead of calling `readlines()`, iterate over file object directly - "FURB132", # Use `{suggestion}` instead of `check` and `remove` - "FURB136", # Replace `if` expression with `{min_max}` call - "FURB157", # Verbose expression in `Decimal` constructor - "FURB162", # Unnecessary timezone replacement with zero offset - "FURB166", # Use of `int` with explicit `base={base}` after removing prefix - "FURB167", # Use of regular expression alias `re.{}` - "FURB168", # Prefer `is` operator over `isinstance` to check if an object is `None` - "FURB169", # Compare the identities of `{object}` and None instead of their respective types - "FURB177", # Prefer `Path.cwd()` over `Path().resolve()` for current-directory lookups - "FURB187", # Use of assignment of `reversed` on list `{name}` - "FURB188", # Prefer `str.removeprefix()` over conditionally replacing with slice. + "print-empty-string", # Unnecessary empty string passed to `print` + "f-string-number-format", # Replace `{function_name}` call with `{display}` + "for-loop-writes", # Use of `{}.write` in a for loop + "readlines-in-for", # Instead of calling `readlines()`, iterate over file object directly + "check-and-remove-from-set", # Use `{suggestion}` instead of `check` and `remove` + "if-expr-min-max", # Replace `if` expression with `{min_max}` call + "verbose-decimal-constructor", # Verbose expression in `Decimal` constructor + "fromisoformat-replace-z", # Unnecessary timezone replacement with zero offset + "int-on-sliced-str", # Use of `int` with explicit `base={base}` after removing prefix + "regex-flag-alias", # Use of regular expression alias `re.{}` + "isinstance-type-none", # Prefer `is` operator over `isinstance` to check if an object is `None` + "type-none-comparison", # Compare the identities of `{object}` and None instead of their respective types + "implicit-cwd", # Prefer `Path.cwd()` over `Path().resolve()` for current-directory lookups + "list-reverse-copy", # Use of assignment of `reversed` on list `{name}` + "slice-to-remove-prefix-or-suffix", # Prefer `str.removeprefix()` over conditionally replacing with slice. # Used for lint.flake8-import-conventions.aliases - "ICN001", # `{name}` should be imported as `{asname}` + "unconventional-import-alias", # `{name}` should be imported as `{asname}` # PYI: only enable rules that have autofixes and that we always want to fix (even manually), # avoids duplicate # noqa with flake8-pyi - "PYI009", # Empty body should contain `...`, not pass - "PYI010", # Function body must contain only `...` - "PYI012", # Class bodies must not contain `pass` - "PYI013", # Non-empty class bodies must not contain `...` - "PYI014", # Only simple default values allowed for arguments - "PYI015", # Only simple default values allowed for assignments - "PYI016", # Duplicate union member `{}` - "PYI018", # Private `{type_var_like_kind}` `{type_var_like_name}` is never used - "PYI019", # Methods like `{method_name}` should return `Self` instead of a custom `TypeVar` - "PYI020", # Quoted annotations should not be included in stubs - "PYI025", # Use `from collections.abc import Set as AbstractSet` to avoid confusion with the `set` builtin + "pass-statement-stub-body", # Empty body should contain `...`, not pass + "non-empty-stub-body", # Function body must contain only `...` + "pass-in-class-body", # Class bodies must not contain `pass` + "ellipsis-in-non-empty-class-body", # Non-empty class bodies must not contain `...` + "argument-default-in-stub", # Only simple default values allowed for arguments + "assignment-default-in-stub", # Only simple default values allowed for assignments + "duplicate-union-member", + "unused-private-type-var", # Private `{type_var_like_kind}` `{type_var_like_name}` is never used + "custom-type-var-for-self", # Methods like `{method_name}` should return `Self` instead of a custom `TypeVar` + "quoted-annotation-in-stub", # Quoted annotations should not be included in stubs + "unaliased-collections-abc-set-import", # Use `from collections.abc import Set as AbstractSet` to avoid confusion with the `set` builtin # "PYI026", Waiting for this mypy bug to be fixed: https://github.com/python/mypy/issues/16581 - "PYI030", # Multiple literal members in a union. Use a single literal, e.g. `Literal[{}]` - "PYI032", # Prefer `object` to `Any` for the second parameter to `{method_name}` - "PYI036", # Star-args in `{method_name}` should be annotated with `object` - "PYI044", # `from __future__ import annotations` has no effect in stub files, since type checkers automatically treat stubs as having those semantics - "PYI055", # Multiple `type[T]` usages in a union. Combine them into one, e.g., `type[{union_str}]`. - "PYI058", # Use `{return_type}` as the return value for simple `{method}` methods - "PYI059", # Checks for classes inheriting from typing.Generic[] where Generic[] is not the last base class in the bases tuple - "PYI061", # Use `None` rather than `Literal[None]` - "PYI062", # Duplicate literal member `{}` - "PYI064", # `Final[Literal[{literal}]]` can be replaced with a bare Final + "unnecessary-literal-union", # Multiple literal members in a union. Use a single literal, e.g. `Literal[{}]` + "any-eq-ne-annotation", # Prefer `object` to `Any` for the second parameter to `{method_name}` + "bad-exit-annotation", # Star-args in `{method_name}` should be annotated with `object` + "future-annotations-in-stub", # `from __future__ import annotations` has no effect in stub files, since type checkers automatically treat stubs as having those semantics + "unnecessary-type-union", # Multiple `type[T]` usages in a union. Combine them into one, e.g., `type[{union_str}]`. + "generator-return-from-iter-method", # Use `{return_type}` as the return value for simple `{method}` methods + "generic-not-last-base-class", # Checks for classes inheriting from typing.Generic[] where Generic[] is not the last base class in the bases tuple + "redundant-none-literal", # Use `None` rather than `Literal[None]` + "duplicate-literal-member", # Duplicate literal member `{}` + "redundant-final-literal", # `Final[Literal[{literal}]]` can be replaced with a bare Final # flake8-simplify, excluding rules that can reduce performance or readability due to long line formatting - "SIM101", # Multiple `isinstance` calls for `{name}`, merge into a single call - "SIM103", # Return the condition `{condition}` directly - "SIM107", # Don't use return in `try-except` and `finally` - "SIM109", # Use `{replacement}` instead of multiple equality comparisons - "SIM112", # Use capitalized environment variable `{expected}` instead of `{actual}` - "SIM113", # Use `enumerate()` for index variable `{index}` in `for` loop - "SIM114", # Combine `if` branches using logical `or` operator - "SIM115", # Use a context manager for opening files - "SIM118", # Use key `{operator}` dict instead of key `{operator} dict.keys()` - "SIM201", # Use `{left} != {right}` instead of not `{left} == {right}` - "SIM202", # Use `{left} == {right}` instead of not `{left} != {right}` - "SIM208", # Use `{expr}` instead of `not (not {expr})` - "SIM210", # Remove unnecessary `True if ... else False` - "SIM211", # Use `not ...` instead of `False if ... else True` - "SIM212", # Use `{expr_else} if {expr_else} else {expr_body}` instead of `{expr_body} if not {expr_else} else {expr_else}` - "SIM220", # Use `False` instead of `{name} and not {name}` - "SIM221", # Use `True` instead of `{name} or not {name}` - "SIM222", # Use `{expr}` instead of `{replaced}` - "SIM223", # Use `{expr}` instead of `{replaced}` - "SIM300", # Yoda condition detected - "SIM401", # Use `{contents}` instead of an if block - "SIM905", # Consider using a list literal instead of `str.{}` - "SIM910", # Use `{expected}` instead of `{actual}` (dict-get-with-none-default) - "SIM911", # Use `{expected}` instead of `{actual}` (zip-dict-keys-and-values) + "duplicate-isinstance-call", # Multiple `isinstance` calls for `{name}`, merge into a single call + "needless-bool", # Return the condition `{condition}` directly + "return-in-try-except-finally", # Don't use return in `try-except` and `finally` + "compare-with-tuple", # Use `{replacement}` instead of multiple equality comparisons + "uncapitalized-environment-variables", # Use capitalized environment variable `{expected}` instead of `{actual}` + "enumerate-for-loop", # Use `enumerate()` for index variable `{index}` in `for` loop + "if-with-same-arms", # Combine `if` branches using logical `or` operator + "open-file-with-context-handler", # Use a context manager for opening files + "in-dict-keys", # Use key `{operator}` dict instead of key `{operator} dict.keys()` + "negate-equal-op", # Use `{left} != {right}` instead of not `{left} == {right}` + "negate-not-equal-op", # Use `{left} == {right}` instead of not `{left} != {right}` + "double-negation", # Use `{expr}` instead of `not (not {expr})` + "if-expr-with-true-false", # Remove unnecessary `True if ... else False` + "if-expr-with-false-true", # Use `not ...` instead of `False if ... else True` + "if-expr-with-twisted-arms", # Use `{expr_else} if {expr_else} else {expr_body}` instead of `{expr_body} if not {expr_else} else {expr_else}` + "expr-and-not-expr", # Use `False` instead of `{name} and not {name}` + "expr-or-not-expr", # Use `True` instead of `{name} or not {name}` + "expr-or-true", + "expr-and-false", + "yoda-conditions", + "if-else-block-instead-of-dict-get", + "split-static-string", # Consider using a list literal instead of `str.{}` + "dict-get-with-none-default", + "zip-dict-keys-and-values", # Don't include TC rules that create a TYPE_CHECKING block or stringifies annotations - "TC004", # Move import `{qualified_name}` out of type-checking block. Import is used for more than type hinting. - "TC005", # Found empty type-checking block - # "TC008", # TODO: Enable when out of preview - "TC010", # Invalid string member in `X | Y`-style union type + "runtime-import-in-type-checking-block", # Move import `{qualified_name}` out of type-checking block. Import is used for more than type hinting. + "empty-type-checking-block", + "quoted-type-alias", + "runtime-string-union", # Invalid string member in `X | Y`-style union type # Used for lint.flake8-import-conventions.aliases - "TID251", # `{name}` is banned: {message} + "banned-api", ] extend-safe-fixes = [ - "UP036", # Remove unnecessary `sys.version_info` blocks + "outdated-version-block", # Remove unnecessary `sys.version_info` blocks ] ignore = [ ### # Rules that can conflict with the formatter (Black) # https://docs.astral.sh/ruff/formatter/#conflicting-lint-rules ### - "E111", # indentation-with-invalid-multiple - "E114", # indentation-with-invalid-multiple-comment - "E117", # over-indented - "W191", # tab-indentation + "indentation-with-invalid-multiple", + "indentation-with-invalid-multiple-comment", + "over-indented", + "tab-indentation", ### # Rules we don't want or don't agree with ### # We're not a library, no need to document everything "D1", # Missing docstring in ... # Sometimes, an extra blank line is more readable - "D202", # No blank lines allowed after function docstring + "blank-line-after-function", # No blank lines allowed after function docstring # Doesn't support split "summary line" - "D205", # 1 blank line required between summary line and description + "missing-blank-line-after-summary", # 1 blank line required between summary line and description # Used for direct, non-subclass type comparison, for example: `type(val) is str` # see https://github.com/astral-sh/ruff/issues/6465 - "E721", # Do not compare types, use `isinstance()` + "type-comparison", # Do not compare types, use `isinstance()` # Highly opinionated, and it's often necessary to violate it - "PLC0415", # `import` should be at the top-level of a file + "import-outside-top-level", # `import` should be at the top-level of a file # Leave the size and complexity of tests to human interpretation "PLR09", # Too many ... # Too many magic number "2" that are preferable inline. https://github.com/astral-sh/ruff/issues/10009 - "PLR2004", # Magic value used in comparison, consider replacing `{value}` with a constant variable + "magic-value-comparison", # Magic value used in comparison, consider replacing `{value}` with a constant variable # Keep codeflow path separation explicit - "PLR5501", # Use `elif` instead of `else` then `if`, to reduce indentation + "collapsible-else-if", # Use `elif` instead of `else` then `if`, to reduce indentation # Often just leads to redundant more verbose code when needing an actual str - "PTH208", # Use `pathlib.Path.iterdir()` instead. + "os-listdir", # Use `pathlib.Path.iterdir()` instead. # Allow FIXME - "TD001", # Invalid TODO tag: `{tag}` + "invalid-todo-tag", # Invalid TODO tag: `{tag}` # Git blame is sufficient - "TD002", # Missing author in TODO; - "TD003", # Missing issue link for this TODO + "missing-todo-author", # Missing author in TODO; + "missing-todo-link", # Missing issue link for this TODO # Mostly from scripts and tests, it's ok to have messages passed directly to exceptions - "TRY003", # Avoid specifying long messages outside the exception class + "raise-vanilla-args", # Avoid specifying long messages outside the exception class + # Stubs need private imports to describe runtime APIs; our scripts also import local private modules such as `_utils`. + "import-private-name", ### # False-positives, but already checked by type-checkers ### # Ruff doesn't support multi-file analysis yet: https://github.com/astral-sh/ruff/issues/5295 - "RUF013", # PEP 484 prohibits implicit `Optional` + "implicit-optional", # PEP 484 prohibits implicit `Optional` ] [tool.ruff.lint.per-file-ignores] @@ -219,8 +222,8 @@ ignore = [ # Ruff 0.8.0 added sorting of __all__ and __slots_. # There is no consensus on whether we want to apply this to stubs, so keeping the status quo. # See https://github.com/python/typeshed/pull/13108 - "RUF022", # `__all__` is not sorted - "RUF023", # `{}.__slots__` is not sorted + "unsorted-dunder-all", + "unsorted-dunder-slots", ### # Rules that are out of the control of stub authors: ### @@ -229,30 +232,32 @@ ignore = [ "A", # flake8-builtins # Stubs can sometimes re-export entire modules. # Issues with using a star-imported name will be caught by type-checkers. - "F403", # `from . import *` used; unable to detect undefined names - "F405", # may be undefined, or defined from star imports + "undefined-local-with-import-star", # `from . import *` used; unable to detect undefined names + "undefined-local-with-import-star-usage", # may be undefined, or defined from star imports # Most pep8-naming rules don't apply for third-party stubs like typeshed. # N811 to N814 could apply, but we often use them to disambiguate a name whilst making it look like a more common one "N8", # pep8-naming # Sometimes __slots__ really is a string at runtime - "PLC0205", # Class `__slots__` should be a non-string iterable - # Stubs are allowed to use private variables (pyright's reportPrivateUsage is also disabled) - "PLC2701", # Private name import from external module + "single-string-slots", # Class `__slots__` should be a non-string iterable # Names in stubs should match implementation - "PLW0211", # First argument of a static method should not be named `{argument_name}` + "bad-staticmethod-argument", # First argument of a static method should not be named `{argument_name}` + # Runtime classes may redefine inherited slots, which their stubs need to preserve. + "redefined-slots-in-subclass", + # String literals in stubs must sometimes match runtime values containing confusable Unicode. + "ambiguous-unicode-character-string", ] "lib/ts_utils/**" = [ # Doesn't affect stubs. The only re-exports we have should be in our local lib ts_utils - "PLC0414", # Import alias does not rename original package + "useless-import-alias", # Import alias does not rename original package ] "*_pb2.pyi" = [ # Special autogenerated typing --> typing_extensions aliases - "ICN001", # `{name}` should be imported as `{asname}` + "unconventional-import-alias", # `{name}` should be imported as `{asname}` # Leave the docstrings as-is, matching source "D", # pydocstyle # See comment on black's force-exclude config above - "E501", # Line too long - "UP036", # Remove unnecessary `sys.version_info` blocks + "line-too-long", + "outdated-version-block", # Remove unnecessary `sys.version_info` blocks ] [tool.ruff.lint.pydocstyle] diff --git a/scripts/stubsabot.py b/scripts/stubsabot.py index ab77367c6c56..7ced8f5a81e0 100755 --- a/scripts/stubsabot.py +++ b/scripts/stubsabot.py @@ -361,7 +361,7 @@ async def get_host_repo_info(session: aiohttp.ClientSession, stub_info: StubMeta # so no need to repeat all of them here split_url = urllib.parse.urlsplit(stub_info.upstream_repository) host = split_url.netloc.removesuffix(".com") - if host not in ("github", "gitlab"): + if host not in {"github", "gitlab"}: return None url_path = split_url.path.strip("/") assert len(Path(url_path).parts) == 2 diff --git a/scripts/sync_protobuf/google_protobuf.py b/scripts/sync_protobuf/google_protobuf.py index 358e5c454e44..f285a45d129e 100755 --- a/scripts/sync_protobuf/google_protobuf.py +++ b/scripts/sync_protobuf/google_protobuf.py @@ -33,7 +33,7 @@ def extract_python_version(file_path: Path) -> str: """Extract the Python version from https://github.com/protocolbuffers/protobuf/blob/main/version.json .""" - with file_path.open() as file: + with file_path.open(encoding="utf-8") as file: data: dict[str, Any] = json.load(file) # The root key will be the protobuf source code version version = next(iter(data.values()))["languages"]["python"] diff --git a/scripts/sync_protobuf/s2clientprotocol.py b/scripts/sync_protobuf/s2clientprotocol.py index cee68e1edea9..95fcc2086b8c 100755 --- a/scripts/sync_protobuf/s2clientprotocol.py +++ b/scripts/sync_protobuf/s2clientprotocol.py @@ -31,7 +31,7 @@ def extract_python_version(file_path: Path) -> str: """Extract Python version from s2clientprotocol's build file.""" - match = re.search(VERSION_PATTERN, file_path.read_text()) + match = re.search(VERSION_PATTERN, file_path.read_text(encoding="utf-8")) assert match return match.group(1) diff --git a/stdlib/_collections_abc.pyi b/stdlib/_collections_abc.pyi index 6fc32078532e..363098df8058 100644 --- a/stdlib/_collections_abc.pyi +++ b/stdlib/_collections_abc.pyi @@ -1,7 +1,7 @@ import sys from abc import abstractmethod from types import MappingProxyType -from typing import ( # noqa: Y022,Y038,UP035,Y057 +from typing import ( # noqa: Y022,Y038,Y057 # ruff: ignore[deprecated-import] AbstractSet as Set, AsyncGenerator as AsyncGenerator, AsyncIterable as AsyncIterable, diff --git a/stdlib/builtins.pyi b/stdlib/builtins.pyi index 949a7a08f1bf..0cd6bd32b256 100644 --- a/stdlib/builtins.pyi +++ b/stdlib/builtins.pyi @@ -37,7 +37,7 @@ from types import CellType, CodeType, EllipsisType, GenericAlias, NotImplemented # mypy crashes if any of {ByteString, Sequence, MutableSequence, Mapping, MutableMapping} # are imported from collections.abc in builtins.pyi -from typing import ( # noqa: Y022,UP035 +from typing import ( # noqa: Y022 # ruff: ignore[deprecated-import] IO, Any, BinaryIO, @@ -65,7 +65,8 @@ from typing import ( # noqa: Y022,UP035 ) # we can't import `Literal` from typing or mypy crashes: see #11247 -from typing_extensions import Literal, LiteralString, Self, TypeIs, TypeVarTuple, deprecated, disjoint_base # noqa: Y023, UP035 +# ruff: ignore[deprecated-import] +from typing_extensions import Literal, LiteralString, Self, TypeIs, TypeVarTuple, deprecated, disjoint_base # noqa: Y023 if sys.version_info >= (3, 14): from _typeshed import AnnotateFunc @@ -91,11 +92,11 @@ _P = ParamSpec("_P") # Type variables for slice _StartT_co = TypeVar("_StartT_co", covariant=True, default=Any) # slice -> slice[Any, Any, Any] -_StopT_co = TypeVar("_StopT_co", covariant=True, default=_StartT_co) # slice[A] -> slice[A, A, A] +_StopT_co = TypeVar("_StopT_co", covariant=True, default=_StartT_co) # slice[A] -> slice[A, A, A] # NOTE: step could differ from start and stop, (e.g. datetime/timedelta)l # the default (start|stop) is chosen to cater to the most common case of int/index slices. # FIXME: https://github.com/python/typing/issues/213 (replace step=start|stop with step=start&stop) -_StepT_co = TypeVar("_StepT_co", covariant=True, default=_StartT_co | _StopT_co) # slice[A,B] -> slice[A, B, A|B] +_StepT_co = TypeVar("_StepT_co", covariant=True, default=_StartT_co | _StopT_co) # slice[A,B] -> slice[A, B, A|B] @disjoint_base class object: @@ -1005,7 +1006,7 @@ class memoryview(Sequence[_I]): def __enter__(self) -> Self: ... def __exit__( self, - exc_type: type[BaseException] | None, # noqa: PYI036 # This is the module declaring BaseException + exc_type: type[BaseException] | None, # ruff: ignore[bad-exit-annotation] # This is the module declaring BaseException exc_val: BaseException | None, exc_tb: TracebackType | None, /, diff --git a/stdlib/email/__init__.pyi b/stdlib/email/__init__.pyi index fbd89b5dc0bc..f2a0a92703e3 100644 --- a/stdlib/email/__init__.pyi +++ b/stdlib/email/__init__.pyi @@ -9,7 +9,7 @@ from typing import TypeAlias, overload # At runtime, listing submodules in __all__ without them being imported is # valid, and causes them to be included in a star import. See #6523 -__all__ = [ # noqa: F822 # Undefined names in __all__ +__all__ = [ # ruff: ignore[undefined-export] # Undefined names in __all__ "base64mime", # pyright: ignore[reportUnsupportedDunderAll] "charset", # pyright: ignore[reportUnsupportedDunderAll] "encoders", # pyright: ignore[reportUnsupportedDunderAll] diff --git a/stdlib/typing.pyi b/stdlib/typing.pyi index c5509510b4a1..198dd45feedf 100644 --- a/stdlib/typing.pyi +++ b/stdlib/typing.pyi @@ -1,7 +1,7 @@ # Since this module defines "overload" it is not recognized by Ruff as typing.overload # TODO: The collections import is required, otherwise mypy crashes. # https://github.com/python/mypy/issues/16744 -import collections # noqa: F401 # pyright: ignore[reportUnusedImport] +import collections # ruff: ignore[unused-import] # pyright: ignore[reportUnusedImport] import sys import typing_extensions from _collections_abc import dict_items, dict_keys, dict_values diff --git a/stdlib/typing_extensions.pyi b/stdlib/typing_extensions.pyi index c3dbcd7be363..49ddbc2f24bf 100644 --- a/stdlib/typing_extensions.pyi +++ b/stdlib/typing_extensions.pyi @@ -30,7 +30,7 @@ from collections.abc import ( from contextlib import AbstractAsyncContextManager as AsyncContextManager, AbstractContextManager as ContextManager from re import Match as Match, Pattern as Pattern from types import GenericAlias, ModuleType, UnionType -from typing import ( # noqa: Y022,Y037,Y038,Y039,UP035 +from typing import ( # noqa: Y022,Y037,Y038,Y039 # ruff: ignore[deprecated-import] IO as IO, TYPE_CHECKING as TYPE_CHECKING, AbstractSet as AbstractSet, diff --git a/stdlib/xml/__init__.pyi b/stdlib/xml/__init__.pyi index 555d9b8f90a9..969712fd20b0 100644 --- a/stdlib/xml/__init__.pyi +++ b/stdlib/xml/__init__.pyi @@ -2,7 +2,7 @@ # valid, and causes them to be included in a star import. See #6523 import sys -__all__ = ["dom", "parsers", "sax", "etree"] # noqa: F822 # pyright: ignore[reportUnsupportedDunderAll] +__all__ = ["dom", "parsers", "sax", "etree"] # ruff: ignore[undefined-export] # pyright: ignore[reportUnsupportedDunderAll] if sys.version_info >= (3, 15): __all__ += ["is_valid_name"] # pyright: ignore[reportUnsupportedDunderAll] diff --git a/stubs/gunicorn/gunicorn/_types.pyi b/stubs/gunicorn/gunicorn/_types.pyi index 815a1179f98c..14e8f740a8be 100644 --- a/stubs/gunicorn/gunicorn/_types.pyi +++ b/stubs/gunicorn/gunicorn/_types.pyi @@ -1,4 +1,6 @@ -### This .pyi file is a helper for centralized storage types that are reused across different runtime modules. ### +############################################################################################################ +# This .pyi file is a helper for centralized storage types that are reused across different runtime modules. +############################################################################################################ from _typeshed import FileDescriptor from collections.abc import Awaitable, Callable, Iterable, MutableMapping from typing import Any, TypeAlias diff --git a/stubs/pika/pika/adapters/twisted_connection.pyi b/stubs/pika/pika/adapters/twisted_connection.pyi index 5fcaa6835c90..d7021aafe991 100644 --- a/stubs/pika/pika/adapters/twisted_connection.pyi +++ b/stubs/pika/pika/adapters/twisted_connection.pyi @@ -13,14 +13,8 @@ from pika.channel import Channel from pika.connection import Connection, ConnectionParameters, Parameters from pika.exchange_type import ExchangeType from pika.spec import BasicProperties -from twisted.internet.base import ( # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] - DelayedCall, - ReactorBase, -) -from twisted.internet.defer import ( # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] - Deferred, - DeferredQueue, -) +from twisted.internet.base import DelayedCall, ReactorBase # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] +from twisted.internet.defer import Deferred, DeferredQueue # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] from twisted.internet.interfaces import ITransport # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] from twisted.internet.protocol import Protocol # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] from twisted.python.failure import Failure # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] diff --git a/stubs/psycopg2/psycopg2/_psycopg.pyi b/stubs/psycopg2/psycopg2/_psycopg.pyi index 91e51a53a012..1cde17a9a4de 100644 --- a/stubs/psycopg2/psycopg2/_psycopg.pyi +++ b/stubs/psycopg2/psycopg2/_psycopg.pyi @@ -235,7 +235,7 @@ class ConnectionInfo: # [1]: https://www.psycopg.org/docs/extensions.html#psycopg2.extensions.ConnectionInfo # [2]: https://github.com/psycopg/psycopg2/blob/1d3a89a0bba621dc1cc9b32db6d241bd2da85ad1/psycopg/conninfo_type.c#L52 and below # [3]: https://www.postgresql.org/docs/current/libpq-status.html - # [4]: https://github.com/postgres/postgres/blob/b39838889e76274b107935fa8e8951baf0e8b31b/src/interfaces/libpq/fe-connect.c#L6754 and below # noqa: E501 + # [4]: https://github.com/postgres/postgres/blob/b39838889e76274b107935fa8e8951baf0e8b31b/src/interfaces/libpq/fe-connect.c#L6754 and below # ruff: ignore[line-too-long] @property def backend_pid(self) -> int: ... @property diff --git a/stubs/pyxdg/xdg/Menu.pyi b/stubs/pyxdg/xdg/Menu.pyi index bd0b7af99651..0d56c6c28369 100644 --- a/stubs/pyxdg/xdg/Menu.pyi +++ b/stubs/pyxdg/xdg/Menu.pyi @@ -95,7 +95,7 @@ class MenuEntry: TYPE_SYSTEM: Literal["System"] TYPE_BOTH: Literal["Both"] DesktopEntry: DesktopEntry - Show: Literal[True, False, "Deleted", "NoDisplay", "Hidden", "Empty", "NotShowIn", "NoExec"] + Show: bool | Literal["Deleted", "NoDisplay", "Hidden", "Empty", "NotShowIn", "NoExec"] Visible: Literal[1, 0, "Deleted", "NoDisplay", "Hidden", "Empty", "NotShowIn", "NoExec"] Original: MenuEntry | None Parents: list[Menu] diff --git a/stubs/reportlab/reportlab/lib/rltempfile.pyi b/stubs/reportlab/reportlab/lib/rltempfile.pyi index 82979cda9478..95675a82ce2b 100644 --- a/stubs/reportlab/reportlab/lib/rltempfile.pyi +++ b/stubs/reportlab/reportlab/lib/rltempfile.pyi @@ -2,4 +2,4 @@ def get_rl_tempdir(*subdirs: str) -> str: ... def get_rl_tempfile(fn: str | None = None) -> str: ... # The duplicate entry matches the runtime __all__. -__all__ = ("get_rl_tempdir", "get_rl_tempdir") # noqa: RUF068 +__all__ = ("get_rl_tempdir", "get_rl_tempdir") # ruff: ignore[duplicate-entry-in-dunder-all] diff --git a/stubs/six/six/moves/builtins.pyi b/stubs/six/six/moves/builtins.pyi index eee6b75c0554..2b1b40808aca 100644 --- a/stubs/six/six/moves/builtins.pyi +++ b/stubs/six/six/moves/builtins.pyi @@ -1,3 +1,3 @@ # six explicitly re-exports builtins. Normally this is something we'd want to avoid. # But this is specifically a compatibility package. -from builtins import * # noqa: UP029 +from builtins import * # ruff: ignore[unnecessary-builtin-import] diff --git a/stubs/workalendar/workalendar/europe/__init__.pyi b/stubs/workalendar/workalendar/europe/__init__.pyi index afaccb646847..122321812f78 100644 --- a/stubs/workalendar/workalendar/europe/__init__.pyi +++ b/stubs/workalendar/workalendar/europe/__init__.pyi @@ -250,7 +250,7 @@ __all__ = ( "ValencianCommunity", # Switzerland # The duplicate entry matches the runtime __all__. - "Switzerland", # noqa: RUF068 + "Switzerland", # ruff: ignore[duplicate-entry-in-dunder-all] "Aargau", "AppenzellInnerrhoden", "AppenzellAusserrhoden", diff --git a/stubs/workalendar/workalendar/europe/scotland/mixins/__init__.pyi b/stubs/workalendar/workalendar/europe/scotland/mixins/__init__.pyi index db24b35f5af5..4b74b6da6488 100644 --- a/stubs/workalendar/workalendar/europe/scotland/mixins/__init__.pyi +++ b/stubs/workalendar/workalendar/europe/scotland/mixins/__init__.pyi @@ -49,7 +49,7 @@ __all__ = [ "SpringHolidayFirstMondayJune", "VictoriaDayFourthMondayMay", "VictoriaDayLastMondayMay", - "VictoriaDayTuesdayAfterFirstMondayMay", # noqa: F822 # pyright: ignore[reportUnsupportedDunderAll] see https://github.com/workalendar/workalendar/pull/778 # pyrefly: ignore [bad-dunder-all] + "VictoriaDayTuesdayAfterFirstMondayMay", # ruff: ignore[undefined-export] # pyright: ignore[reportUnsupportedDunderAll] # pyrefly: ignore [bad-dunder-all] # see https://github.com/workalendar/workalendar/pull/778 "VictoriaDayFirstMondayJune", "FairHolidayLastMondayJune", "FairHolidayFirstMondayJuly", diff --git a/stubs/yt-dlp/yt_dlp/compat/__init__.pyi b/stubs/yt-dlp/yt_dlp/compat/__init__.pyi index 000a451745b0..4d5f96eb63f9 100644 --- a/stubs/yt-dlp/yt_dlp/compat/__init__.pyi +++ b/stubs/yt-dlp/yt_dlp/compat/__init__.pyi @@ -1,5 +1,4 @@ import datetime -import urllib import urllib.request import xml.etree.ElementTree as etree diff --git a/stubs/yt-dlp/yt_dlp/utils/_jsruntime.pyi b/stubs/yt-dlp/yt_dlp/utils/_jsruntime.pyi index 3b66663a6e0b..4fc92f699623 100644 --- a/stubs/yt-dlp/yt_dlp/utils/_jsruntime.pyi +++ b/stubs/yt-dlp/yt_dlp/utils/_jsruntime.pyi @@ -14,25 +14,22 @@ class JsRuntimeInfo: class JsRuntime(abc.ABC): def __init__(self, path: str | None = None) -> None: ... @cached_property - @abc.abstractmethod def info(self) -> JsRuntimeInfo | None: ... + @abc.abstractmethod + def _info(self) -> JsRuntimeInfo | None: ... class DenoJsRuntime(JsRuntime): MIN_SUPPORTED_VERSION: Final[tuple[int, int, int]] - @cached_property - def info(self) -> JsRuntimeInfo | None: ... + def _info(self) -> JsRuntimeInfo | None: ... class BunJsRuntime(JsRuntime): MIN_SUPPORTED_VERSION: Final[tuple[int, int, int]] - @cached_property - def info(self) -> JsRuntimeInfo | None: ... + def _info(self) -> JsRuntimeInfo | None: ... class NodeJsRuntime(JsRuntime): MIN_SUPPORTED_VERSION: Final[tuple[int, int, int]] - @cached_property - def info(self) -> JsRuntimeInfo | None: ... + def _info(self) -> JsRuntimeInfo | None: ... class QuickJsRuntime(JsRuntime): MIN_SUPPORTED_VERSION: Final[tuple[int, int, int]] - @cached_property - def info(self) -> JsRuntimeInfo | None: ... + def _info(self) -> JsRuntimeInfo | None: ... diff --git a/tests/mypy_test.py b/tests/mypy_test.py index e9642070d148..d17b0df02276 100755 --- a/tests/mypy_test.py +++ b/tests/mypy_test.py @@ -38,7 +38,7 @@ # Fail early if mypy isn't installed try: - import mypy # pyright: ignore[reportUnusedImport] # noqa: F401 + import mypy # pyright: ignore[reportUnusedImport] # ruff: ignore[unused-import] except ImportError: print_error("Cannot import mypy. Did you install it?") sys.exit(1)