diff --git a/.flake8 b/.flake8 index 3d2d0193a83a..3a65b6b2c583 100644 --- a/.flake8 +++ b/.flake8 @@ -18,20 +18,15 @@ # F403 import *' used; unable to detect undefined names # F405 defined from star imports -# Rules that we'd like to enable in the future: -# Y037 Use PEP 604 syntax instead of `typing.Union` and `typing.Optional`. -# Currently can't be enabled due to a few lingering bugs in mypy regarding -# PEP 604 type aliases (see #4819). - [flake8] per-file-ignores = *.py: E203, E301, E302, E305, E501 - *.pyi: B, E301, E302, E305, E501, E701, E741, F401, F403, F405, F822, Y037 + *.pyi: B, E301, E302, E305, E501, E701, E741, F401, F403, F405, F822 # Since typing.pyi defines "overload" this is not recognized by flake8 as typing.overload. # Unfortunately, flake8 does not allow to "noqa" just a specific error inside the file itself. # https://github.com/PyCQA/flake8/issues/1079 # F811 redefinition of unused '...' - stdlib/typing.pyi: B, E301, E302, E305, E501, E701, E741, F401, F403, F405, F811, F822, Y037 + stdlib/typing.pyi: B, E301, E302, E305, E501, E701, E741, F401, F403, F405, F811, F822 # Generated protobuf files include docstrings *_pb2.pyi: B, E301, E302, E305, E501, E701, Y021, Y026 diff --git a/stdlib/_csv.pyi b/stdlib/_csv.pyi index 7d15365d3b02..c3f1dd58cd3c 100644 --- a/stdlib/_csv.pyi +++ b/stdlib/_csv.pyi @@ -1,6 +1,6 @@ from _typeshed import SupportsWrite from collections.abc import Iterable, Iterator -from typing import Any, Union +from typing import Any from typing_extensions import Literal, TypeAlias __version__: str @@ -27,7 +27,7 @@ class Dialect: strict: bool def __init__(self) -> None: ... -_DialectLike: TypeAlias = Union[str, Dialect, type[Dialect]] +_DialectLike: TypeAlias = str | Dialect | type[Dialect] class _reader(Iterator[list[str]]): @property diff --git a/stdlib/_decimal.pyi b/stdlib/_decimal.pyi index 38b8ac30cc2f..5924c36a37ff 100644 --- a/stdlib/_decimal.pyi +++ b/stdlib/_decimal.pyi @@ -3,11 +3,11 @@ import sys from _typeshed import Self from collections.abc import Container, Sequence from types import TracebackType -from typing import Any, ClassVar, NamedTuple, Union, overload +from typing import Any, ClassVar, NamedTuple, overload from typing_extensions import Literal, TypeAlias _Decimal: TypeAlias = Decimal | int -_DecimalNew: TypeAlias = Union[Decimal, float, str, tuple[int, Sequence[int], int]] +_DecimalNew: TypeAlias = Decimal | float | str | tuple[int, Sequence[int], int] _ComparableNum: TypeAlias = Decimal | float | numbers.Rational __version__: str diff --git a/stdlib/_typeshed/__init__.pyi b/stdlib/_typeshed/__init__.pyi index 33af534311d1..d0c6b3ab1173 100644 --- a/stdlib/_typeshed/__init__.pyi +++ b/stdlib/_typeshed/__init__.pyi @@ -11,7 +11,7 @@ from collections.abc import Awaitable, Callable, Iterable, Set as AbstractSet from dataclasses import Field from os import PathLike from types import FrameType, TracebackType -from typing import Any, AnyStr, ClassVar, Generic, Protocol, TypeVar, Union +from typing import Any, AnyStr, ClassVar, Generic, Protocol, TypeVar from typing_extensions import Final, Literal, LiteralString, TypeAlias, final _KT = TypeVar("_KT") @@ -265,7 +265,7 @@ IndexableBuffer: TypeAlias = bytes | bytearray | memoryview | array.array[Any] | # def __buffer__(self, __flags: int) -> memoryview: ... ExcInfo: TypeAlias = tuple[type[BaseException], BaseException, TracebackType] -OptExcInfo: TypeAlias = Union[ExcInfo, tuple[None, None, None]] +OptExcInfo: TypeAlias = ExcInfo | tuple[None, None, None] # stable if sys.version_info >= (3, 10): diff --git a/stdlib/copyreg.pyi b/stdlib/copyreg.pyi index 07338b422385..8f7fd957fc52 100644 --- a/stdlib/copyreg.pyi +++ b/stdlib/copyreg.pyi @@ -1,9 +1,9 @@ from collections.abc import Callable, Hashable -from typing import Any, SupportsInt, TypeVar, Union +from typing import Any, SupportsInt, TypeVar from typing_extensions import TypeAlias _T = TypeVar("_T") -_Reduce: TypeAlias = Union[tuple[Callable[..., _T], tuple[Any, ...]], tuple[Callable[..., _T], tuple[Any, ...], Any | None]] +_Reduce: TypeAlias = tuple[Callable[..., _T], tuple[Any, ...]] | tuple[Callable[..., _T], tuple[Any, ...], Any | None] __all__ = ["pickle", "constructor", "add_extension", "remove_extension", "clear_extension_cache"] diff --git a/stdlib/ctypes/__init__.pyi b/stdlib/ctypes/__init__.pyi index cd31a36a354d..87ae2513e1e7 100644 --- a/stdlib/ctypes/__init__.pyi +++ b/stdlib/ctypes/__init__.pyi @@ -3,7 +3,7 @@ from _ctypes import RTLD_GLOBAL as RTLD_GLOBAL, RTLD_LOCAL as RTLD_LOCAL from _typeshed import ReadableBuffer, Self, WriteableBuffer from abc import abstractmethod from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence -from typing import Any, ClassVar, Generic, TypeVar, Union as _UnionT, overload +from typing import Any, ClassVar, Generic, TypeVar, overload from typing_extensions import TypeAlias if sys.version_info >= (3, 9): @@ -91,7 +91,7 @@ class _CanCastTo(_CData): ... class _PointerLike(_CanCastTo): ... _ECT: TypeAlias = Callable[[type[_CData] | None, _FuncPointer, tuple[_CData, ...]], _CData] -_PF: TypeAlias = _UnionT[tuple[int], tuple[int, str], tuple[int, str, Any]] +_PF: TypeAlias = tuple[int] | tuple[int, str] | tuple[int, str, Any] class _FuncPointer(_PointerLike, _CData): restype: type[_CData] | Callable[[int], Any] | None diff --git a/stdlib/distutils/ccompiler.pyi b/stdlib/distutils/ccompiler.pyi index 711b30ba4e0e..e7277aa3f9c4 100644 --- a/stdlib/distutils/ccompiler.pyi +++ b/stdlib/distutils/ccompiler.pyi @@ -1,8 +1,8 @@ from collections.abc import Callable -from typing import Any, Union +from typing import Any from typing_extensions import TypeAlias -_Macro: TypeAlias = Union[tuple[str], tuple[str, str | None]] +_Macro: TypeAlias = tuple[str] | tuple[str, str | None] def gen_lib_options( compiler: CCompiler, library_dirs: list[str], runtime_library_dirs: list[str], libraries: list[str] diff --git a/stdlib/email/__init__.pyi b/stdlib/email/__init__.pyi index 6b59dc73d5cc..fca302f5f1a7 100644 --- a/stdlib/email/__init__.pyi +++ b/stdlib/email/__init__.pyi @@ -1,12 +1,12 @@ from collections.abc import Callable from email.message import Message from email.policy import Policy -from typing import IO, Union +from typing import IO from typing_extensions import TypeAlias # Definitions imported by multiple submodules in typeshed -_ParamType: TypeAlias = Union[str, tuple[str | None, str | None, str]] # noqa: Y047 -_ParamsType: TypeAlias = Union[str, None, tuple[str, str | None, str]] # noqa: Y047 +_ParamType: TypeAlias = str | tuple[str | None, str | None, str] # noqa: Y047 +_ParamsType: TypeAlias = str | None | tuple[str, str | None, str] # noqa: Y047 def message_from_string(s: str, _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> Message: ... def message_from_bytes(s: bytes | bytearray, _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> Message: ... diff --git a/stdlib/inspect.pyi b/stdlib/inspect.pyi index 3b82e0b0af2a..5fa806bca988 100644 --- a/stdlib/inspect.pyi +++ b/stdlib/inspect.pyi @@ -25,7 +25,7 @@ from types import ( TracebackType, WrapperDescriptorType, ) -from typing import Any, ClassVar, NamedTuple, Protocol, TypeVar, Union, overload +from typing import Any, ClassVar, NamedTuple, Protocol, TypeVar, overload from typing_extensions import Literal, ParamSpec, TypeAlias, TypeGuard if sys.version_info >= (3, 11): @@ -264,9 +264,9 @@ def isdatadescriptor(object: object) -> TypeGuard[_SupportsSet[Any, Any] | _Supp # # Retrieving source code # -_SourceObjectType: TypeAlias = Union[ - ModuleType, type[Any], MethodType, FunctionType, TracebackType, FrameType, CodeType, Callable[..., Any] -] +_SourceObjectType: TypeAlias = ( + ModuleType | type[Any] | MethodType | FunctionType | TracebackType | FrameType | CodeType | Callable[..., Any] +) def findsource(object: _SourceObjectType) -> tuple[list[str], int]: ... def getabsfile(object: _SourceObjectType, _filename: str | None = None) -> str: ... diff --git a/stdlib/logging/__init__.pyi b/stdlib/logging/__init__.pyi index 231700653a32..b68eb201df40 100644 --- a/stdlib/logging/__init__.pyi +++ b/stdlib/logging/__init__.pyi @@ -7,7 +7,7 @@ from re import Pattern from string import Template from time import struct_time from types import FrameType, TracebackType -from typing import Any, ClassVar, Generic, TextIO, TypeVar, Union, overload +from typing import Any, ClassVar, Generic, TextIO, TypeVar, overload from typing_extensions import Literal, TypeAlias if sys.version_info >= (3, 11): @@ -61,7 +61,7 @@ __all__ = [ if sys.version_info >= (3, 11): __all__ += ["getLevelNamesMapping"] -_SysExcInfoType: TypeAlias = Union[tuple[type[BaseException], BaseException, TracebackType | None], tuple[None, None, None]] +_SysExcInfoType: TypeAlias = tuple[type[BaseException], BaseException, TracebackType | None] | tuple[None, None, None] _ExcInfoType: TypeAlias = None | bool | _SysExcInfoType | BaseException _ArgsType: TypeAlias = tuple[object, ...] | Mapping[str, object] _FilterType: TypeAlias = Filter | Callable[[LogRecord], bool] diff --git a/stdlib/marshal.pyi b/stdlib/marshal.pyi index da5d1a95a6f6..21f05c908479 100644 --- a/stdlib/marshal.pyi +++ b/stdlib/marshal.pyi @@ -1,31 +1,31 @@ import builtins import types from _typeshed import ReadableBuffer, SupportsRead, SupportsWrite -from typing import Any, Union +from typing import Any from typing_extensions import TypeAlias version: int -_Marshallable: TypeAlias = Union[ +_Marshallable: TypeAlias = ( # handled in w_object() in marshal.c - None, - type[StopIteration], - builtins.ellipsis, - bool, + None + | type[StopIteration] + | builtins.ellipsis + | bool # handled in w_complex_object() in marshal.c - int, - float, - complex, - bytes, - str, - tuple[_Marshallable, ...], - list[Any], - dict[Any, Any], - set[Any], - frozenset[_Marshallable], - types.CodeType, - ReadableBuffer, -] + | int + | float + | complex + | bytes + | str + | tuple[_Marshallable, ...] + | list[Any] + | dict[Any, Any] + | set[Any] + | frozenset[_Marshallable] + | types.CodeType + | ReadableBuffer +) def dump(__value: _Marshallable, __file: SupportsWrite[bytes], __version: int = 4) -> None: ... def load(__file: SupportsRead[bytes]) -> Any: ... diff --git a/stdlib/multiprocessing/connection.pyi b/stdlib/multiprocessing/connection.pyi index 392e3168aaaa..868921f8b1d2 100644 --- a/stdlib/multiprocessing/connection.pyi +++ b/stdlib/multiprocessing/connection.pyi @@ -3,13 +3,13 @@ import sys import types from _typeshed import ReadableBuffer, Self from collections.abc import Iterable -from typing import Any, Union +from typing import Any from typing_extensions import SupportsIndex, TypeAlias __all__ = ["Client", "Listener", "Pipe", "wait"] # https://docs.python.org/3/library/multiprocessing.html#address-formats -_Address: TypeAlias = Union[str, tuple[str, int]] +_Address: TypeAlias = str | tuple[str, int] class _ConnectionBase: def __init__(self, handle: SupportsIndex, readable: bool = True, writable: bool = True) -> None: ... diff --git a/stdlib/multiprocessing/dummy/connection.pyi b/stdlib/multiprocessing/dummy/connection.pyi index 1630472b3b06..82a9027141fa 100644 --- a/stdlib/multiprocessing/dummy/connection.pyi +++ b/stdlib/multiprocessing/dummy/connection.pyi @@ -1,14 +1,14 @@ from _typeshed import Self from queue import Queue from types import TracebackType -from typing import Any, Union +from typing import Any from typing_extensions import TypeAlias __all__ = ["Client", "Listener", "Pipe"] families: list[None] -_Address: TypeAlias = Union[str, tuple[str, int]] +_Address: TypeAlias = str | tuple[str, int] class Connection: _in: Any diff --git a/stdlib/pickle.pyi b/stdlib/pickle.pyi index dc098cae97b7..57c4cb03e484 100644 --- a/stdlib/pickle.pyi +++ b/stdlib/pickle.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import ReadableBuffer, SupportsWrite from collections.abc import Callable, Iterable, Iterator, Mapping -from typing import Any, ClassVar, Protocol, SupportsBytes, Union +from typing import Any, ClassVar, Protocol, SupportsBytes from typing_extensions import SupportsIndex, TypeAlias, final __all__ = [ @@ -142,13 +142,13 @@ class PickleError(Exception): ... class PicklingError(PickleError): ... class UnpicklingError(PickleError): ... -_ReducedType: TypeAlias = Union[ - str, - tuple[Callable[..., Any], tuple[Any, ...]], - tuple[Callable[..., Any], tuple[Any, ...], Any], - tuple[Callable[..., Any], tuple[Any, ...], Any, Iterator[Any] | None], - tuple[Callable[..., Any], tuple[Any, ...], Any, Iterator[Any] | None, Iterator[Any] | None], -] +_ReducedType: TypeAlias = ( + str + | tuple[Callable[..., Any], tuple[Any, ...]] + | tuple[Callable[..., Any], tuple[Any, ...], Any] + | tuple[Callable[..., Any], tuple[Any, ...], Any, Iterator[Any] | None] + | tuple[Callable[..., Any], tuple[Any, ...], Any, Iterator[Any] | None, Iterator[Any] | None] +) class Pickler: fast: bool diff --git a/stdlib/signal.pyi b/stdlib/signal.pyi index d1bd6930626c..29481119ba73 100644 --- a/stdlib/signal.pyi +++ b/stdlib/signal.pyi @@ -3,7 +3,7 @@ from _typeshed import structseq from collections.abc import Callable, Iterable from enum import IntEnum from types import FrameType -from typing import Any, Union +from typing import Any from typing_extensions import Final, Never, TypeAlias, final NSIG: int @@ -62,7 +62,7 @@ SIG_DFL: Handlers SIG_IGN: Handlers _SIGNUM: TypeAlias = int | Signals -_HANDLER: TypeAlias = Union[Callable[[int, FrameType | None], Any], int, Handlers, None] +_HANDLER: TypeAlias = Callable[[int, FrameType | None], Any] | int | Handlers | None def default_int_handler(__signalnum: int, __frame: FrameType | None) -> Never: ... diff --git a/stdlib/socketserver.pyi b/stdlib/socketserver.pyi index b35f1553fb44..c74312cea6e6 100644 --- a/stdlib/socketserver.pyi +++ b/stdlib/socketserver.pyi @@ -4,7 +4,7 @@ from _socket import _Address, _RetAddress from _typeshed import ReadableBuffer, Self from collections.abc import Callable from socket import socket as _socket -from typing import Any, BinaryIO, ClassVar, Union +from typing import Any, BinaryIO, ClassVar from typing_extensions import TypeAlias __all__ = [ @@ -29,7 +29,7 @@ if sys.platform != "win32": "UnixStreamServer", ] -_RequestType: TypeAlias = Union[_socket, tuple[bytes, _socket]] +_RequestType: TypeAlias = _socket | tuple[bytes, _socket] _AfUnixAddress: TypeAlias = str | ReadableBuffer # adddress acceptable for an AF_UNIX socket _AfInetAddress: TypeAlias = tuple[str | bytes | bytearray, int] # address acceptable for an AF_INET socket diff --git a/stdlib/ssl.pyi b/stdlib/ssl.pyi index f8b97fb60eb7..73df70c00d3c 100644 --- a/stdlib/ssl.pyi +++ b/stdlib/ssl.pyi @@ -3,7 +3,7 @@ import socket import sys from _typeshed import ReadableBuffer, Self, StrOrBytesPath, WriteableBuffer from collections.abc import Callable, Iterable -from typing import Any, NamedTuple, Union, overload +from typing import Any, NamedTuple, overload from typing_extensions import Literal, TypeAlias, TypedDict, final _PCTRTT: TypeAlias = tuple[tuple[str, str], ...] @@ -11,7 +11,7 @@ _PCTRTTT: TypeAlias = tuple[_PCTRTT, ...] _PeerCertRetDictType: TypeAlias = dict[str, str | _PCTRTTT | _PCTRTT] _PeerCertRetType: TypeAlias = _PeerCertRetDictType | bytes | None _EnumRetType: TypeAlias = list[tuple[bytes, str, set[str] | bool]] -_PasswordType: TypeAlias = Union[Callable[[], str | bytes | bytearray], str, bytes, bytearray] +_PasswordType: TypeAlias = Callable[[], str | bytes | bytearray] | str | bytes | bytearray _SrvnmeCbType: TypeAlias = Callable[[SSLSocket | SSLObject, str | None, SSLSocket], int | None] diff --git a/stdlib/tkinter/__init__.pyi b/stdlib/tkinter/__init__.pyi index 4aab7da1a690..1d30e4b73c23 100644 --- a/stdlib/tkinter/__init__.pyi +++ b/stdlib/tkinter/__init__.pyi @@ -6,7 +6,7 @@ from enum import Enum from tkinter.constants import * from tkinter.font import _FontDescription from types import TracebackType -from typing import Any, Generic, NamedTuple, Protocol, TypeVar, Union, overload +from typing import Any, Generic, NamedTuple, Protocol, TypeVar, overload from typing_extensions import Literal, TypeAlias, TypedDict if sys.version_info >= (3, 9): @@ -179,7 +179,7 @@ _CanvasItemId: TypeAlias = int _Color: TypeAlias = str # typically '#rrggbb', '#rgb' or color names. _Compound: TypeAlias = Literal["top", "left", "center", "right", "bottom", "none"] # -compound in manual page named 'options' # manual page: Tk_GetCursor -_Cursor: TypeAlias = Union[str, tuple[str], tuple[str, str], tuple[str, str, str], tuple[str, str, str, str]] +_Cursor: TypeAlias = str | tuple[str] | tuple[str, str] | tuple[str, str, str] | tuple[str, str, str, str] # example when it's sequence: entry['invalidcommand'] = [entry.register(print), '%P'] _EntryValidateCommand: TypeAlias = str | list[str] | tuple[str, ...] | Callable[[], bool] _GridIndex: TypeAlias = int | str @@ -188,7 +188,7 @@ _Relief: TypeAlias = Literal["raised", "sunken", "flat", "ridge", "solid", "groo _ScreenUnits: TypeAlias = str | float # Often the right type instead of int. Manual page: Tk_GetPixels # -xscrollcommand and -yscrollcommand in 'options' manual page _XYScrollCommand: TypeAlias = str | Callable[[float, float], object] -_TakeFocusValue: TypeAlias = Union[int, Literal[""], Callable[[str], bool | None]] # -takefocus in manual page named 'options' +_TakeFocusValue: TypeAlias = int | Literal[""] | Callable[[str], bool | None] # -takefocus in manual page named 'options' if sys.version_info >= (3, 11): class _VersionInfoType(NamedTuple): diff --git a/stdlib/tkinter/ttk.pyi b/stdlib/tkinter/ttk.pyi index bd477535f41f..61ebc0e2734f 100644 --- a/stdlib/tkinter/ttk.pyi +++ b/stdlib/tkinter/ttk.pyi @@ -4,7 +4,7 @@ import tkinter from _typeshed import Incomplete from collections.abc import Callable from tkinter.font import _FontDescription -from typing import Any, Union, overload +from typing import Any, overload from typing_extensions import Literal, TypeAlias, TypedDict __all__ = [ @@ -38,13 +38,13 @@ __all__ = [ def tclobjs_to_py(adict: dict[Any, Any]) -> dict[Any, Any]: ... def setup_master(master: Incomplete | None = None): ... -_Padding: TypeAlias = Union[ - tkinter._ScreenUnits, - tuple[tkinter._ScreenUnits], - tuple[tkinter._ScreenUnits, tkinter._ScreenUnits], - tuple[tkinter._ScreenUnits, tkinter._ScreenUnits, tkinter._ScreenUnits], - tuple[tkinter._ScreenUnits, tkinter._ScreenUnits, tkinter._ScreenUnits, tkinter._ScreenUnits], -] +_Padding: TypeAlias = ( + tkinter._ScreenUnits + | tuple[tkinter._ScreenUnits] + | tuple[tkinter._ScreenUnits, tkinter._ScreenUnits] + | tuple[tkinter._ScreenUnits, tkinter._ScreenUnits, tkinter._ScreenUnits] + | tuple[tkinter._ScreenUnits, tkinter._ScreenUnits, tkinter._ScreenUnits, tkinter._ScreenUnits] +) # from ttk_widget (aka ttk::widget) manual page, differs from tkinter._Compound _TtkCompound: TypeAlias = Literal["text", "image", tkinter._Compound] diff --git a/stdlib/tracemalloc.pyi b/stdlib/tracemalloc.pyi index d7214de285f8..3dc8b8603fe5 100644 --- a/stdlib/tracemalloc.pyi +++ b/stdlib/tracemalloc.pyi @@ -1,7 +1,7 @@ import sys from _tracemalloc import * from collections.abc import Sequence -from typing import Any, Union, overload +from typing import Any, overload from typing_extensions import SupportsIndex, TypeAlias def get_object_traceback(obj: object) -> Traceback | None: ... @@ -67,7 +67,7 @@ class Frame: def __le__(self, other: Frame, NotImplemented: Any = ...) -> bool: ... if sys.version_info >= (3, 9): - _TraceTuple: TypeAlias = Union[tuple[int, int, Sequence[_FrameTuple], int | None], tuple[int, int, Sequence[_FrameTuple]]] + _TraceTuple: TypeAlias = tuple[int, int, Sequence[_FrameTuple], int | None] | tuple[int, int, Sequence[_FrameTuple]] else: _TraceTuple: TypeAlias = tuple[int, int, Sequence[_FrameTuple]] diff --git a/stdlib/turtle.pyi b/stdlib/turtle.pyi index 1259ca6fb4cc..2187d13b1a13 100644 --- a/stdlib/turtle.pyi +++ b/stdlib/turtle.pyi @@ -1,7 +1,7 @@ from _typeshed import Self from collections.abc import Callable, Sequence from tkinter import Canvas, Frame, Misc, PhotoImage, Scrollbar -from typing import Any, ClassVar, Union, overload +from typing import Any, ClassVar, overload from typing_extensions import TypeAlias __all__ = [ @@ -133,7 +133,7 @@ __all__ = [ # alias we use for return types. Really, these two aliases should be the # same, but as per the "no union returns" typeshed policy, we'll return # Any instead. -_Color: TypeAlias = Union[str, tuple[float, float, float]] +_Color: TypeAlias = str | tuple[float, float, float] _AnyColor: TypeAlias = Any # TODO: Replace this with a TypedDict once it becomes standardized. diff --git a/stdlib/unittest/case.pyi b/stdlib/unittest/case.pyi index 5b1bd9288659..630267a7ce07 100644 --- a/stdlib/unittest/case.pyi +++ b/stdlib/unittest/case.pyi @@ -6,20 +6,7 @@ from collections.abc import Callable, Container, Iterable, Mapping, Sequence, Se from contextlib import AbstractContextManager from re import Pattern from types import TracebackType -from typing import ( - Any, - AnyStr, - ClassVar, - Generic, - NamedTuple, - NoReturn, - Protocol, - SupportsAbs, - SupportsRound, - TypeVar, - Union, - overload, -) +from typing import Any, AnyStr, ClassVar, Generic, NamedTuple, NoReturn, Protocol, SupportsAbs, SupportsRound, TypeVar, overload from typing_extensions import ParamSpec, TypeAlias from warnings import WarningMessage @@ -82,9 +69,9 @@ class SkipTest(Exception): class _SupportsAbsAndDunderGE(SupportsDunderGE[Any], SupportsAbs[Any], Protocol): ... if sys.version_info >= (3, 10): - _IsInstanceClassInfo: TypeAlias = Union[type, UnionType, tuple[type | UnionType | tuple[Any, ...], ...]] + _IsInstanceClassInfo: TypeAlias = type | UnionType | tuple[type | UnionType | tuple[Any, ...], ...] else: - _IsInstanceClassInfo: TypeAlias = Union[type, tuple[type | tuple[Any, ...], ...]] + _IsInstanceClassInfo: TypeAlias = type | tuple[type | tuple[Any, ...], ...] class TestCase: failureException: type[BaseException] diff --git a/stdlib/xmlrpc/client.pyi b/stdlib/xmlrpc/client.pyi index 536cd6382d0b..86d21abd7725 100644 --- a/stdlib/xmlrpc/client.pyi +++ b/stdlib/xmlrpc/client.pyi @@ -7,7 +7,7 @@ from collections.abc import Callable, Iterable, Mapping from datetime import datetime from io import BytesIO from types import TracebackType -from typing import Any, Protocol, Union, overload +from typing import Any, Protocol, overload from typing_extensions import Literal, TypeAlias class _SupportsTimeTuple(Protocol): @@ -31,7 +31,7 @@ _Marshallable: TypeAlias = ( | Binary ) _XMLDate: TypeAlias = int | datetime | tuple[int, ...] | time.struct_time -_HostType: TypeAlias = Union[tuple[str, dict[str, str]], str] +_HostType: TypeAlias = tuple[str, dict[str, str]] | str def escape(s: str) -> str: ... # undocumented diff --git a/stubs/Pillow/PIL/Image.pyi b/stubs/Pillow/PIL/Image.pyi index c5655f0e37be..c2be2dcd23cd 100644 --- a/stubs/Pillow/PIL/Image.pyi +++ b/stubs/Pillow/PIL/Image.pyi @@ -2,7 +2,7 @@ from _typeshed import Incomplete, Self, SupportsRead, SupportsWrite from collections.abc import Callable, Iterable, Iterator, MutableMapping, Sequence from enum import IntEnum from pathlib import Path -from typing import Any, ClassVar, Protocol, SupportsBytes, Union +from typing import Any, ClassVar, Protocol, SupportsBytes from typing_extensions import Literal, TypeAlias from PIL.PyAccess import PyAccess @@ -22,13 +22,13 @@ _Resample: TypeAlias = Literal[0, 1, 2, 3, 4, 5] _Size: TypeAlias = tuple[int, int] _Box: TypeAlias = tuple[int, int, int, int] -_ConversionMatrix: TypeAlias = Union[ - tuple[float, float, float, float], tuple[float, float, float, float, float, float, float, float, float, float, float, float] -] +_ConversionMatrix: TypeAlias = ( + tuple[float, float, float, float] | tuple[float, float, float, float, float, float, float, float, float, float, float, float] +) # `str` values are only accepted if mode="RGB" for an `Image` object # `float` values are only accepted for certain modes such as "F" # See https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.new -_Color: TypeAlias = Union[int, tuple[int], tuple[int, int, int], tuple[int, int, int, int], str, float, tuple[float]] +_Color: TypeAlias = int | tuple[int] | tuple[int, int, int] | tuple[int, int, int, int] | str | float | tuple[float] class _Writeable(SupportsWrite[bytes], Protocol): def seek(self, __offset: int) -> Any: ... diff --git a/stubs/Pillow/PIL/ImageColor.pyi b/stubs/Pillow/PIL/ImageColor.pyi index 1815d7004f50..62fba216bb57 100644 --- a/stubs/Pillow/PIL/ImageColor.pyi +++ b/stubs/Pillow/PIL/ImageColor.pyi @@ -1,7 +1,6 @@ -from typing import Union from typing_extensions import TypeAlias -_RGB: TypeAlias = Union[tuple[int, int, int], tuple[int, int, int, int]] +_RGB: TypeAlias = tuple[int, int, int] | tuple[int, int, int, int] _Ink: TypeAlias = str | int | _RGB _GreyScale: TypeAlias = tuple[int, int] diff --git a/stubs/Pillow/PIL/ImageOps.pyi b/stubs/Pillow/PIL/ImageOps.pyi index aa082e5f8b9f..9cc148018e8f 100644 --- a/stubs/Pillow/PIL/ImageOps.pyi +++ b/stubs/Pillow/PIL/ImageOps.pyi @@ -1,12 +1,12 @@ from _typeshed import Incomplete from collections.abc import Iterable -from typing import Protocol, Union +from typing import Protocol from typing_extensions import TypeAlias from .Image import Image, Resampling, _Resample, _Size from .ImageColor import _Ink -_Border: TypeAlias = Union[int, tuple[int, int], tuple[int, int, int, int]] +_Border: TypeAlias = int | tuple[int, int] | tuple[int, int, int, int] class _Deformer(Protocol): def getmesh(self, image: Image): ... diff --git a/stubs/Pillow/PIL/TiffTags.pyi b/stubs/Pillow/PIL/TiffTags.pyi index 4bef226ae4ef..f546f604b81b 100644 --- a/stubs/Pillow/PIL/TiffTags.pyi +++ b/stubs/Pillow/PIL/TiffTags.pyi @@ -1,5 +1,5 @@ from _typeshed import Incomplete -from typing import Any, NamedTuple, Union +from typing import Any, NamedTuple from typing_extensions import Literal, TypeAlias class _TagInfo(NamedTuple): @@ -37,7 +37,7 @@ DOUBLE: Literal[12] IFD: Literal[13] _TagType: TypeAlias = Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] -_TagTuple: TypeAlias = Union[tuple[str, _TagType, int], tuple[str, _TagInfo, int, dict[str, int]]] +_TagTuple: TypeAlias = tuple[str, _TagType, int] | tuple[str, _TagInfo, int, dict[str, int]] TAGS_V2: dict[int, _TagTuple] TAGS_V2_GROUPS: dict[int, dict[int, _TagTuple]] diff --git a/stubs/jsonschema/jsonschema/_format.pyi b/stubs/jsonschema/jsonschema/_format.pyi index 2f3df1bd77e8..9c2b12ef186e 100644 --- a/stubs/jsonschema/jsonschema/_format.pyi +++ b/stubs/jsonschema/jsonschema/_format.pyi @@ -1,10 +1,10 @@ from collections.abc import Callable, Iterable -from typing import TypeVar, Union +from typing import TypeVar from typing_extensions import TypeAlias _FormatCheckCallable: TypeAlias = Callable[[object], bool] _F = TypeVar("_F", bound=_FormatCheckCallable) -_RaisesType: TypeAlias = Union[type[Exception], tuple[type[Exception], ...]] +_RaisesType: TypeAlias = type[Exception] | tuple[type[Exception], ...] class FormatChecker: checkers: dict[str, tuple[_FormatCheckCallable, _RaisesType]] diff --git a/stubs/keyboard/keyboard/__init__.pyi b/stubs/keyboard/keyboard/__init__.pyi index bfc19bc051c4..d65c0c508f33 100644 --- a/stubs/keyboard/keyboard/__init__.pyi +++ b/stubs/keyboard/keyboard/__init__.pyi @@ -1,7 +1,6 @@ from collections.abc import Callable, Generator, Iterable, Sequence from queue import Queue from threading import Event as _UninterruptibleEvent -from typing import Optional from typing_extensions import TypeAlias from ._canonical_names import all_modifiers as all_modifiers, sided_modifiers as sided_modifiers @@ -10,7 +9,7 @@ from ._keyboard_event import KEY_DOWN as KEY_DOWN, KEY_UP as KEY_UP, KeyboardEve _Key: TypeAlias = int | str _ScanCodeList: TypeAlias = list[int] | tuple[int, ...] _ParseableHotkey: TypeAlias = _Key | list[int | _ScanCodeList] | tuple[int | _ScanCodeList, ...] -_Callback: TypeAlias = Callable[[KeyboardEvent], Optional[bool]] | Callable[[], Optional[bool]] +_Callback: TypeAlias = Callable[[KeyboardEvent], bool | None] | Callable[[], bool | None] # mypy doesn't support PEP 646's TypeVarTuple yet: https://github.com/python/mypy/issues/12280 # _Ts = TypeVarTuple("_Ts") _Ts: TypeAlias = tuple[object, ...] diff --git a/stubs/netaddr/netaddr/ip/__init__.pyi b/stubs/netaddr/netaddr/ip/__init__.pyi index 7125323f190e..c05525246d8a 100644 --- a/stubs/netaddr/netaddr/ip/__init__.pyi +++ b/stubs/netaddr/netaddr/ip/__init__.pyi @@ -1,7 +1,7 @@ from _typeshed import Incomplete, Self from abc import abstractmethod from collections.abc import Iterable, Iterator -from typing import SupportsInt, Union, overload +from typing import SupportsInt, overload from typing_extensions import Literal, SupportsIndex, TypeAlias from netaddr.core import DictDotLookup @@ -38,7 +38,7 @@ class BaseIP: def version(self) -> Literal[4, 6]: ... _IPAddressAddr: TypeAlias = BaseIP | int | str -_IPNetworkAddr: TypeAlias = Union[IPNetwork, IPAddress, tuple[int, int], str] +_IPNetworkAddr: TypeAlias = IPNetwork | IPAddress | tuple[int, int] | str class IPAddress(BaseIP): def __init__(self, addr: _IPAddressAddr, version: Literal[4, 6] | None = ..., flags: int = ...) -> None: ... diff --git a/stubs/paho-mqtt/paho/mqtt/client.pyi b/stubs/paho-mqtt/paho/mqtt/client.pyi index 3a3b0f1e4bc5..a06eddcca262 100644 --- a/stubs/paho-mqtt/paho/mqtt/client.pyi +++ b/stubs/paho-mqtt/paho/mqtt/client.pyi @@ -5,7 +5,7 @@ import time import types from _typeshed import Incomplete from collections.abc import Callable -from typing import Any, Optional, TypeVar +from typing import Any, TypeVar from typing_extensions import TypeAlias from .matcher import MQTTMatcher as MQTTMatcher @@ -92,7 +92,7 @@ _Payload: TypeAlias = str | bytes | bytearray | float _ExtraHeader: TypeAlias = dict[str, str] | Callable[[dict[str, str]], dict[str, str]] _OnLog: TypeAlias = Callable[[Client, _UserData, int, str], object] _OnConnect: TypeAlias = Callable[[Client, _UserData, dict[str, int], int], object] -_OnConnectV5: TypeAlias = Callable[[Client, _UserData, dict[str, int], ReasonCodes, Optional[Properties]], object] +_OnConnectV5: TypeAlias = Callable[[Client, _UserData, dict[str, int], ReasonCodes, Properties | None], object] _TOnConnect = TypeVar("_TOnConnect", _OnConnect, _OnConnectV5) _OnConnectFail: TypeAlias = Callable[[Client, _UserData], object] _OnSubscribe: TypeAlias = Callable[[Client, _UserData, int, tuple[int]], object] @@ -104,7 +104,7 @@ _OnUnsubscribe: TypeAlias = Callable[[Client, _UserData, int], object] _OnUnsubscribeV5: TypeAlias = Callable[[Client, _UserData, int, Properties, list[ReasonCodes] | ReasonCodes], object] _TOnUnsubscribe = TypeVar("_TOnUnsubscribe", _OnUnsubscribe, _OnUnsubscribeV5) _OnDisconnect: TypeAlias = Callable[[Client, _UserData, int], object] -_OnDisconnectV5: TypeAlias = Callable[[Client, _UserData, Optional[ReasonCodes], Optional[Properties]], object] +_OnDisconnectV5: TypeAlias = Callable[[Client, _UserData, ReasonCodes | None, Properties | None], object] _TOnDisconnect = TypeVar("_TOnDisconnect", _OnDisconnect, _OnDisconnectV5) _OnSocket: TypeAlias = Callable[[Client, _UserData, _Socket | WebsocketWrapper | None], object] diff --git a/stubs/parsimonious/parsimonious/expressions.pyi b/stubs/parsimonious/parsimonious/expressions.pyi index fdc50b071c7d..482390b14f63 100644 --- a/stubs/parsimonious/parsimonious/expressions.pyi +++ b/stubs/parsimonious/parsimonious/expressions.pyi @@ -2,7 +2,7 @@ import collections.abc from _typeshed import Self from collections.abc import Callable, Mapping from re import Pattern -from typing import Any, Union +from typing import Any from typing_extensions import TypeAlias from parsimonious.exceptions import ParseError @@ -10,7 +10,7 @@ from parsimonious.grammar import Grammar from parsimonious.nodes import Node from parsimonious.utils import StrAndRepr -_CALLABLE_RETURN_TYPE: TypeAlias = Union[int, tuple[int, list[Node]], Node, None] +_CALLABLE_RETURN_TYPE: TypeAlias = int | tuple[int, list[Node]] | Node | None _CALLABLE_TYPE: TypeAlias = ( Callable[[str, int], _CALLABLE_RETURN_TYPE] | Callable[[str, int, Mapping[tuple[int, int], Node], ParseError, Grammar], _CALLABLE_RETURN_TYPE] diff --git a/stubs/python-xlib/Xlib/_typing.pyi b/stubs/python-xlib/Xlib/_typing.pyi index 34d5b3cd4620..f7dd1ca6ced0 100644 --- a/stubs/python-xlib/Xlib/_typing.pyi +++ b/stubs/python-xlib/Xlib/_typing.pyi @@ -1,12 +1,12 @@ from _typeshed import FileDescriptor, StrOrBytesPath from collections.abc import Callable -from typing import Optional, TypeVar +from typing import TypeVar from typing_extensions import TypeAlias from Xlib.error import XError from Xlib.protocol.rq import Request _T = TypeVar("_T") -ErrorHandler: TypeAlias = Callable[[XError, Optional[Request]], _T] +ErrorHandler: TypeAlias = Callable[[XError, Request | None], _T] Unused: TypeAlias = object OpenFile: TypeAlias = StrOrBytesPath | FileDescriptor diff --git a/stubs/python-xlib/Xlib/ext/composite.pyi b/stubs/python-xlib/Xlib/ext/composite.pyi index 96123fcf6ec9..f974c1365b7d 100644 --- a/stubs/python-xlib/Xlib/ext/composite.pyi +++ b/stubs/python-xlib/Xlib/ext/composite.pyi @@ -1,5 +1,5 @@ from collections.abc import Callable -from typing import Any, Union +from typing import Any from typing_extensions import TypeAlias from Xlib._typing import ErrorHandler, Unused @@ -7,7 +7,7 @@ from Xlib.display import Display from Xlib.protocol import rq from Xlib.xobject import drawable, resource -_Update: TypeAlias = Callable[[Union[rq.DictWrapper, dict[str, Any]]], object] +_Update: TypeAlias = Callable[[rq.DictWrapper | dict[str, Any]], object] extname: str RedirectAutomatic: int diff --git a/stubs/requests/requests/sessions.pyi b/stubs/requests/requests/sessions.pyi index d0da69ead3b0..95cb7381e986 100644 --- a/stubs/requests/requests/sessions.pyi +++ b/stubs/requests/requests/sessions.pyi @@ -1,6 +1,6 @@ from _typeshed import Incomplete, Self, SupportsItems, SupportsRead from collections.abc import Callable, Iterable, Mapping, MutableMapping -from typing import Any, Union +from typing import Any from typing_extensions import TypeAlias, TypedDict from urllib3._collections import RecentlyUsedContainer @@ -77,8 +77,8 @@ _Data: TypeAlias = ( | tuple[tuple[Any, Any], ...] | Mapping[Any, Any] ) -_Auth: TypeAlias = Union[tuple[str, str], _auth.AuthBase, Callable[[PreparedRequest], PreparedRequest]] -_Cert: TypeAlias = Union[str, tuple[str, str]] +_Auth: TypeAlias = tuple[str, str] | _auth.AuthBase | Callable[[PreparedRequest], PreparedRequest] +_Cert: TypeAlias = str | tuple[str, str] # Files is passed to requests.utils.to_key_val_list() _FileName: TypeAlias = str | None _FileContent: TypeAlias = SupportsRead[str | bytes] | str | bytes @@ -94,15 +94,16 @@ _HooksInput: TypeAlias = Mapping[str, Iterable[_Hook] | _Hook] _ParamsMappingKeyType: TypeAlias = str | bytes | int | float _ParamsMappingValueType: TypeAlias = str | bytes | int | float | Iterable[str | bytes | int | float] | None -_Params: TypeAlias = Union[ - SupportsItems[_ParamsMappingKeyType, _ParamsMappingValueType], - tuple[_ParamsMappingKeyType, _ParamsMappingValueType], - Iterable[tuple[_ParamsMappingKeyType, _ParamsMappingValueType]], - str | bytes, -] +_Params: TypeAlias = ( + SupportsItems[_ParamsMappingKeyType, _ParamsMappingValueType] + | tuple[_ParamsMappingKeyType, _ParamsMappingValueType] + | Iterable[tuple[_ParamsMappingKeyType, _ParamsMappingValueType]] + | str + | bytes +) _TextMapping: TypeAlias = MutableMapping[str, str] _HeadersUpdateMapping: TypeAlias = Mapping[str, str | bytes | None] -_Timeout: TypeAlias = Union[float, tuple[float, float], tuple[float, None]] +_Timeout: TypeAlias = float | tuple[float, float] | tuple[float, None] _Verify: TypeAlias = bool | str class _Settings(TypedDict): diff --git a/stubs/setuptools/setuptools/_distutils/ccompiler.pyi b/stubs/setuptools/setuptools/_distutils/ccompiler.pyi index 5b92c5f5c42e..96a756bb2cf8 100644 --- a/stubs/setuptools/setuptools/_distutils/ccompiler.pyi +++ b/stubs/setuptools/setuptools/_distutils/ccompiler.pyi @@ -1,8 +1,8 @@ from collections.abc import Callable -from typing import Any, Union +from typing import Any from typing_extensions import TypeAlias -_Macro: TypeAlias = Union[tuple[str], tuple[str, str | None]] +_Macro: TypeAlias = tuple[str] | tuple[str, str | None] def gen_lib_options( compiler: CCompiler, library_dirs: list[str], runtime_library_dirs: list[str], libraries: list[str] diff --git a/stubs/urllib3/urllib3/fields.pyi b/stubs/urllib3/urllib3/fields.pyi index 8127d72d6968..a7eb02554374 100644 --- a/stubs/urllib3/urllib3/fields.pyi +++ b/stubs/urllib3/urllib3/fields.pyi @@ -1,9 +1,9 @@ from collections.abc import Callable, Mapping -from typing import Any, Union +from typing import Any from typing_extensions import TypeAlias _FieldValue: TypeAlias = str | bytes -_FieldValueTuple: TypeAlias = Union[_FieldValue, tuple[str, _FieldValue], tuple[str, _FieldValue, str]] +_FieldValueTuple: TypeAlias = _FieldValue | tuple[str, _FieldValue] | tuple[str, _FieldValue, str] def guess_content_type(filename: str | None, default: str = ...) -> str: ... def format_header_param_rfc2231(name: str, value: _FieldValue) -> str: ... diff --git a/tests/check_new_syntax.py b/tests/check_new_syntax.py index 4c47557caceb..c99c0137be06 100755 --- a/tests/check_new_syntax.py +++ b/tests/check_new_syntax.py @@ -10,68 +10,6 @@ def check_new_syntax(tree: ast.AST, path: Path, stub: str) -> list[str]: errors = [] - sourcelines = stub.splitlines() - - class AnnotationUnionFinder(ast.NodeVisitor): - def visit_Subscript(self, node: ast.Subscript) -> None: - if isinstance(node.value, ast.Name): - if node.value.id == "Union" and isinstance(node.slice, ast.Tuple): - new_syntax = " | ".join(ast.unparse(x) for x in node.slice.elts) - errors.append(f"{path}:{node.lineno}: Use PEP 604 syntax for Union, e.g. `{new_syntax}`") - if node.value.id == "Optional": - new_syntax = f"{ast.unparse(node.slice)} | None" - errors.append(f"{path}:{node.lineno}: Use PEP 604 syntax for Optional, e.g. `{new_syntax}`") - - self.generic_visit(node) - - class NonAnnotationUnionFinder(ast.NodeVisitor): - def visit_Subscript(self, node: ast.Subscript) -> None: - if isinstance(node.value, ast.Name): - nodelines = sourcelines[(node.lineno - 1) : node.end_lineno] - for line in nodelines: - # A hack to workaround various PEP 604 bugs in mypy - if any(x in line for x in {"tuple[", "Callable[", "type["}): - return None - if node.value.id == "Union" and isinstance(node.slice, ast.Tuple): - new_syntax = " | ".join(ast.unparse(x) for x in node.slice.elts) - errors.append(f"{path}:{node.lineno}: Use PEP 604 syntax for Union, e.g. `{new_syntax}`") - elif node.value.id == "Optional": - new_syntax = f"{ast.unparse(node.slice)} | None" - errors.append(f"{path}:{node.lineno}: Use PEP 604 syntax for Optional, e.g. `{new_syntax}`") - - self.generic_visit(node) - - class OldSyntaxFinder(ast.NodeVisitor): - def visit_AnnAssign(self, node: ast.AnnAssign) -> None: - AnnotationUnionFinder().visit(node.annotation) - if node.value is not None: - NonAnnotationUnionFinder().visit(node.value) - self.generic_visit(node) - - def visit_arg(self, node: ast.arg) -> None: - if node.annotation is not None: - AnnotationUnionFinder().visit(node.annotation) - self.generic_visit(node) - - def _visit_function(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None: - if node.returns is not None: - AnnotationUnionFinder().visit(node.returns) - self.generic_visit(node) - - def visit_FunctionDef(self, node: ast.FunctionDef) -> None: - self._visit_function(node) - - def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None: - self._visit_function(node) - - def visit_Assign(self, node: ast.Assign) -> None: - NonAnnotationUnionFinder().visit(node.value) - self.generic_visit(node) - - def visit_ClassDef(self, node: ast.ClassDef) -> None: - for base in node.bases: - NonAnnotationUnionFinder().visit(base) - self.generic_visit(node) class IfFinder(ast.NodeVisitor): def visit_If(self, node: ast.If) -> None: @@ -88,7 +26,6 @@ def visit_If(self, node: ast.If) -> None: ) self.generic_visit(node) - OldSyntaxFinder().visit(tree) IfFinder().visit(tree) return errors