Skip to content

Commit a045be8

Browse files
authored
Import names from typing directly rather than importing module (#13761)
1 parent 7ffb7e0 commit a045be8

File tree

10 files changed

+43
-34
lines changed

10 files changed

+43
-34
lines changed

.pre-commit-config.yaml

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ repos:
2222
name: Run ruff on the test cases
2323
args:
2424
- "--exit-non-zero-on-fix"
25-
- "--select=FA,I,RUF100"
25+
- "--select=FA,I,ICN001,RUF100"
2626
- "--no-force-exclude"
2727
- "--unsafe-fixes"
2828
files: '.*test_cases/.+\.py$'

pyproject.toml

+9
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,8 @@ select = [
8383
"FURB169", # Compare the identities of `{object}` and None instead of their respective types
8484
"FURB177", # Prefer `Path.cwd()` over `Path().resolve()` for current-directory lookups
8585
"FURB187", # Use of assignment of `reversed` on list `{name}`
86+
# Used for lint.flake8-import-conventions.aliases
87+
"ICN001", # `{name}` should be imported as `{asname}`
8688
# Autofixable flake8-use-pathlib only
8789
"PTH201", # Do not pass the current directory explicitly to `Path`
8890
"PTH210", # Invalid suffix passed to `.with_suffix()`
@@ -217,6 +219,8 @@ ignore = [
217219
"PLC0414", # Import alias does not rename original package
218220
]
219221
"*_pb2.pyi" = [
222+
# Special autogenerated typing --> typing_extensions aliases
223+
"ICN001", # `{name}` should be imported as `{asname}`
220224
# Leave the docstrings as-is, matching source
221225
"D", # pydocstyle
222226
# See comment on black's force-exclude config above
@@ -226,6 +230,11 @@ ignore = [
226230
[tool.ruff.lint.pydocstyle]
227231
convention = "pep257" # https://docs.astral.sh/ruff/settings/#lint_pydocstyle_convention
228232

233+
[tool.ruff.lint.flake8-import-conventions.aliases]
234+
# Prevent aliasing these, as it causes false-negatives for certain rules
235+
typing_extensions = "typing_extensions"
236+
typing = "typing"
237+
229238
[tool.ruff.lint.isort]
230239
split-on-trailing-comma = false
231240
combine-as-imports = true

stdlib/@tests/test_cases/check_re.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,18 @@
22

33
import mmap
44
import re
5-
import typing as t
5+
from typing import AnyStr, Match, Optional
66
from typing_extensions import assert_type
77

88

99
def check_search(str_pat: re.Pattern[str], bytes_pat: re.Pattern[bytes]) -> None:
10-
assert_type(str_pat.search("x"), t.Optional[t.Match[str]])
11-
assert_type(bytes_pat.search(b"x"), t.Optional[t.Match[bytes]])
12-
assert_type(bytes_pat.search(bytearray(b"x")), t.Optional[t.Match[bytes]])
13-
assert_type(bytes_pat.search(mmap.mmap(0, 10)), t.Optional[t.Match[bytes]])
10+
assert_type(str_pat.search("x"), Optional[Match[str]])
11+
assert_type(bytes_pat.search(b"x"), Optional[Match[bytes]])
12+
assert_type(bytes_pat.search(bytearray(b"x")), Optional[Match[bytes]])
13+
assert_type(bytes_pat.search(mmap.mmap(0, 10)), Optional[Match[bytes]])
1414

1515

16-
def check_search_with_AnyStr(pattern: re.Pattern[t.AnyStr], string: t.AnyStr) -> re.Match[t.AnyStr]:
16+
def check_search_with_AnyStr(pattern: re.Pattern[AnyStr], string: AnyStr) -> re.Match[AnyStr]:
1717
"""See issue #9591"""
1818
match = pattern.search(string)
1919
if match is None:

stdlib/@tests/test_cases/typing/check_regression_issue_9296.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
from __future__ import annotations
22

3-
import typing as t
3+
from typing import Any, KeysView, TypeVar
44

5-
KT = t.TypeVar("KT")
5+
KT = TypeVar("KT")
66

77

8-
class MyKeysView(t.KeysView[KT]):
8+
class MyKeysView(KeysView[KT]):
99
pass
1010

1111

12-
d: dict[t.Any, t.Any] = {}
12+
d: dict[Any, Any] = {}
1313
dict_keys = type(d.keys())
1414

1515
# This should not cause an error like `Member "register" is unknown`:

stdlib/_typeshed/__init__.pyi

+3-4
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
# See the README.md file in this directory for more information.
44

55
import sys
6-
import typing_extensions
76
from collections.abc import Awaitable, Callable, Iterable, Sequence, Set as AbstractSet, Sized
87
from dataclasses import Field
98
from os import PathLike
@@ -23,7 +22,7 @@ from typing import (
2322
final,
2423
overload,
2524
)
26-
from typing_extensions import Buffer, LiteralString, TypeAlias
25+
from typing_extensions import Buffer, LiteralString, Self as _Self, TypeAlias
2726

2827
_KT = TypeVar("_KT")
2928
_KT_co = TypeVar("_KT_co", covariant=True)
@@ -329,9 +328,9 @@ class structseq(Generic[_T_co]):
329328
# The second parameter will accept a dict of any kind without raising an exception,
330329
# but only has any meaning if you supply it a dict where the keys are strings.
331330
# https://github.com/python/typeshed/pull/6560#discussion_r767149830
332-
def __new__(cls, sequence: Iterable[_T_co], dict: dict[str, Any] = ...) -> typing_extensions.Self: ...
331+
def __new__(cls, sequence: Iterable[_T_co], dict: dict[str, Any] = ...) -> _Self: ...
333332
if sys.version_info >= (3, 13):
334-
def __replace__(self, **kwargs: Any) -> typing_extensions.Self: ...
333+
def __replace__(self, **kwargs: Any) -> _Self: ...
335334

336335
# Superset of typing.AnyStr that also includes LiteralString
337336
AnyOrLiteralStr = TypeVar("AnyOrLiteralStr", str, bytes, LiteralString) # noqa: Y001

stdlib/typing_extensions.pyi

+5-5
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import abc
22
import enum
33
import sys
4-
import typing
54
from _collections_abc import dict_items, dict_keys, dict_values
65
from _typeshed import IdentityFunction, Incomplete, Unused
76
from collections.abc import (
@@ -57,6 +56,7 @@ from typing import ( # noqa: Y022,Y037,Y038,Y039,UP035
5756
Tuple as Tuple,
5857
Type as Type,
5958
TypedDict as TypedDict,
59+
TypeVar as _TypeVar,
6060
Union as Union,
6161
_Alias,
6262
cast as cast,
@@ -195,10 +195,10 @@ __all__ = [
195195
"CapsuleType",
196196
]
197197

198-
_T = typing.TypeVar("_T")
199-
_F = typing.TypeVar("_F", bound=Callable[..., Any])
200-
_TC = typing.TypeVar("_TC", bound=type[object])
201-
_T_co = typing.TypeVar("_T_co", covariant=True) # Any type covariant containers.
198+
_T = _TypeVar("_T")
199+
_F = _TypeVar("_F", bound=Callable[..., Any])
200+
_TC = _TypeVar("_TC", bound=type[object])
201+
_T_co = _TypeVar("_T_co", covariant=True) # Any type covariant containers.
202202

203203
class _Final: ... # This should be imported from typing but that breaks pytype
204204

stubs/click-default-group/click_default_group.pyi

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import typing as t
21
from _typeshed import Incomplete
2+
from collections.abc import Sequence
33

44
import click
55

@@ -23,7 +23,7 @@ class DefaultCommandFormatter:
2323
formatter: click.HelpFormatter
2424
mark: str
2525
def __init__(self, group: click.Group, formatter: click.HelpFormatter, mark: str = ...) -> None: ...
26-
def write_dl(self, rows: t.Sequence[tuple[str, str]], col_max: int = 30, col_spacing: int = -2) -> None: ...
26+
def write_dl(self, rows: Sequence[tuple[str, str]], col_max: int = 30, col_spacing: int = -2) -> None: ...
2727
def __getattr__(self, attr: str) -> Incomplete: ...
2828
# __getattr__ used to ala-derive from click.HelpFormatter:
2929
# indent_increment: int

stubs/click-log/click_log/options.pyi

+5-6
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
import logging
2-
import typing as t
2+
from collections.abc import Callable
3+
from typing import Any, TypeVar
34
from typing_extensions import TypeAlias
45

56
import click
67

7-
_AnyCallable: TypeAlias = t.Callable[..., t.Any]
8-
_FC = t.TypeVar("_FC", bound=_AnyCallable | click.Command)
8+
_AnyCallable: TypeAlias = Callable[..., Any]
9+
_FC = TypeVar("_FC", bound=_AnyCallable | click.Command)
910

10-
def simple_verbosity_option(
11-
logger: logging.Logger | str | None = None, *names: str, **kwargs: t.Any
12-
) -> t.Callable[[_FC], _FC]: ...
11+
def simple_verbosity_option(logger: logging.Logger | str | None = None, *names: str, **kwargs: Any) -> Callable[[_FC], _FC]: ...

stubs/click-web/click_web/web_click_types.pyi

+6-4
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,19 @@
11
import re
2-
from typing import ClassVar
2+
from typing import ClassVar, TypeVar
33

44
import click
55

6+
_T = TypeVar("_T")
7+
68
class EmailParamType(click.ParamType):
79
EMAIL_REGEX: ClassVar[re.Pattern[str]]
8-
def convert(self, value: str, param: click.Parameter | None, ctx: click.Context | None) -> str | None: ...
10+
def convert(self, value: str, param: click.Parameter | None, ctx: click.Context | None) -> str: ...
911

1012
class PasswordParamType(click.ParamType):
11-
def convert(self, value: str, param: click.Parameter | None, ctx: click.Context | None) -> str | None: ...
13+
def convert(self, value: _T, param: click.Parameter | None, ctx: click.Context | None) -> _T: ...
1214

1315
class TextAreaParamType(click.ParamType):
14-
def convert(self, value: str, param: click.Parameter | None, ctx: click.Context | None) -> str | None: ...
16+
def convert(self, value: _T, param: click.Parameter | None, ctx: click.Context | None) -> _T: ...
1517

1618
EMAIL_TYPE: EmailParamType
1719
PASSWORD_TYPE: PasswordParamType

stubs/corus/corus/third/WikiExtractor.pyi

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import typing
21
from _typeshed import Incomplete
32
from collections.abc import Generator
43
from math import (
@@ -14,6 +13,7 @@ from math import (
1413
tan as tan,
1514
trunc as trunc,
1615
)
16+
from typing import TypeVar
1717

1818
PY2: Incomplete
1919
text_type = str
@@ -52,7 +52,7 @@ quote_quote: Incomplete
5252
spaces: Incomplete
5353
dots: Incomplete
5454

55-
_T = typing.TypeVar("_T")
55+
_T = TypeVar("_T")
5656

5757
class Template(list[_T]):
5858
@classmethod

0 commit comments

Comments
 (0)