diff --git a/stdlib/_codecs.pyi b/stdlib/_codecs.pyi index a44a8a1a7c2a..6bc3951188ba 100644 --- a/stdlib/_codecs.pyi +++ b/stdlib/_codecs.pyi @@ -1,12 +1,12 @@ import codecs import sys -from typing import Any, Callable, Dict, Tuple, Union +from typing import Any, Callable, Dict, Tuple # This type is not exposed; it is defined in unicodeobject.c class _EncodingMap: def size(self) -> int: ... -_MapT = Union[Dict[int, int], _EncodingMap] +_MapT = Dict[int, int] | _EncodingMap _Handler = Callable[[Exception], Tuple[str, int]] def register(__search_function: Callable[[str], Any]) -> None: ... diff --git a/stdlib/_csv.pyi b/stdlib/_csv.pyi index 65f0ca27f0ec..c6d720e02c93 100644 --- a/stdlib/_csv.pyi +++ b/stdlib/_csv.pyi @@ -1,4 +1,4 @@ -from typing import Any, Iterable, Iterator, List, Protocol, Type, Union +from typing import Any, Iterable, Iterator, List, Protocol, Type QUOTE_ALL: int QUOTE_MINIMAL: int @@ -18,7 +18,7 @@ class Dialect: strict: int def __init__(self) -> None: ... -_DialectLike = Union[str, Dialect, Type[Dialect]] +_DialectLike = str | Dialect | Type[Dialect] class _reader(Iterator[List[str]]): dialect: Dialect diff --git a/stdlib/_curses.pyi b/stdlib/_curses.pyi index 80e7776c1f0a..64a316354acb 100644 --- a/stdlib/_curses.pyi +++ b/stdlib/_curses.pyi @@ -1,7 +1,7 @@ import sys -from typing import IO, Any, BinaryIO, NamedTuple, Union, overload +from typing import IO, Any, BinaryIO, NamedTuple, overload -_chtype = Union[str, bytes, int] +_chtype = str | bytes | int # ACS codes are only initialized after initscr is called ACS_BBSS: int diff --git a/stdlib/_dummy_threading.pyi b/stdlib/_dummy_threading.pyi index 64998d86bf9f..fdcfa1e5fb84 100644 --- a/stdlib/_dummy_threading.pyi +++ b/stdlib/_dummy_threading.pyi @@ -1,9 +1,9 @@ import sys from types import FrameType, TracebackType -from typing import Any, Callable, Iterable, Mapping, Optional, Type, TypeVar +from typing import Any, Callable, Iterable, Mapping, Type, TypeVar # TODO recursive type -_TF = Callable[[FrameType, str, Any], Optional[Callable[..., Any]]] +_TF = Callable[[FrameType, str, Any], Callable[..., Any] | None] _PF = Callable[[FrameType, str, Any], None] _T = TypeVar("_T") diff --git a/stdlib/_socket.pyi b/stdlib/_socket.pyi index 82898177286b..a5c1d18c12d8 100644 --- a/stdlib/_socket.pyi +++ b/stdlib/_socket.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import ReadableBuffer, WriteableBuffer from collections.abc import Iterable -from typing import Any, SupportsInt, Tuple, Union, overload +from typing import Any, SupportsInt, Tuple, overload if sys.version_info >= (3, 8): from typing import SupportsIndex @@ -15,7 +15,7 @@ _CMSGArg = Tuple[int, int, ReadableBuffer] # Addresses can be either tuples of varying lengths (AF_INET, AF_INET6, # AF_NETLINK, AF_TIPC) or strings (AF_UNIX). -_Address = Union[Tuple[Any, ...], str] +_Address = Tuple[Any, ...] | str _RetAddress = Any # TODO Most methods allow bytes as address objects diff --git a/stdlib/_thread.pyi b/stdlib/_thread.pyi index 2f4252981b68..a9c24e9abb79 100644 --- a/stdlib/_thread.pyi +++ b/stdlib/_thread.pyi @@ -1,7 +1,7 @@ import sys from threading import Thread from types import TracebackType -from typing import Any, Callable, NoReturn, Optional, Tuple, Type +from typing import Any, Callable, NoReturn, Tuple, Type from typing_extensions import final error = RuntimeError @@ -32,7 +32,7 @@ TIMEOUT_MAX: float if sys.version_info >= (3, 8): def get_native_id() -> int: ... # only available on some platforms @final - class _ExceptHookArgs(Tuple[Type[BaseException], Optional[BaseException], Optional[TracebackType], Optional[Thread]]): + class _ExceptHookArgs(Tuple[Type[BaseException], BaseException | None, TracebackType | None, Thread | None]): @property def exc_type(self) -> Type[BaseException]: ... @property diff --git a/stdlib/aifc.pyi b/stdlib/aifc.pyi index 79f470a366bb..fd3ea65cb720 100644 --- a/stdlib/aifc.pyi +++ b/stdlib/aifc.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import Self from types import TracebackType -from typing import IO, Any, NamedTuple, Tuple, Type, Union, overload +from typing import IO, Any, NamedTuple, Tuple, Type, overload from typing_extensions import Literal class Error(Exception): ... @@ -14,7 +14,7 @@ class _aifc_params(NamedTuple): comptype: bytes compname: bytes -_File = Union[str, IO[bytes]] +_File = str | IO[bytes] _Marker = Tuple[int, int, bytes] class Aifc_read: diff --git a/stdlib/array.pyi b/stdlib/array.pyi index f49eb2c916c2..12c2070fb4bc 100644 --- a/stdlib/array.pyi +++ b/stdlib/array.pyi @@ -1,11 +1,11 @@ import sys -from typing import Any, BinaryIO, Generic, Iterable, MutableSequence, TypeVar, Union, overload +from typing import Any, BinaryIO, Generic, Iterable, MutableSequence, TypeVar, overload from typing_extensions import Literal, SupportsIndex _IntTypeCode = Literal["b", "B", "h", "H", "i", "I", "l", "L", "q", "Q"] _FloatTypeCode = Literal["f", "d"] _UnicodeTypeCode = Literal["u"] -_TypeCode = Union[_IntTypeCode, _FloatTypeCode, _UnicodeTypeCode] +_TypeCode = _IntTypeCode | _FloatTypeCode | _UnicodeTypeCode _T = TypeVar("_T", int, float, str) diff --git a/stdlib/asyncio/base_events.pyi b/stdlib/asyncio/base_events.pyi index e804c2f5d3bd..8c4479c75783 100644 --- a/stdlib/asyncio/base_events.pyi +++ b/stdlib/asyncio/base_events.pyi @@ -9,7 +9,7 @@ from asyncio.tasks import Task from asyncio.transports import BaseTransport from collections.abc import Iterable from socket import AddressFamily, SocketKind, _Address, _RetAddress, socket -from typing import IO, Any, Awaitable, Callable, Dict, Generator, Sequence, Tuple, TypeVar, Union, overload +from typing import IO, Any, Awaitable, Callable, Dict, Generator, Sequence, Tuple, TypeVar, overload from typing_extensions import Literal if sys.version_info >= (3, 7): @@ -19,7 +19,7 @@ _T = TypeVar("_T") _Context = Dict[str, Any] _ExceptionHandler = Callable[[AbstractEventLoop, _Context], Any] _ProtocolFactory = Callable[[], BaseProtocol] -_SSLContext = Union[bool, None, ssl.SSLContext] +_SSLContext = bool | None | ssl.SSLContext _TransProtPair = Tuple[BaseTransport, BaseProtocol] class Server(AbstractServer): diff --git a/stdlib/asyncio/base_subprocess.pyi b/stdlib/asyncio/base_subprocess.pyi index 096bce60f7e3..fe9f096bb54c 100644 --- a/stdlib/asyncio/base_subprocess.pyi +++ b/stdlib/asyncio/base_subprocess.pyi @@ -1,10 +1,10 @@ import subprocess from collections import deque -from typing import IO, Any, Callable, Optional, Sequence, Tuple, Union +from typing import IO, Any, Callable, Sequence, Tuple from . import events, futures, protocols, transports -_File = Optional[Union[int, IO[Any]]] +_File = int | IO[Any] | None class BaseSubprocessTransport(transports.SubprocessTransport): diff --git a/stdlib/asyncio/events.pyi b/stdlib/asyncio/events.pyi index 6ef9117b6491..8d94381932b2 100644 --- a/stdlib/asyncio/events.pyi +++ b/stdlib/asyncio/events.pyi @@ -3,7 +3,7 @@ import sys from _typeshed import FileDescriptorLike, Self from abc import ABCMeta, abstractmethod from socket import AddressFamily, SocketKind, _Address, _RetAddress, socket -from typing import IO, Any, Awaitable, Callable, Dict, Generator, Sequence, Tuple, TypeVar, Union, overload +from typing import IO, Any, Awaitable, Callable, Dict, Generator, Sequence, Tuple, TypeVar, overload from typing_extensions import Literal from .base_events import Server @@ -20,7 +20,7 @@ _T = TypeVar("_T") _Context = Dict[str, Any] _ExceptionHandler = Callable[[AbstractEventLoop, _Context], Any] _ProtocolFactory = Callable[[], BaseProtocol] -_SSLContext = Union[bool, None, ssl.SSLContext] +_SSLContext = bool | None | ssl.SSLContext _TransProtPair = Tuple[BaseTransport, BaseProtocol] class Handle: diff --git a/stdlib/asyncio/format_helpers.pyi b/stdlib/asyncio/format_helpers.pyi index be80efe266b1..ae197000cc50 100644 --- a/stdlib/asyncio/format_helpers.pyi +++ b/stdlib/asyncio/format_helpers.pyi @@ -2,12 +2,12 @@ import functools import sys import traceback from types import FrameType, FunctionType -from typing import Any, Iterable, Union, overload +from typing import Any, Iterable, overload class _HasWrapper: __wrapper__: _HasWrapper | FunctionType -_FuncType = Union[FunctionType, _HasWrapper, functools.partial[Any], functools.partialmethod[Any]] +_FuncType = FunctionType | _HasWrapper | functools.partial[Any] | functools.partialmethod[Any] if sys.version_info >= (3, 7): @overload diff --git a/stdlib/asyncio/streams.pyi b/stdlib/asyncio/streams.pyi index 595222280d58..c4649f8c0a62 100644 --- a/stdlib/asyncio/streams.pyi +++ b/stdlib/asyncio/streams.pyi @@ -1,11 +1,11 @@ import sys from _typeshed import StrPath -from typing import Any, AsyncIterator, Awaitable, Callable, Iterable, Optional +from typing import Any, AsyncIterator, Awaitable, Callable, Iterable from . import events, protocols, transports from .base_events import Server -_ClientConnectedCallback = Callable[[StreamReader, StreamWriter], Optional[Awaitable[None]]] +_ClientConnectedCallback = Callable[[StreamReader, StreamWriter], Awaitable[None] | None] if sys.version_info < (3, 8): class IncompleteReadError(EOFError): diff --git a/stdlib/asyncio/subprocess.pyi b/stdlib/asyncio/subprocess.pyi index d835c12af3d8..4a3d155899f9 100644 --- a/stdlib/asyncio/subprocess.pyi +++ b/stdlib/asyncio/subprocess.pyi @@ -2,13 +2,13 @@ import subprocess import sys from _typeshed import StrOrBytesPath from asyncio import events, protocols, streams, transports -from typing import IO, Any, Callable, Union +from typing import IO, Any, Callable from typing_extensions import Literal if sys.version_info >= (3, 8): _ExecArg = StrOrBytesPath else: - _ExecArg = Union[str, bytes] + _ExecArg = str | bytes PIPE: int STDOUT: int diff --git a/stdlib/asyncio/trsock.pyi b/stdlib/asyncio/trsock.pyi index 33ec5d67aaf9..1514f01afca0 100644 --- a/stdlib/asyncio/trsock.pyi +++ b/stdlib/asyncio/trsock.pyi @@ -1,13 +1,13 @@ import socket import sys from types import TracebackType -from typing import Any, BinaryIO, Iterable, NoReturn, Tuple, Type, Union, overload +from typing import Any, BinaryIO, Iterable, NoReturn, Tuple, Type, overload if sys.version_info >= (3, 8): # These are based in socket, maybe move them out into _typeshed.pyi or such - _Address = Union[Tuple[Any, ...], str] + _Address = Tuple[Any, ...] | str _RetAddress = Any - _WriteBuffer = Union[bytearray, memoryview] + _WriteBuffer = bytearray | memoryview _CMSG = Tuple[int, int, bytes] class TransportSocket: def __init__(self, sock: socket.socket) -> None: ... diff --git a/stdlib/binhex.pyi b/stdlib/binhex.pyi index 02d094faf923..8383a028a6cd 100644 --- a/stdlib/binhex.pyi +++ b/stdlib/binhex.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, Tuple, Union +from typing import IO, Any, Tuple class Error(Exception): ... @@ -13,7 +13,7 @@ class FInfo: Flags: int _FileInfoTuple = Tuple[str, FInfo, int, int] -_FileHandleUnion = Union[str, IO[bytes]] +_FileHandleUnion = str | IO[bytes] def getfileinfo(name: str) -> _FileInfoTuple: ... diff --git a/stdlib/builtins.pyi b/stdlib/builtins.pyi index 0c66c7972ca1..a58f01f98140 100644 --- a/stdlib/builtins.pyi +++ b/stdlib/builtins.pyi @@ -1292,7 +1292,7 @@ class _SupportsPow3NoneOnly(Protocol[_E, _T_co]): class _SupportsPow3(Protocol[_E, _M, _T_co]): def __pow__(self, __other: _E, __modulo: _M) -> _T_co: ... -_SupportsSomeKindOfPow = Union[_SupportsPow2[Any, Any], _SupportsPow3NoneOnly[Any, Any], _SupportsPow3[Any, Any, Any]] +_SupportsSomeKindOfPow = _SupportsPow2[Any, Any] | _SupportsPow3NoneOnly[Any, Any] | _SupportsPow3[Any, Any, Any] if sys.version_info >= (3, 8): @overload diff --git a/stdlib/calendar.pyi b/stdlib/calendar.pyi index 26073fb7281b..af38401609d3 100644 --- a/stdlib/calendar.pyi +++ b/stdlib/calendar.pyi @@ -1,9 +1,9 @@ import datetime import sys from time import struct_time -from typing import Any, Iterable, Optional, Sequence, Tuple +from typing import Any, Iterable, Sequence, Tuple -_LocaleType = Tuple[Optional[str], Optional[str]] +_LocaleType = Tuple[str | None, str | None] class IllegalMonthError(ValueError): def __init__(self, month: int) -> None: ... diff --git a/stdlib/cgitb.pyi b/stdlib/cgitb.pyi index 7576740fc1c0..4800bb4a87fc 100644 --- a/stdlib/cgitb.pyi +++ b/stdlib/cgitb.pyi @@ -1,8 +1,8 @@ from _typeshed import StrOrBytesPath from types import FrameType, TracebackType -from typing import IO, Any, Callable, Optional, Tuple, Type +from typing import IO, Any, Callable, Tuple, Type -_ExcInfo = Tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]] +_ExcInfo = Tuple[Type[BaseException] | None, BaseException | None, TracebackType | None] def reset() -> str: ... # undocumented def small(text: str) -> str: ... # undocumented diff --git a/stdlib/cmath.pyi b/stdlib/cmath.pyi index 04c2b632d411..ee51861fdaa0 100644 --- a/stdlib/cmath.pyi +++ b/stdlib/cmath.pyi @@ -1,5 +1,5 @@ import sys -from typing import SupportsComplex, SupportsFloat, Union +from typing import SupportsComplex, SupportsFloat if sys.version_info >= (3, 8): from typing import SupportsIndex @@ -13,9 +13,9 @@ nanj: complex tau: float if sys.version_info >= (3, 8): - _C = Union[SupportsFloat, SupportsComplex, SupportsIndex, complex] + _C = SupportsFloat | SupportsComplex | SupportsIndex | complex else: - _C = Union[SupportsFloat, SupportsComplex, complex] + _C = SupportsFloat | SupportsComplex | complex def acos(__z: _C) -> complex: ... def acosh(__z: _C) -> complex: ... diff --git a/stdlib/configparser.pyi b/stdlib/configparser.pyi index 83d9d969080a..2aa696183827 100644 --- a/stdlib/configparser.pyi +++ b/stdlib/configparser.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import StrOrBytesPath, StrPath, SupportsWrite from collections.abc import Callable, ItemsView, Iterable, Iterator, Mapping, MutableMapping, Sequence -from typing import Any, ClassVar, Dict, Optional, Pattern, Type, TypeVar, overload +from typing import Any, ClassVar, Dict, Pattern, Type, TypeVar, overload from typing_extensions import Literal # Internal type aliases @@ -180,7 +180,7 @@ class SectionProxy(MutableMapping[str, str]): # SectionProxy can have arbitrary attributes when custom converters are used def __getattr__(self, key: str) -> Callable[..., Any]: ... -class ConverterMapping(MutableMapping[str, Optional[_converter]]): +class ConverterMapping(MutableMapping[str, _converter | None]): GETTERCRE: Pattern[Any] def __init__(self, parser: RawConfigParser) -> None: ... def __getitem__(self, key: str) -> _converter: ... diff --git a/stdlib/contextlib.pyi b/stdlib/contextlib.pyi index df1ca8d28c65..e6a444bdcfc7 100644 --- a/stdlib/contextlib.pyi +++ b/stdlib/contextlib.pyi @@ -10,7 +10,6 @@ from typing import ( ContextManager, Generic, Iterator, - Optional, Protocol, Type, TypeVar, @@ -26,11 +25,11 @@ if sys.version_info >= (3, 7): _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) -_T_io = TypeVar("_T_io", bound=Optional[IO[str]]) +_T_io = TypeVar("_T_io", bound=IO[str] | None) _F = TypeVar("_F", bound=Callable[..., Any]) _P = ParamSpec("_P") -_ExitFunc = Callable[[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]], bool] +_ExitFunc = Callable[[Type[BaseException] | None, BaseException | None, TracebackType | None], bool] _CM_EF = TypeVar("_CM_EF", AbstractContextManager[Any], _ExitFunc) class _GeneratorContextManager(AbstractContextManager[_T_co]): @@ -88,7 +87,7 @@ class ExitStack(AbstractContextManager[ExitStack]): ) -> bool: ... if sys.version_info >= (3, 7): - _ExitCoroFunc = Callable[[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]], Awaitable[bool]] + _ExitCoroFunc = Callable[[Type[BaseException] | None, BaseException | None, TracebackType | None], Awaitable[bool]] _CallbackCoroFunc = Callable[..., Awaitable[Any]] _ACM_EF = TypeVar("_ACM_EF", AbstractAsyncContextManager[Any], _ExitCoroFunc) class AsyncExitStack(AbstractAsyncContextManager[AsyncExitStack]): diff --git a/stdlib/ctypes/__init__.pyi b/stdlib/ctypes/__init__.pyi index b76c59becab8..023f4f947fa6 100644 --- a/stdlib/ctypes/__init__.pyi +++ b/stdlib/ctypes/__init__.pyi @@ -9,7 +9,6 @@ from typing import ( Iterable, Iterator, Mapping, - Optional, Sequence, Tuple, Type, @@ -98,7 +97,7 @@ class _CData(metaclass=_CDataMeta): class _CanCastTo(_CData): ... class _PointerLike(_CanCastTo): ... -_ECT = Callable[[Optional[Type[_CData]], _FuncPointer, Tuple[_CData, ...]], _CData] +_ECT = Callable[[Type[_CData] | None, _FuncPointer, Tuple[_CData, ...]], _CData] _PF = _UnionT[Tuple[int], Tuple[int, str], Tuple[int, str, Any]] class _FuncPointer(_PointerLike, _CData): @@ -209,7 +208,7 @@ class c_byte(_SimpleCData[int]): ... class c_char(_SimpleCData[bytes]): def __init__(self, value: int | bytes = ...) -> None: ... -class c_char_p(_PointerLike, _SimpleCData[Optional[bytes]]): +class c_char_p(_PointerLike, _SimpleCData[bytes | None]): def __init__(self, value: int | bytes | None = ...) -> None: ... class c_double(_SimpleCData[float]): ... @@ -234,10 +233,10 @@ class c_uint64(_SimpleCData[int]): ... class c_ulong(_SimpleCData[int]): ... class c_ulonglong(_SimpleCData[int]): ... class c_ushort(_SimpleCData[int]): ... -class c_void_p(_PointerLike, _SimpleCData[Optional[int]]): ... +class c_void_p(_PointerLike, _SimpleCData[int | None]): ... class c_wchar(_SimpleCData[str]): ... -class c_wchar_p(_PointerLike, _SimpleCData[Optional[str]]): +class c_wchar_p(_PointerLike, _SimpleCData[str | None]): def __init__(self, value: int | str | None = ...) -> None: ... class c_bool(_SimpleCData[bool]): diff --git a/stdlib/dbm/__init__.pyi b/stdlib/dbm/__init__.pyi index 5ecacd91b4ed..80826851d933 100644 --- a/stdlib/dbm/__init__.pyi +++ b/stdlib/dbm/__init__.pyi @@ -1,10 +1,10 @@ from _typeshed import Self from types import TracebackType -from typing import Iterator, MutableMapping, Type, Union +from typing import Iterator, MutableMapping, Type from typing_extensions import Literal -_KeyType = Union[str, bytes] -_ValueType = Union[str, bytes] +_KeyType = str | bytes +_ValueType = str | bytes _TFlags = Literal[ "r", "w", diff --git a/stdlib/dbm/dumb.pyi b/stdlib/dbm/dumb.pyi index 0a941b070754..16c2cc826ef1 100644 --- a/stdlib/dbm/dumb.pyi +++ b/stdlib/dbm/dumb.pyi @@ -1,9 +1,9 @@ from _typeshed import Self from types import TracebackType -from typing import Iterator, MutableMapping, Type, Union +from typing import Iterator, MutableMapping, Type -_KeyType = Union[str, bytes] -_ValueType = Union[str, bytes] +_KeyType = str | bytes +_ValueType = str | bytes error = OSError diff --git a/stdlib/dbm/gnu.pyi b/stdlib/dbm/gnu.pyi index 850c32ac0ea9..a971c900e072 100644 --- a/stdlib/dbm/gnu.pyi +++ b/stdlib/dbm/gnu.pyi @@ -1,10 +1,10 @@ from _typeshed import Self from types import TracebackType -from typing import Type, TypeVar, Union, overload +from typing import Type, TypeVar, overload _T = TypeVar("_T") -_KeyType = Union[str, bytes] -_ValueType = Union[str, bytes] +_KeyType = str | bytes +_ValueType = str | bytes class error(OSError): ... diff --git a/stdlib/dbm/ndbm.pyi b/stdlib/dbm/ndbm.pyi index 7b04c5385dbe..d9bf5699db00 100644 --- a/stdlib/dbm/ndbm.pyi +++ b/stdlib/dbm/ndbm.pyi @@ -1,10 +1,10 @@ from _typeshed import Self from types import TracebackType -from typing import Type, TypeVar, Union, overload +from typing import Type, TypeVar, overload _T = TypeVar("_T") -_KeyType = Union[str, bytes] -_ValueType = Union[str, bytes] +_KeyType = str | bytes +_ValueType = str | bytes class error(OSError): ... diff --git a/stdlib/decimal.pyi b/stdlib/decimal.pyi index 30c8e973348d..24ef49190075 100644 --- a/stdlib/decimal.pyi +++ b/stdlib/decimal.pyi @@ -1,10 +1,10 @@ import numbers from types import TracebackType -from typing import Any, Container, NamedTuple, Sequence, Tuple, Type, TypeVar, Union, overload +from typing import Any, Container, NamedTuple, Sequence, Tuple, Type, TypeVar, overload -_Decimal = Union[Decimal, int] -_DecimalNew = Union[Decimal, float, str, Tuple[int, Sequence[int], int]] -_ComparableNum = Union[Decimal, float, numbers.Rational] +_Decimal = Decimal | int +_DecimalNew = Decimal | float | str | Tuple[int, Sequence[int], int] +_ComparableNum = Decimal | float | numbers.Rational _DecimalT = TypeVar("_DecimalT", bound=Decimal) class DecimalTuple(NamedTuple): diff --git a/stdlib/difflib.pyi b/stdlib/difflib.pyi index 944a63966241..502f78921928 100644 --- a/stdlib/difflib.pyi +++ b/stdlib/difflib.pyi @@ -1,11 +1,11 @@ import sys -from typing import Any, AnyStr, Callable, Generic, Iterable, Iterator, NamedTuple, Sequence, TypeVar, Union, overload +from typing import Any, AnyStr, Callable, Generic, Iterable, Iterator, NamedTuple, Sequence, TypeVar, overload if sys.version_info >= (3, 9): from types import GenericAlias _T = TypeVar("_T") -_JunkCallback = Union[Callable[[str], bool], Callable[[str], bool]] +_JunkCallback = Callable[[str], bool] | Callable[[str], bool] class Match(NamedTuple): a: int diff --git a/stdlib/dis.pyi b/stdlib/dis.pyi index ac0632d25c9c..b29f4810d1f9 100644 --- a/stdlib/dis.pyi +++ b/stdlib/dis.pyi @@ -16,12 +16,12 @@ from opcode import ( opname as opname, stack_effect as stack_effect, ) -from typing import IO, Any, Callable, Iterator, NamedTuple, Union +from typing import IO, Any, Callable, Iterator, NamedTuple # Strictly this should not have to include Callable, but mypy doesn't use FunctionType # for functions (python/mypy#3171) -_HaveCodeType = Union[types.MethodType, types.FunctionType, types.CodeType, type, Callable[..., Any]] -_HaveCodeOrStringType = Union[_HaveCodeType, str, bytes] +_HaveCodeType = types.MethodType | types.FunctionType | types.CodeType | type | Callable[..., Any] +_HaveCodeOrStringType = _HaveCodeType | str | bytes class Instruction(NamedTuple): opname: str diff --git a/stdlib/distutils/ccompiler.pyi b/stdlib/distutils/ccompiler.pyi index d21de4691503..23ecd516ec11 100644 --- a/stdlib/distutils/ccompiler.pyi +++ b/stdlib/distutils/ccompiler.pyi @@ -1,6 +1,6 @@ -from typing import Any, Callable, Optional, Tuple, Union +from typing import Any, Callable, Optional, Tuple -_Macro = Union[Tuple[str], Tuple[str, Optional[str]]] +_Macro = Tuple[str] | Tuple[str, Optional[str]] def gen_lib_options( compiler: CCompiler, library_dirs: list[str], runtime_library_dirs: list[str], libraries: list[str] diff --git a/stdlib/distutils/fancy_getopt.pyi b/stdlib/distutils/fancy_getopt.pyi index 06a0847e4687..4ede4a8a175e 100644 --- a/stdlib/distutils/fancy_getopt.pyi +++ b/stdlib/distutils/fancy_getopt.pyi @@ -1,6 +1,6 @@ -from typing import Any, Iterable, List, Mapping, Optional, Tuple, overload +from typing import Any, Iterable, List, Mapping, Tuple, overload -_Option = Tuple[str, Optional[str], str] +_Option = Tuple[str, str | None, str] _GR = Tuple[List[str], OptionDummy] def fancy_getopt( diff --git a/stdlib/email/_header_value_parser.pyi b/stdlib/email/_header_value_parser.pyi index a14f5a2d2238..993413482ef2 100644 --- a/stdlib/email/_header_value_parser.pyi +++ b/stdlib/email/_header_value_parser.pyi @@ -1,7 +1,7 @@ import sys from email.errors import HeaderParseError, MessageDefect from email.policy import Policy -from typing import Any, Iterable, Iterator, List, Pattern, Type, TypeVar, Union +from typing import Any, Iterable, Iterator, List, Pattern, Type, TypeVar from typing_extensions import Final _T = TypeVar("_T") @@ -23,7 +23,7 @@ def quote_string(value: Any) -> str: ... if sys.version_info >= (3, 7): rfc2047_matcher: Pattern[str] -class TokenList(List[Union[TokenList, Terminal]]): +class TokenList(List[TokenList | Terminal]): token_type: str | None syntactic_break: bool ew_combine_allowed: bool diff --git a/stdlib/enum.pyi b/stdlib/enum.pyi index f4ce81eaf1ce..b6dd951b6316 100644 --- a/stdlib/enum.pyi +++ b/stdlib/enum.pyi @@ -3,7 +3,7 @@ import types from abc import ABCMeta from builtins import property as _builtins_property from collections.abc import Iterable, Iterator, Mapping -from typing import Any, Dict, Tuple, Type, TypeVar, Union, overload +from typing import Any, Dict, Tuple, Type, TypeVar, overload _T = TypeVar("_T") _S = TypeVar("_S", bound=Type[Enum]) @@ -19,7 +19,7 @@ _S = TypeVar("_S", bound=Type[Enum]) # # >>> Enum('Foo', names={'RED': 1, 'YELLOW': 2}) # -_EnumNames = Union[str, Iterable[str], Iterable[Iterable[Union[str, Any]]], Mapping[str, Any]] +_EnumNames = str | Iterable[str] | Iterable[Iterable[str | Any]] | Mapping[str, Any] class _EnumDict(Dict[str, Any]): def __init__(self) -> None: ... diff --git a/stdlib/fractions.pyi b/stdlib/fractions.pyi index 8de5ae20971c..be7fa2274542 100644 --- a/stdlib/fractions.pyi +++ b/stdlib/fractions.pyi @@ -1,10 +1,10 @@ import sys from decimal import Decimal from numbers import Integral, Rational, Real -from typing import Type, TypeVar, Union, overload +from typing import Type, TypeVar, overload from typing_extensions import Literal -_ComparableNum = Union[int, float, Decimal, Real] +_ComparableNum = int | float | Decimal | Real _T = TypeVar("_T") if sys.version_info < (3, 9): diff --git a/stdlib/hmac.pyi b/stdlib/hmac.pyi index 440bddd7919c..9ce029490223 100644 --- a/stdlib/hmac.pyi +++ b/stdlib/hmac.pyi @@ -1,11 +1,11 @@ import sys from _typeshed import ReadableBuffer from types import ModuleType -from typing import Any, AnyStr, Callable, Union, overload +from typing import Any, AnyStr, Callable, overload # TODO more precise type for object of hashlib _Hash = Any -_DigestMod = Union[str, Callable[[], _Hash], ModuleType] +_DigestMod = str | Callable[[], _Hash] | ModuleType digest_size: None diff --git a/stdlib/http/client.pyi b/stdlib/http/client.pyi index 1558f6ff46e8..5f55277a5a7a 100644 --- a/stdlib/http/client.pyi +++ b/stdlib/http/client.pyi @@ -5,9 +5,9 @@ import sys import types from _typeshed import Self, WriteableBuffer from socket import socket -from typing import IO, Any, BinaryIO, Callable, Iterable, Iterator, Mapping, Protocol, Type, TypeVar, Union, overload +from typing import IO, Any, BinaryIO, Callable, Iterable, Iterator, Mapping, Protocol, Type, TypeVar, overload -_DataType = Union[bytes, IO[Any], Iterable[bytes], str] +_DataType = bytes | IO[Any] | Iterable[bytes] | str _T = TypeVar("_T") HTTP_PORT: int diff --git a/stdlib/http/cookies.pyi b/stdlib/http/cookies.pyi index 4244c0c6aa0d..e872e338c1e6 100644 --- a/stdlib/http/cookies.pyi +++ b/stdlib/http/cookies.pyi @@ -1,10 +1,10 @@ import sys -from typing import Any, Dict, Generic, Iterable, Mapping, TypeVar, Union, overload +from typing import Any, Dict, Generic, Iterable, Mapping, TypeVar, overload if sys.version_info >= (3, 9): from types import GenericAlias -_DataType = Union[str, Mapping[str, Union[str, Morsel[Any]]]] +_DataType = str | Mapping[str, str | Morsel[Any]] _T = TypeVar("_T") @overload diff --git a/stdlib/imaplib.pyi b/stdlib/imaplib.pyi index a9f19048c9ae..5e0b1bb05dd0 100644 --- a/stdlib/imaplib.pyi +++ b/stdlib/imaplib.pyi @@ -5,14 +5,14 @@ from _typeshed import Self from socket import socket as _socket from ssl import SSLContext, SSLSocket from types import TracebackType -from typing import IO, Any, Callable, List, Pattern, Tuple, Type, Union +from typing import IO, Any, Callable, List, Pattern, Tuple, Type from typing_extensions import Literal # TODO: Commands should use their actual return types, not this type alias. # E.g. Tuple[Literal["OK"], List[bytes]] _CommandResults = Tuple[str, List[Any]] -_AnyResponseData = Union[List[None], List[Union[bytes, Tuple[bytes, bytes]]]] +_AnyResponseData = List[None] | List[bytes | Tuple[bytes, bytes]] _list = list # conflicts with a method named "list" diff --git a/stdlib/importlib/abc.pyi b/stdlib/importlib/abc.pyi index 47a00643e485..8ac4ffea385e 100644 --- a/stdlib/importlib/abc.pyi +++ b/stdlib/importlib/abc.pyi @@ -12,10 +12,10 @@ from _typeshed import ( from abc import ABCMeta, abstractmethod from importlib.machinery import ModuleSpec from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper -from typing import IO, Any, BinaryIO, Iterator, Mapping, NoReturn, Protocol, Sequence, Union, overload +from typing import IO, Any, BinaryIO, Iterator, Mapping, NoReturn, Protocol, Sequence, overload from typing_extensions import Literal, runtime_checkable -_Path = Union[bytes, str] +_Path = bytes | str class Finder(metaclass=ABCMeta): ... diff --git a/stdlib/importlib/resources.pyi b/stdlib/importlib/resources.pyi index b484d7126b21..f832e063e927 100644 --- a/stdlib/importlib/resources.pyi +++ b/stdlib/importlib/resources.pyi @@ -7,10 +7,10 @@ if sys.version_info >= (3, 7): from contextlib import AbstractContextManager from pathlib import Path from types import ModuleType - from typing import BinaryIO, Iterator, TextIO, Union + from typing import BinaryIO, Iterator, TextIO - Package = Union[str, ModuleType] - Resource = Union[str, os.PathLike[Any]] + Package = str | ModuleType + Resource = str | os.PathLike[Any] def open_binary(package: Package, resource: Resource) -> BinaryIO: ... def open_text(package: Package, resource: Resource, encoding: str = ..., errors: str = ...) -> TextIO: ... def read_binary(package: Package, resource: Resource) -> bytes: ... diff --git a/stdlib/inspect.pyi b/stdlib/inspect.pyi index bd00d9ba677e..07b4fbfaa80f 100644 --- a/stdlib/inspect.pyi +++ b/stdlib/inspect.pyi @@ -23,7 +23,7 @@ from types import ( if sys.version_info >= (3, 7): from types import ClassMethodDescriptorType, WrapperDescriptorType, MemberDescriptorType, MethodDescriptorType -from typing import Any, ClassVar, NamedTuple, Protocol, Tuple, Type, TypeVar, Union +from typing import Any, ClassVar, NamedTuple, Protocol, Tuple, Type, TypeVar from typing_extensions import Literal, TypeGuard # @@ -123,7 +123,7 @@ def isdatadescriptor(object: object) -> TypeGuard[_SupportsSet[Any, Any] | _Supp # # Retrieving source code # -_SourceObjectType = Union[ModuleType, Type[Any], MethodType, FunctionType, TracebackType, FrameType, CodeType, Callable[..., Any]] +_SourceObjectType = 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 = ...) -> str: ... diff --git a/stdlib/itertools.pyi b/stdlib/itertools.pyi index 1ff7ffc181ed..d9204bfc0a67 100644 --- a/stdlib/itertools.pyi +++ b/stdlib/itertools.pyi @@ -12,7 +12,6 @@ from typing import ( Tuple, Type, TypeVar, - Union, overload, ) from typing_extensions import Literal, SupportsIndex @@ -23,7 +22,7 @@ if sys.version_info >= (3, 9): _T = TypeVar("_T") _S = TypeVar("_S") _N = TypeVar("_N", int, float, SupportsFloat, SupportsInt, SupportsIndex, SupportsComplex) -_Step = Union[int, float, SupportsFloat, SupportsInt, SupportsIndex, SupportsComplex] +_Step = int | float | SupportsFloat | SupportsInt | SupportsIndex | SupportsComplex Predicate = Callable[[_T], object] diff --git a/stdlib/lib2to3/pgen2/grammar.pyi b/stdlib/lib2to3/pgen2/grammar.pyi index 48cb4eae916c..5fa48b3d935a 100644 --- a/stdlib/lib2to3/pgen2/grammar.pyi +++ b/stdlib/lib2to3/pgen2/grammar.pyi @@ -1,8 +1,8 @@ from _typeshed import StrPath -from typing import Dict, List, Optional, Tuple, TypeVar +from typing import Dict, List, Tuple, TypeVar _P = TypeVar("_P") -_Label = Tuple[int, Optional[str]] +_Label = Tuple[int, str | None] _DFA = List[List[Tuple[int, int]]] _DFAS = Tuple[_DFA, Dict[int, int]] diff --git a/stdlib/lib2to3/pytree.pyi b/stdlib/lib2to3/pytree.pyi index eab82cbc200d..aa0fc71395d1 100644 --- a/stdlib/lib2to3/pytree.pyi +++ b/stdlib/lib2to3/pytree.pyi @@ -1,11 +1,11 @@ from lib2to3.pgen2.grammar import Grammar -from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, TypeVar, Union +from typing import Any, Callable, Dict, Iterator, List, Tuple, TypeVar _P = TypeVar("_P") -_NL = Union[Node, Leaf] +_NL = Node | Leaf _Context = Tuple[str, int, int] _Results = Dict[str, _NL] -_RawNode = Tuple[int, str, _Context, Optional[List[_NL]]] +_RawNode = Tuple[int, str, _Context, List[_NL] | None] _Convert = Callable[[Grammar, _RawNode], Any] HUGE: int diff --git a/stdlib/lzma.pyi b/stdlib/lzma.pyi index e1da3024c4ac..bee09c86ca58 100644 --- a/stdlib/lzma.pyi +++ b/stdlib/lzma.pyi @@ -1,12 +1,12 @@ import io from _typeshed import ReadableBuffer, Self, StrOrBytesPath -from typing import IO, Any, Mapping, Sequence, TextIO, Union, overload +from typing import IO, Any, Mapping, Sequence, TextIO, overload from typing_extensions import Literal, final _OpenBinaryWritingMode = Literal["w", "wb", "x", "xb", "a", "ab"] _OpenTextWritingMode = Literal["wt", "xt", "at"] -_PathOrFile = Union[StrOrBytesPath, IO[bytes]] +_PathOrFile = StrOrBytesPath | IO[bytes] _FilterChain = Sequence[Mapping[str, Any]] diff --git a/stdlib/mailbox.pyi b/stdlib/mailbox.pyi index ffd9c3005cec..ba5977ac079c 100644 --- a/stdlib/mailbox.pyi +++ b/stdlib/mailbox.pyi @@ -2,22 +2,7 @@ import email.message import sys from _typeshed import Self, StrOrBytesPath from types import TracebackType -from typing import ( - IO, - Any, - AnyStr, - Callable, - Generic, - Iterable, - Iterator, - Mapping, - Protocol, - Sequence, - Type, - TypeVar, - Union, - overload, -) +from typing import IO, Any, AnyStr, Callable, Generic, Iterable, Iterator, Mapping, Protocol, Sequence, Type, TypeVar, overload from typing_extensions import Literal if sys.version_info >= (3, 9): @@ -25,7 +10,7 @@ if sys.version_info >= (3, 9): _T = TypeVar("_T") _MessageT = TypeVar("_MessageT", bound=Message) -_MessageData = Union[email.message.Message, bytes, str, IO[str], IO[bytes]] +_MessageData = email.message.Message | bytes | str | IO[str] | IO[bytes] class _HasIteritems(Protocol): def iteritems(self) -> Iterator[tuple[str, _MessageData]]: ... diff --git a/stdlib/mailcap.pyi b/stdlib/mailcap.pyi index 9eaa771ed3d3..f72d819576a4 100644 --- a/stdlib/mailcap.pyi +++ b/stdlib/mailcap.pyi @@ -1,6 +1,6 @@ -from typing import Dict, Mapping, Sequence, Union +from typing import Dict, Mapping, Sequence -_Cap = Dict[str, Union[str, int]] +_Cap = Dict[str, str | int] def findmatch( caps: Mapping[str, list[_Cap]], MIMEtype: str, key: str = ..., filename: str = ..., plist: Sequence[str] = ... diff --git a/stdlib/math.pyi b/stdlib/math.pyi index d5e6f99dfa68..bc679339e876 100644 --- a/stdlib/math.pyi +++ b/stdlib/math.pyi @@ -1,10 +1,10 @@ import sys from _typeshed import SupportsTrunc -from typing import Iterable, SupportsFloat, Union, overload +from typing import Iterable, SupportsFloat, overload from typing_extensions import SupportsIndex if sys.version_info >= (3, 8): - _SupportsFloatOrIndex = Union[SupportsFloat, SupportsIndex] + _SupportsFloatOrIndex = SupportsFloat | SupportsIndex else: _SupportsFloatOrIndex = SupportsFloat diff --git a/stdlib/msilib/sequence.pyi b/stdlib/msilib/sequence.pyi index 123d232886f7..f9622bb73a78 100644 --- a/stdlib/msilib/sequence.pyi +++ b/stdlib/msilib/sequence.pyi @@ -1,9 +1,9 @@ import sys -from typing import List, Optional, Tuple +from typing import List, Tuple if sys.platform == "win32": - _SequenceType = List[Tuple[str, Optional[str], int]] + _SequenceType = List[Tuple[str, str | None, int]] AdminExecuteSequence: _SequenceType AdminUISequence: _SequenceType diff --git a/stdlib/multiprocessing/__init__.pyi b/stdlib/multiprocessing/__init__.pyi index 000fed79f3e4..d66e2a4c3a09 100644 --- a/stdlib/multiprocessing/__init__.pyi +++ b/stdlib/multiprocessing/__init__.pyi @@ -20,7 +20,7 @@ from multiprocessing.process import active_children as active_children, current_ # multiprocessing.queues or the aliases defined below. See #4266 for discussion. from multiprocessing.queues import JoinableQueue as JoinableQueue, Queue as Queue, SimpleQueue as SimpleQueue from multiprocessing.spawn import freeze_support as freeze_support -from typing import Any, Union, overload +from typing import Any, overload from typing_extensions import Literal if sys.version_info >= (3, 8): @@ -54,7 +54,7 @@ _SemaphoreType = synchronize.Semaphore # be identical (modulo self). # Synchronization primitives -_LockLike = Union[synchronize.Lock, synchronize.RLock] +_LockLike = synchronize.Lock | synchronize.RLock RawValue = context._default_context.RawValue RawArray = context._default_context.RawArray Value = context._default_context.Value diff --git a/stdlib/multiprocessing/connection.pyi b/stdlib/multiprocessing/connection.pyi index 56ea5c7c0b0b..0d5b521b0f2a 100644 --- a/stdlib/multiprocessing/connection.pyi +++ b/stdlib/multiprocessing/connection.pyi @@ -2,13 +2,13 @@ import socket import sys import types from _typeshed import Self -from typing import Any, Iterable, Tuple, Type, Union +from typing import Any, Iterable, Tuple, Type if sys.version_info >= (3, 8): from typing import SupportsIndex # https://docs.python.org/3/library/multiprocessing.html#address-formats -_Address = Union[str, Tuple[str, int]] +_Address = str | Tuple[str, int] class _ConnectionBase: if sys.version_info >= (3, 8): diff --git a/stdlib/multiprocessing/context.pyi b/stdlib/multiprocessing/context.pyi index e65a387819bc..29ca25c4bc04 100644 --- a/stdlib/multiprocessing/context.pyi +++ b/stdlib/multiprocessing/context.pyi @@ -8,10 +8,10 @@ from multiprocessing import queues, synchronize from multiprocessing.pool import Pool as _Pool from multiprocessing.process import BaseProcess from multiprocessing.sharedctypes import SynchronizedArray, SynchronizedBase -from typing import Any, Type, TypeVar, Union, overload +from typing import Any, Type, TypeVar, overload from typing_extensions import Literal -_LockLike = Union[synchronize.Lock, synchronize.RLock] +_LockLike = synchronize.Lock | synchronize.RLock _CT = TypeVar("_CT", bound=_CData) class ProcessError(Exception): ... diff --git a/stdlib/multiprocessing/dummy/connection.pyi b/stdlib/multiprocessing/dummy/connection.pyi index 4ef3d095911f..2b43fcfd6248 100644 --- a/stdlib/multiprocessing/dummy/connection.pyi +++ b/stdlib/multiprocessing/dummy/connection.pyi @@ -1,11 +1,11 @@ from _typeshed import Self from queue import Queue from types import TracebackType -from typing import Any, Tuple, Type, Union +from typing import Any, Tuple, Type families: list[None] -_Address = Union[str, Tuple[str, int]] +_Address = str | Tuple[str, int] class Connection(object): _in: Any diff --git a/stdlib/multiprocessing/synchronize.pyi b/stdlib/multiprocessing/synchronize.pyi index c32c9aafe9a4..685bbd1bcabb 100644 --- a/stdlib/multiprocessing/synchronize.pyi +++ b/stdlib/multiprocessing/synchronize.pyi @@ -2,9 +2,9 @@ import sys import threading from contextlib import AbstractContextManager from multiprocessing.context import BaseContext -from typing import Any, Callable, Union +from typing import Any, Callable -_LockLike = Union[Lock, RLock] +_LockLike = Lock | RLock class Barrier(threading.Barrier): def __init__( diff --git a/stdlib/netrc.pyi b/stdlib/netrc.pyi index b8eac307740a..5b0c68d52622 100644 --- a/stdlib/netrc.pyi +++ b/stdlib/netrc.pyi @@ -1,5 +1,5 @@ from _typeshed import StrOrBytesPath -from typing import Optional, Tuple +from typing import Tuple class NetrcParseError(Exception): filename: str | None @@ -8,7 +8,7 @@ class NetrcParseError(Exception): def __init__(self, msg: str, filename: StrOrBytesPath | None = ..., lineno: int | None = ...) -> None: ... # (login, account, password) tuple -_NetrcTuple = Tuple[str, Optional[str], Optional[str]] +_NetrcTuple = Tuple[str, str | None, str | None] class netrc: hosts: dict[str, _NetrcTuple] diff --git a/stdlib/nntplib.pyi b/stdlib/nntplib.pyi index 508b5f679bc3..3f308e2a2dd7 100644 --- a/stdlib/nntplib.pyi +++ b/stdlib/nntplib.pyi @@ -3,9 +3,9 @@ import socket import ssl import sys from _typeshed import Self -from typing import IO, Any, Iterable, NamedTuple, Tuple, Union +from typing import IO, Any, Iterable, NamedTuple, Tuple -_File = Union[IO[bytes], bytes, str, None] +_File = IO[bytes] | bytes | str | None class NNTPError(Exception): response: str diff --git a/stdlib/os/__init__.pyi b/stdlib/os/__init__.pyi index c68a587671a2..238d02a429d9 100644 --- a/stdlib/os/__init__.pyi +++ b/stdlib/os/__init__.pyi @@ -32,7 +32,6 @@ from typing import ( Sequence, Tuple, TypeVar, - Union, overload, runtime_checkable, ) @@ -341,7 +340,7 @@ def listdir(path: int) -> list[str]: ... @overload def listdir(path: PathLike[str]) -> list[str]: ... -_FdOrAnyPath = Union[int, StrOrBytesPath] +_FdOrAnyPath = int | StrOrBytesPath @final class DirEntry(Generic[AnyStr]): @@ -773,17 +772,17 @@ def execlpe(file: StrOrBytesPath, __arg0: StrOrBytesPath, *args: Any) -> NoRetur # Not separating out PathLike[str] and PathLike[bytes] here because it doesn't make much difference # in practice, and doing so would explode the number of combinations in this already long union. # All these combinations are necessary due to list being invariant. -_ExecVArgs = Union[ - Tuple[StrOrBytesPath, ...], - List[bytes], - List[str], - List[PathLike[Any]], - List[Union[bytes, str]], - List[Union[bytes, PathLike[Any]]], - List[Union[str, PathLike[Any]]], - List[Union[bytes, str, PathLike[Any]]], -] -_ExecEnv = Union[Mapping[bytes, Union[bytes, str]], Mapping[str, Union[bytes, str]]] +_ExecVArgs = ( + Tuple[StrOrBytesPath, ...] + | List[bytes] + | List[str] + | List[PathLike[Any]] + | List[bytes | str] + | List[bytes | PathLike[Any]] + | List[str | PathLike[Any]] + | List[bytes | str | PathLike[Any]] +) +_ExecEnv = Mapping[bytes, bytes | str] | Mapping[str, bytes | str] def execv(__path: StrOrBytesPath, __argv: _ExecVArgs) -> NoReturn: ... def execve(path: _FdOrAnyPath, argv: _ExecVArgs, env: _ExecEnv) -> NoReturn: ... diff --git a/stdlib/pstats.pyi b/stdlib/pstats.pyi index e8256f9f98ab..51e89c320146 100644 --- a/stdlib/pstats.pyi +++ b/stdlib/pstats.pyi @@ -2,9 +2,9 @@ import sys from _typeshed import StrOrBytesPath from cProfile import Profile as _cProfile from profile import Profile -from typing import IO, Any, Iterable, Tuple, TypeVar, Union, overload +from typing import IO, Any, Iterable, Tuple, TypeVar, overload -_Selector = Union[str, float, int] +_Selector = str | float | int _T = TypeVar("_T", bound=Stats) if sys.version_info >= (3, 7): diff --git a/stdlib/pydoc.pyi b/stdlib/pydoc.pyi index b60ef8f9bcb3..835f3872e6f6 100644 --- a/stdlib/pydoc.pyi +++ b/stdlib/pydoc.pyi @@ -1,10 +1,10 @@ from _typeshed import SupportsWrite from reprlib import Repr from types import MethodType, ModuleType, TracebackType -from typing import IO, Any, AnyStr, Callable, Container, Mapping, MutableMapping, NoReturn, Optional, Tuple, Type +from typing import IO, Any, AnyStr, Callable, Container, Mapping, MutableMapping, NoReturn, Tuple, Type # the return type of sys.exc_info(), used by ErrorDuringImport.__init__ -_Exc_Info = Tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]] +_Exc_Info = Tuple[Type[BaseException] | None, BaseException | None, TracebackType | None] __author__: str __date__: str diff --git a/stdlib/pyexpat/__init__.pyi b/stdlib/pyexpat/__init__.pyi index 6a3d6cd56791..26cc3374fb2e 100644 --- a/stdlib/pyexpat/__init__.pyi +++ b/stdlib/pyexpat/__init__.pyi @@ -1,7 +1,7 @@ import pyexpat.errors as errors import pyexpat.model as model from _typeshed import SupportsRead -from typing import Any, Callable, Optional, Tuple +from typing import Any, Callable, Tuple from typing_extensions import final EXPAT_VERSION: str # undocumented @@ -20,7 +20,7 @@ XML_PARAM_ENTITY_PARSING_NEVER: int XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE: int XML_PARAM_ENTITY_PARSING_ALWAYS: int -_Model = Tuple[int, int, Optional[str], Tuple[Any, ...]] +_Model = Tuple[int, int, str | None, Tuple[Any, ...]] @final class XMLParserType(object): diff --git a/stdlib/re.pyi b/stdlib/re.pyi index 01a60d170c50..30105797d8c3 100644 --- a/stdlib/re.pyi +++ b/stdlib/re.pyi @@ -1,7 +1,7 @@ import enum import sys from sre_constants import error as error -from typing import Any, AnyStr, Callable, Iterator, Union, overload +from typing import Any, AnyStr, Callable, Iterator, overload # ----- re variables and constants ----- if sys.version_info >= (3, 7): @@ -45,7 +45,7 @@ U = RegexFlag.U UNICODE = RegexFlag.UNICODE T = RegexFlag.T TEMPLATE = RegexFlag.TEMPLATE -_FlagsType = Union[int, RegexFlag] +_FlagsType = int | RegexFlag if sys.version_info < (3, 7): # undocumented diff --git a/stdlib/readline.pyi b/stdlib/readline.pyi index 2de749b2c216..f8bb00cbb83e 100644 --- a/stdlib/readline.pyi +++ b/stdlib/readline.pyi @@ -1,8 +1,8 @@ from _typeshed import StrOrBytesPath from typing import Callable, Optional, Sequence -_CompleterT = Optional[Callable[[str, int], Optional[str]]] -_CompDispT = Optional[Callable[[str, Sequence[str], int], None]] +_CompleterT = Callable[[str, int], Optional[str]] | None +_CompDispT = Callable[[str, Sequence[str], int], None] | None def parse_and_bind(__string: str) -> None: ... def read_init_file(__filename: StrOrBytesPath | None = ...) -> None: ... diff --git a/stdlib/shutil.pyi b/stdlib/shutil.pyi index f4c492caccaf..4c2517c2ab7f 100644 --- a/stdlib/shutil.pyi +++ b/stdlib/shutil.pyi @@ -1,7 +1,7 @@ import os import sys from _typeshed import StrOrBytesPath, StrPath, SupportsRead, SupportsWrite -from typing import Any, AnyStr, Callable, Iterable, NamedTuple, Sequence, TypeVar, Union, overload +from typing import Any, AnyStr, Callable, Iterable, NamedTuple, Sequence, TypeVar, overload _PathT = TypeVar("_PathT", str, os.PathLike[str]) # Return value of some functions that may either return a path-like object that was passed in or @@ -46,7 +46,7 @@ else: def rmtree(path: bytes | StrPath, ignore_errors: bool = ..., onerror: Callable[[Any, Any, Any], Any] | None = ...) -> None: ... -_CopyFn = Union[Callable[[str, str], None], Callable[[StrPath, StrPath], None]] +_CopyFn = Callable[[str, str], None] | Callable[[StrPath, StrPath], None] if sys.version_info >= (3, 9): def move(src: StrPath, dst: StrPath, copy_function: _CopyFn = ...) -> _PathReturn: ... diff --git a/stdlib/smtplib.pyi b/stdlib/smtplib.pyi index a6f7d07ee7ec..31e769982f0f 100644 --- a/stdlib/smtplib.pyi +++ b/stdlib/smtplib.pyi @@ -4,12 +4,12 @@ from email.message import Message as _Message from socket import socket from ssl import SSLContext from types import TracebackType -from typing import Any, Dict, Pattern, Protocol, Sequence, Tuple, Type, Union, overload +from typing import Any, Dict, Pattern, Protocol, Sequence, Tuple, Type, overload _Reply = Tuple[int, bytes] _SendErrs = Dict[str, _Reply] # Should match source_address for socket.create_connection -_SourceAddress = Tuple[Union[bytearray, bytes, str], int] +_SourceAddress = Tuple[bytearray | bytes | str, int] SMTP_PORT: int SMTP_SSL_PORT: int diff --git a/stdlib/socketserver.pyi b/stdlib/socketserver.pyi index c64408cfab07..a3c9c9a25fce 100644 --- a/stdlib/socketserver.pyi +++ b/stdlib/socketserver.pyi @@ -2,11 +2,11 @@ import sys import types from _typeshed import Self from socket import socket as _socket -from typing import Any, BinaryIO, Callable, ClassVar, Tuple, Type, TypeVar, Union +from typing import Any, BinaryIO, Callable, ClassVar, Tuple, Type, TypeVar _T = TypeVar("_T") -_RequestType = Union[_socket, Tuple[bytes, _socket]] -_AddressType = Union[Tuple[str, int], str] +_RequestType = _socket | Tuple[bytes, _socket] +_AddressType = Tuple[str, int] | str class BaseServer: address_family: int diff --git a/stdlib/sre_parse.pyi b/stdlib/sre_parse.pyi index 8a60c2f990d6..e788980e4512 100644 --- a/stdlib/sre_parse.pyi +++ b/stdlib/sre_parse.pyi @@ -1,6 +1,6 @@ import sys from sre_constants import _NamedIntConstant as _NIC, error as _Error -from typing import Any, Iterable, List, Match, Optional, Pattern as _Pattern, Tuple, Union, overload +from typing import Any, Iterable, List, Match, Pattern as _Pattern, Tuple, overload SPECIAL_CHARS: str REPEAT_CHARS: str @@ -34,11 +34,11 @@ if sys.version_info >= (3, 8): else: Pattern = _State -_OpSubpatternType = Tuple[Optional[int], int, int, SubPattern] +_OpSubpatternType = Tuple[int | None, int, int, SubPattern] _OpGroupRefExistsType = Tuple[int, SubPattern, SubPattern] _OpInType = List[Tuple[_NIC, int]] _OpBranchType = Tuple[None, List[SubPattern]] -_AvType = Union[_OpInType, _OpBranchType, Iterable[SubPattern], _OpGroupRefExistsType, _OpSubpatternType] +_AvType = _OpInType | _OpBranchType | Iterable[SubPattern] | _OpGroupRefExistsType | _OpSubpatternType _CodeType = Tuple[_NIC, _AvType] class SubPattern: @@ -82,8 +82,8 @@ class Tokenizer: def fix_flags(src: str | bytes, flags: int) -> int: ... -_TemplateType = Tuple[List[Tuple[int, int]], List[Optional[str]]] -_TemplateByteType = Tuple[List[Tuple[int, int]], List[Optional[bytes]]] +_TemplateType = Tuple[List[Tuple[int, int]], List[str | None]] +_TemplateByteType = Tuple[List[Tuple[int, int]], List[bytes | None]] if sys.version_info >= (3, 8): def parse(str: str, flags: int = ..., state: State | None = ...) -> SubPattern: ... @overload diff --git a/stdlib/statistics.pyi b/stdlib/statistics.pyi index 908d6adaf45d..5a549c75cc2e 100644 --- a/stdlib/statistics.pyi +++ b/stdlib/statistics.pyi @@ -2,11 +2,11 @@ import sys from _typeshed import SupportsRichComparisonT from decimal import Decimal from fractions import Fraction -from typing import Any, Hashable, Iterable, NamedTuple, Sequence, SupportsFloat, Type, TypeVar, Union +from typing import Any, Hashable, Iterable, NamedTuple, Sequence, SupportsFloat, Type, TypeVar _T = TypeVar("_T") # Most functions in this module accept homogeneous collections of one of these types -_Number = Union[float, Decimal, Fraction] +_Number = float | Decimal | Fraction _NumberT = TypeVar("_NumberT", float, Decimal, Fraction) # Used in mode, multimode diff --git a/stdlib/subprocess.pyi b/stdlib/subprocess.pyi index fce517745ee6..6ca52d5eab18 100644 --- a/stdlib/subprocess.pyi +++ b/stdlib/subprocess.pyi @@ -22,17 +22,17 @@ if sys.version_info >= (3, 9): # except TimeoutError as e: # reveal_type(e.cmd) # Any, but morally is _CMD _FILE = Union[None, int, IO[Any]] -_TXT = Union[bytes, str] +_TXT = bytes | str if sys.version_info >= (3, 8): - _CMD = Union[StrOrBytesPath, Sequence[StrOrBytesPath]] + _CMD = StrOrBytesPath | Sequence[StrOrBytesPath] else: # Python 3.6 doesn't support _CMD being a single PathLike. # See: https://bugs.python.org/issue31961 - _CMD = Union[_TXT, Sequence[StrOrBytesPath]] + _CMD = _TXT | Sequence[StrOrBytesPath] if sys.platform == "win32": _ENV = Mapping[str, str] else: - _ENV = Union[Mapping[bytes, StrOrBytesPath], Mapping[str, StrOrBytesPath]] + _ENV = Mapping[bytes, StrOrBytesPath] | Mapping[str, StrOrBytesPath] _T = TypeVar("_T") diff --git a/stdlib/sunau.pyi b/stdlib/sunau.pyi index 8393136aa795..9673ab473421 100644 --- a/stdlib/sunau.pyi +++ b/stdlib/sunau.pyi @@ -1,8 +1,8 @@ import sys from _typeshed import Self -from typing import IO, Any, NamedTuple, NoReturn, Union +from typing import IO, Any, NamedTuple, NoReturn -_File = Union[str, IO[bytes]] +_File = str | IO[bytes] class Error(Exception): ... diff --git a/stdlib/sys.pyi b/stdlib/sys.pyi index 274e4b90fd6e..d060375467fe 100644 --- a/stdlib/sys.pyi +++ b/stdlib/sys.pyi @@ -4,28 +4,14 @@ from importlib.abc import PathEntryFinder from importlib.machinery import ModuleSpec from io import TextIOWrapper from types import FrameType, ModuleType, TracebackType -from typing import ( - Any, - AsyncGenerator, - Callable, - NoReturn, - Optional, - Protocol, - Sequence, - TextIO, - Tuple, - Type, - TypeVar, - Union, - overload, -) +from typing import Any, AsyncGenerator, Callable, NoReturn, Protocol, Sequence, TextIO, Tuple, Type, TypeVar, overload from typing_extensions import Literal _T = TypeVar("_T") # The following type alias are stub-only and do not exist during runtime _ExcInfo = Tuple[Type[BaseException], BaseException, TracebackType] -_OptExcInfo = Union[_ExcInfo, Tuple[None, None, None]] +_OptExcInfo = _ExcInfo | Tuple[None, None, None] # Intentionally omits one deprecated and one optional method of `importlib.abc.MetaPathFinder` class _MetaPathFinder(Protocol): @@ -187,7 +173,7 @@ _ProfileFunc = Callable[[FrameType, str, Any], Any] def getprofile() -> _ProfileFunc | None: ... def setprofile(profilefunc: _ProfileFunc | None) -> None: ... -_TraceFunc = Callable[[FrameType, str, Any], Optional[Callable[[FrameType, str, Any], Any]]] +_TraceFunc = Callable[[FrameType, str, Any], Callable[[FrameType, str, Any], Any] | None] def gettrace() -> _TraceFunc | None: ... def settrace(tracefunc: _TraceFunc | None) -> None: ... @@ -237,7 +223,7 @@ if sys.version_info >= (3, 8): def addaudithook(hook: Callable[[str, Tuple[Any, ...]], Any]) -> None: ... def audit(__event: str, *args: Any) -> None: ... -_AsyncgenHook = Optional[Callable[[AsyncGenerator[Any, Any]], None]] +_AsyncgenHook = Callable[[AsyncGenerator[Any, Any]], None] | None class _asyncgen_hooks(Tuple[_AsyncgenHook, _AsyncgenHook]): firstiter: _AsyncgenHook diff --git a/stdlib/termios.pyi b/stdlib/termios.pyi index ed8522dccc51..d9c7fb8cd697 100644 --- a/stdlib/termios.pyi +++ b/stdlib/termios.pyi @@ -1,7 +1,7 @@ from _typeshed import FileDescriptorLike -from typing import Any, List, Union +from typing import Any, List -_Attr = List[Union[int, List[Union[bytes, int]]]] +_Attr = List[int | List[bytes | int]] # TODO constants not really documented B0: int diff --git a/stdlib/threading.pyi b/stdlib/threading.pyi index d6ac9f7251c2..63f33e0518cb 100644 --- a/stdlib/threading.pyi +++ b/stdlib/threading.pyi @@ -1,9 +1,9 @@ import sys from types import FrameType, TracebackType -from typing import Any, Callable, Iterable, Mapping, Optional, Type, TypeVar +from typing import Any, Callable, Iterable, Mapping, Type, TypeVar # TODO recursive type -_TF = Callable[[FrameType, str, Any], Optional[Callable[..., Any]]] +_TF = Callable[[FrameType, str, Any], Callable[..., Any] | None] _PF = Callable[[FrameType, str, Any], None] _T = TypeVar("_T") diff --git a/stdlib/timeit.pyi b/stdlib/timeit.pyi index d82dd80598dc..7d85942ddd37 100644 --- a/stdlib/timeit.pyi +++ b/stdlib/timeit.pyi @@ -1,7 +1,7 @@ -from typing import IO, Any, Callable, Sequence, Union +from typing import IO, Any, Callable, Sequence _Timer = Callable[[], float] -_Stmt = Union[str, Callable[[], Any]] +_Stmt = str | Callable[[], Any] default_timer: _Timer diff --git a/stdlib/tkinter/font.pyi b/stdlib/tkinter/font.pyi index fccc0fbf1f0a..a313b05b97e6 100644 --- a/stdlib/tkinter/font.pyi +++ b/stdlib/tkinter/font.pyi @@ -1,7 +1,7 @@ import _tkinter import sys import tkinter -from typing import Any, List, Tuple, Union, overload +from typing import Any, List, Tuple, overload from typing_extensions import Literal, TypedDict NORMAL: Literal["normal"] @@ -9,17 +9,17 @@ ROMAN: Literal["roman"] BOLD: Literal["bold"] ITALIC: Literal["italic"] -_FontDescription = Union[ +_FontDescription = ( # "Helvetica 12" - str, + str # A font object constructed in Python - Font, + | Font # ("Helvetica", 12, BOLD) - List[Any], - Tuple[Any, ...], + | List[Any] + | Tuple[Any, ...] # A font object constructed in Tcl - _tkinter.Tcl_Obj, -] + | _tkinter.Tcl_Obj +) class _FontDict(TypedDict): family: str diff --git a/stdlib/tkinter/ttk.pyi b/stdlib/tkinter/ttk.pyi index 0cb806fddd52..a03fe5c20e1e 100644 --- a/stdlib/tkinter/ttk.pyi +++ b/stdlib/tkinter/ttk.pyi @@ -2,7 +2,7 @@ import _tkinter import sys import tkinter from tkinter.font import _FontDescription -from typing import Any, Callable, Tuple, Union, overload +from typing import Any, Callable, Tuple, overload from typing_extensions import Literal, TypedDict def tclobjs_to_py(adict): ... @@ -914,7 +914,7 @@ class _TreeviewColumnDict(TypedDict): anchor: tkinter._Anchor id: str -_TreeviewColumnId = Union[int, str] # manual page: "COLUMN IDENTIFIERS" +_TreeviewColumnId = int | str # manual page: "COLUMN IDENTIFIERS" class Treeview(Widget, tkinter.XView, tkinter.YView): def __init__( diff --git a/stdlib/tokenize.pyi b/stdlib/tokenize.pyi index a8294adb653f..91e661912908 100644 --- a/stdlib/tokenize.pyi +++ b/stdlib/tokenize.pyi @@ -2,7 +2,7 @@ import sys from _typeshed import StrOrBytesPath from builtins import open as _builtin_open from token import * # noqa: F403 -from typing import Any, Callable, Generator, Iterable, NamedTuple, Pattern, Sequence, TextIO, Tuple, Union +from typing import Any, Callable, Generator, Iterable, NamedTuple, Pattern, Sequence, TextIO, Tuple if sys.version_info < (3, 7): COMMENT: int @@ -26,7 +26,7 @@ class TokenInfo(_TokenInfo): def exact_type(self) -> int: ... # Backwards compatible tokens can be sequences of a shorter length too -_Token = Union[TokenInfo, Sequence[Union[int, str, _Position]]] +_Token = TokenInfo | Sequence[int | str | _Position] class TokenError(Exception): ... class StopTokenizing(Exception): ... # undocumented diff --git a/stdlib/trace.pyi b/stdlib/trace.pyi index bab75c9ada8d..34ba0eccbbaa 100644 --- a/stdlib/trace.pyi +++ b/stdlib/trace.pyi @@ -1,13 +1,13 @@ import sys import types from _typeshed import StrPath -from typing import Any, Callable, Mapping, Optional, Sequence, Tuple, TypeVar +from typing import Any, Callable, Mapping, Sequence, Tuple, TypeVar from typing_extensions import ParamSpec _T = TypeVar("_T") _P = ParamSpec("_P") _localtrace = Callable[[types.FrameType, str, Any], Callable[..., Any]] -_fileModuleFunction = Tuple[str, Optional[str], str] +_fileModuleFunction = Tuple[str, str | None, str] class CoverageResults: def __init__( diff --git a/stdlib/traceback.pyi b/stdlib/traceback.pyi index f09a3cc70ade..c70103eb88b1 100644 --- a/stdlib/traceback.pyi +++ b/stdlib/traceback.pyi @@ -1,9 +1,9 @@ import sys from _typeshed import SupportsWrite from types import FrameType, TracebackType -from typing import IO, Any, Generator, Iterable, Iterator, List, Mapping, Optional, Tuple, Type, overload +from typing import IO, Any, Generator, Iterable, Iterator, List, Mapping, Tuple, Type, overload -_PT = Tuple[str, int, str, Optional[str]] +_PT = Tuple[str, int, str, str | None] def print_tb(tb: TracebackType | None, limit: int | None = ..., file: IO[str] | None = ...) -> None: ... diff --git a/stdlib/tracemalloc.pyi b/stdlib/tracemalloc.pyi index 4666bd1565a0..3a0c02e21dec 100644 --- a/stdlib/tracemalloc.pyi +++ b/stdlib/tracemalloc.pyi @@ -1,6 +1,6 @@ import sys from _tracemalloc import * -from typing import Optional, Sequence, Tuple, Union, overload +from typing import Optional, Sequence, Tuple, overload from typing_extensions import SupportsIndex def get_object_traceback(obj: object) -> Traceback | None: ... @@ -43,7 +43,7 @@ class Frame: def __init__(self, frame: _FrameTupleT) -> None: ... if sys.version_info >= (3, 9): - _TraceTupleT = Union[Tuple[int, int, Sequence[_FrameTupleT], Optional[int]], Tuple[int, int, Sequence[_FrameTupleT]]] + _TraceTupleT = Tuple[int, int, Sequence[_FrameTupleT], Optional[int]] | Tuple[int, int, Sequence[_FrameTupleT]] else: _TraceTupleT = Tuple[int, int, Sequence[_FrameTupleT]] diff --git a/stdlib/tty.pyi b/stdlib/tty.pyi index c0dc418e9933..c25f22a5a4ff 100644 --- a/stdlib/tty.pyi +++ b/stdlib/tty.pyi @@ -1,6 +1,6 @@ -from typing import IO, Union +from typing import IO -_FD = Union[int, IO[str]] +_FD = int | IO[str] # XXX: Undocumented integer constants IFLAG: int diff --git a/stdlib/turtle.pyi b/stdlib/turtle.pyi index 8542fc8bfa24..b8919882c44d 100644 --- a/stdlib/turtle.pyi +++ b/stdlib/turtle.pyi @@ -1,17 +1,17 @@ from tkinter import Canvas, Frame, PhotoImage -from typing import Any, Callable, ClassVar, Dict, Sequence, Tuple, TypeVar, Union, overload +from typing import Any, Callable, ClassVar, Dict, Sequence, Tuple, TypeVar, overload # Note: '_Color' is the alias we use for arguments and _AnyColor is the # 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 = Union[str, Tuple[float, float, float]] +_Color = str | Tuple[float, float, float] _AnyColor = Any # TODO: Replace this with a TypedDict once it becomes standardized. _PenState = Dict[str, Any] -_Speed = Union[str, float] +_Speed = str | float _PolygonCoords = Sequence[Tuple[float, float]] # TODO: Type this more accurately diff --git a/stdlib/unittest/result.pyi b/stdlib/unittest/result.pyi index 20c43cf38aa4..427b059f0c7d 100644 --- a/stdlib/unittest/result.pyi +++ b/stdlib/unittest/result.pyi @@ -1,8 +1,8 @@ import unittest.case from types import TracebackType -from typing import Any, Callable, TextIO, Tuple, Type, TypeVar, Union +from typing import Any, Callable, TextIO, Tuple, Type, TypeVar -_SysExcInfoType = Union[Tuple[Type[BaseException], BaseException, TracebackType], Tuple[None, None, None]] +_SysExcInfoType = Tuple[Type[BaseException], BaseException, TracebackType] | Tuple[None, None, None] _F = TypeVar("_F", bound=Callable[..., Any]) diff --git a/stdlib/unittest/suite.pyi b/stdlib/unittest/suite.pyi index 396b46eadf5a..3d7f87c9b20f 100644 --- a/stdlib/unittest/suite.pyi +++ b/stdlib/unittest/suite.pyi @@ -1,8 +1,8 @@ import unittest.case import unittest.result -from typing import Iterable, Iterator, Union +from typing import Iterable, Iterator -_TestType = Union[unittest.case.TestCase, TestSuite] +_TestType = unittest.case.TestCase | TestSuite class BaseTestSuite(Iterable[_TestType]): _tests: list[unittest.case.TestCase] diff --git a/stdlib/urllib/parse.pyi b/stdlib/urllib/parse.pyi index a2467e96c43c..43bd991eb8eb 100644 --- a/stdlib/urllib/parse.pyi +++ b/stdlib/urllib/parse.pyi @@ -1,10 +1,10 @@ import sys -from typing import Any, AnyStr, Callable, Generic, Mapping, NamedTuple, Sequence, Tuple, Union, overload +from typing import Any, AnyStr, Callable, Generic, Mapping, NamedTuple, Sequence, Tuple, overload if sys.version_info >= (3, 9): from types import GenericAlias -_Str = Union[bytes, str] +_Str = bytes | str uses_relative: list[str] uses_netloc: list[str] diff --git a/stdlib/uu.pyi b/stdlib/uu.pyi index aacd458c02c7..3687a843d39d 100644 --- a/stdlib/uu.pyi +++ b/stdlib/uu.pyi @@ -1,7 +1,7 @@ import sys -from typing import BinaryIO, Union +from typing import BinaryIO -_File = Union[str, BinaryIO] +_File = str | BinaryIO class Error(Exception): ... diff --git a/stdlib/wave.pyi b/stdlib/wave.pyi index 3ce1b88a6835..aef20986572a 100644 --- a/stdlib/wave.pyi +++ b/stdlib/wave.pyi @@ -1,8 +1,8 @@ import sys from _typeshed import Self -from typing import IO, Any, BinaryIO, NamedTuple, NoReturn, Union +from typing import IO, Any, BinaryIO, NamedTuple, NoReturn -_File = Union[str, IO[bytes]] +_File = str | IO[bytes] class Error(Exception): ... diff --git a/stdlib/winreg.pyi b/stdlib/winreg.pyi index 5fff1104e246..13f784111554 100644 --- a/stdlib/winreg.pyi +++ b/stdlib/winreg.pyi @@ -1,9 +1,9 @@ from _typeshed import Self from types import TracebackType -from typing import Any, Type, Union +from typing import Any, Type from typing_extensions import final -_KeyType = Union[HKEYType, int] +_KeyType = HKEYType | int def CloseKey(__hkey: _KeyType) -> None: ... def ConnectRegistry(__computer_name: str | None, __key: _KeyType) -> HKEYType: ... diff --git a/stdlib/wsgiref/handlers.pyi b/stdlib/wsgiref/handlers.pyi index ac1e56b7664e..3e79b7b682b9 100644 --- a/stdlib/wsgiref/handlers.pyi +++ b/stdlib/wsgiref/handlers.pyi @@ -1,12 +1,12 @@ from abc import abstractmethod from types import TracebackType -from typing import IO, Callable, MutableMapping, Optional, Tuple, Type +from typing import IO, Callable, MutableMapping, Tuple, Type from .headers import Headers from .types import ErrorStream, InputStream, StartResponse, WSGIApplication, WSGIEnvironment from .util import FileWrapper -_exc_info = Tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]] +_exc_info = Tuple[Type[BaseException] | None, BaseException | None, TracebackType | None] def format_date_time(timestamp: float | None) -> str: ... # undocumented def read_environ() -> dict[str, str]: ... diff --git a/stdlib/xml/dom/pulldom.pyi b/stdlib/xml/dom/pulldom.pyi index 530c1988e743..72399ff261b0 100644 --- a/stdlib/xml/dom/pulldom.pyi +++ b/stdlib/xml/dom/pulldom.pyi @@ -1,5 +1,5 @@ import sys -from typing import IO, Any, Sequence, Tuple, Union +from typing import IO, Any, Sequence, Tuple from typing_extensions import Literal from xml.dom.minidom import Document, DOMImplementation, Element, Text from xml.sax.handler import ContentHandler @@ -14,8 +14,8 @@ PROCESSING_INSTRUCTION: Literal["PROCESSING_INSTRUCTION"] IGNORABLE_WHITESPACE: Literal["IGNORABLE_WHITESPACE"] CHARACTERS: Literal["CHARACTERS"] -_DocumentFactory = Union[DOMImplementation, None] -_Node = Union[Document, Element, Text] +_DocumentFactory = DOMImplementation | None +_Node = Document | Element | Text _Event = Tuple[ Literal[ diff --git a/stdlib/xml/dom/xmlbuilder.pyi b/stdlib/xml/dom/xmlbuilder.pyi index 2738d735e73f..5792842eaf9d 100644 --- a/stdlib/xml/dom/xmlbuilder.pyi +++ b/stdlib/xml/dom/xmlbuilder.pyi @@ -1,4 +1,4 @@ -from typing import Any, NoReturn, Optional +from typing import Any, NoReturn from typing_extensions import Literal from urllib.request import OpenerDirector from xml.dom.expatbuilder import ExpatBuilder, ExpatBuilderNS @@ -16,13 +16,13 @@ from xml.dom.minidom import Node # probably the same as `Options.errorHandler`? # Maybe `xml.sax.handler.ErrorHandler`? -_DOMBuilderErrorHandlerType = Optional[Any] +_DOMBuilderErrorHandlerType = Any | None # probably some kind of IO... -_DOMInputSourceCharacterStreamType = Optional[Any] +_DOMInputSourceCharacterStreamType = Any | None # probably a string?? -_DOMInputSourceStringDataType = Optional[Any] +_DOMInputSourceStringDataType = Any | None # probably a string?? -_DOMInputSourceEncodingType = Optional[Any] +_DOMInputSourceEncodingType = Any | None class Options: namespaces: int diff --git a/stdlib/xml/etree/ElementTree.pyi b/stdlib/xml/etree/ElementTree.pyi index 6ee578b9aa81..108654970e02 100644 --- a/stdlib/xml/etree/ElementTree.pyi +++ b/stdlib/xml/etree/ElementTree.pyi @@ -14,13 +14,12 @@ from typing import ( MutableSequence, Sequence, TypeVar, - Union, overload, ) from typing_extensions import Literal, SupportsIndex _T = TypeVar("_T") -_File = Union[StrOrBytesPath, FileDescriptor, IO[Any]] +_File = StrOrBytesPath | FileDescriptor | IO[Any] VERSION: str diff --git a/stdlib/xmlrpc/client.pyi b/stdlib/xmlrpc/client.pyi index b715e8b2928a..3fc47bed1a27 100644 --- a/stdlib/xmlrpc/client.pyi +++ b/stdlib/xmlrpc/client.pyi @@ -12,10 +12,10 @@ from typing_extensions import Literal class _SupportsTimeTuple(Protocol): def timetuple(self) -> time.struct_time: ... -_DateTimeComparable = Union[DateTime, datetime, str, _SupportsTimeTuple] +_DateTimeComparable = DateTime | datetime | str | _SupportsTimeTuple _Marshallable = Union[None, bool, int, float, str, bytes, Tuple[Any, ...], List[Any], Dict[Any, Any], datetime, DateTime, Binary] -_XMLDate = Union[int, datetime, Tuple[int, ...], time.struct_time] -_HostType = Union[Tuple[str, Dict[str, str]], str] +_XMLDate = int | datetime | Tuple[int, ...] | time.struct_time +_HostType = Tuple[str, Dict[str, str]] | str def escape(s: str) -> str: ... # undocumented diff --git a/stdlib/xmlrpc/server.pyi b/stdlib/xmlrpc/server.pyi index f84253cef568..a7a405b9e7f7 100644 --- a/stdlib/xmlrpc/server.pyi +++ b/stdlib/xmlrpc/server.pyi @@ -30,7 +30,7 @@ class _DispatchArity4(Protocol): class _DispatchArityN(Protocol): def __call__(self, *args: _Marshallable) -> _Marshallable: ... -_DispatchProtocol = Union[_DispatchArity0, _DispatchArity1, _DispatchArity2, _DispatchArity3, _DispatchArity4, _DispatchArityN] +_DispatchProtocol = _DispatchArity0 | _DispatchArity1 | _DispatchArity2 | _DispatchArity3 | _DispatchArity4 | _DispatchArityN def resolve_dotted_attribute(obj: Any, attr: str, allow_dotted_names: bool = ...) -> Any: ... # undocumented def list_public_methods(obj: Any) -> list[str]: ... # undocumented diff --git a/stdlib/zipapp.pyi b/stdlib/zipapp.pyi index 581d2b72a664..4ed6cf5d0a0a 100644 --- a/stdlib/zipapp.pyi +++ b/stdlib/zipapp.pyi @@ -1,8 +1,8 @@ import sys from pathlib import Path -from typing import BinaryIO, Callable, Union +from typing import BinaryIO, Callable -_Path = Union[str, Path, BinaryIO] +_Path = str | Path | BinaryIO class ZipAppError(ValueError): ... diff --git a/stubs/Pillow/PIL/Image.pyi b/stubs/Pillow/PIL/Image.pyi index 4d7113496b60..b341034b77c9 100644 --- a/stubs/Pillow/PIL/Image.pyi +++ b/stubs/Pillow/PIL/Image.pyi @@ -1,7 +1,7 @@ from _typeshed import SupportsRead, SupportsWrite from collections.abc import Iterable, Iterator, MutableMapping from pathlib import Path -from typing import Any, Callable, Dict, Protocol, Sequence, SupportsBytes, Tuple, Union +from typing import Any, Callable, Dict, Protocol, Sequence, SupportsBytes, Tuple from typing_extensions import Literal from ._imaging import ( @@ -19,10 +19,10 @@ _Resample = Literal[0, 1, 2, 3, 4, 5] _Size = Tuple[int, int] _Box = Tuple[int, int, int, int] -_ConversionMatrix = Union[ - Tuple[float, float, float, float], Tuple[float, float, float, float, float, float, float, float, float, float, float, float], -] -_Color = Union[float, Tuple[float, ...]] +_ConversionMatrix = ( + Tuple[float, float, float, float] | Tuple[float, float, float, float, float, float, float, float, float, float, float, float] +) +_Color = 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 8e0db5292296..59a5dc8505d8 100644 --- a/stubs/Pillow/PIL/ImageColor.pyi +++ b/stubs/Pillow/PIL/ImageColor.pyi @@ -1,7 +1,7 @@ -from typing import Tuple, Union +from typing import Tuple -_RGB = Union[Tuple[int, int, int], Tuple[int, int, int, int]] -_Ink = Union[str, int, _RGB] +_RGB = Tuple[int, int, int] | Tuple[int, int, int, int] +_Ink = str | int | _RGB _GreyScale = Tuple[int, int] def getrgb(color: _Ink) -> _RGB: ... diff --git a/stubs/Pillow/PIL/ImageDraw.pyi b/stubs/Pillow/PIL/ImageDraw.pyi index 5ca32e3b3c8f..dc357db6a97a 100644 --- a/stubs/Pillow/PIL/ImageDraw.pyi +++ b/stubs/Pillow/PIL/ImageDraw.pyi @@ -1,12 +1,12 @@ from collections.abc import Container -from typing import Any, Sequence, Tuple, Union, overload +from typing import Any, Sequence, Tuple, overload from typing_extensions import Literal from .Image import Image from .ImageColor import _Ink from .ImageFont import _Font -_XY = Sequence[Union[float, Tuple[float, float]]] +_XY = Sequence[float | Tuple[float, float]] _Outline = Any class ImageDraw: diff --git a/stubs/Pillow/PIL/TiffTags.pyi b/stubs/Pillow/PIL/TiffTags.pyi index 5559e169bd5c..57ef38add890 100644 --- a/stubs/Pillow/PIL/TiffTags.pyi +++ b/stubs/Pillow/PIL/TiffTags.pyi @@ -1,4 +1,4 @@ -from typing import Any, Dict, NamedTuple, Tuple, Union +from typing import Any, Dict, NamedTuple, Tuple from typing_extensions import Literal class _TagInfo(NamedTuple): @@ -36,7 +36,7 @@ DOUBLE: Literal[12] IFD: Literal[13] _TagType = Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] -_TagTuple = Union[Tuple[str, _TagType, int], Tuple[str, _TagInfo, int, Dict[str, int]]] +_TagTuple = 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/PyMySQL/pymysql/converters.pyi b/stubs/PyMySQL/pymysql/converters.pyi index ee2e4ba89aaa..f440d8887320 100644 --- a/stubs/PyMySQL/pymysql/converters.pyi +++ b/stubs/PyMySQL/pymysql/converters.pyi @@ -2,9 +2,9 @@ import datetime import time from collections.abc import Callable, Mapping, Sequence from decimal import Decimal -from typing import Any, Optional, Type, TypeVar +from typing import Any, Type, TypeVar -_EscaperMapping = Optional[Mapping[Type[object], Callable[..., str]]] +_EscaperMapping = Mapping[Type[object], Callable[..., str]] | None _T = TypeVar("_T") def escape_item(val: object, charset: object, mapping: _EscaperMapping = ...) -> str: ... diff --git a/stubs/PyYAML/yaml/constructor.pyi b/stubs/PyYAML/yaml/constructor.pyi index e503cba6949a..c030cd23a2bb 100644 --- a/stubs/PyYAML/yaml/constructor.pyi +++ b/stubs/PyYAML/yaml/constructor.pyi @@ -1,9 +1,9 @@ -from typing import Any, Pattern, Union +from typing import Any, Pattern from yaml.error import MarkedYAMLError from yaml.nodes import ScalarNode -_Scalar = Union[str, int, float, bool, None] +_Scalar = str | int | float | bool | None class ConstructorError(MarkedYAMLError): ... diff --git a/stubs/PyYAML/yaml/cyaml.pyi b/stubs/PyYAML/yaml/cyaml.pyi index d70b44148bec..74946311ec94 100644 --- a/stubs/PyYAML/yaml/cyaml.pyi +++ b/stubs/PyYAML/yaml/cyaml.pyi @@ -1,6 +1,6 @@ from _typeshed import SupportsRead from collections.abc import Mapping, Sequence -from typing import IO, Any, Union +from typing import IO, Any from ._yaml import CEmitter, CParser from .constructor import BaseConstructor, FullConstructor, SafeConstructor, UnsafeConstructor @@ -9,7 +9,7 @@ from .resolver import BaseResolver, Resolver __all__ = ["CBaseLoader", "CSafeLoader", "CFullLoader", "CUnsafeLoader", "CLoader", "CBaseDumper", "CSafeDumper", "CDumper"] -_Readable = SupportsRead[Union[str, bytes]] +_Readable = SupportsRead[str | bytes] class CBaseLoader(CParser, BaseConstructor, BaseResolver): def __init__(self, stream: str | bytes | _Readable) -> None: ... diff --git a/stubs/Pygments/pygments/lexers/__init__.pyi b/stubs/Pygments/pygments/lexers/__init__.pyi index 23a2966c3890..7f53a1b9ff79 100644 --- a/stubs/Pygments/pygments/lexers/__init__.pyi +++ b/stubs/Pygments/pygments/lexers/__init__.pyi @@ -1,10 +1,10 @@ from _typeshed import StrOrBytesPath, StrPath from collections.abc import Iterator -from typing import Any, Tuple, Union +from typing import Any, Tuple from pygments.lexer import Lexer, LexerMeta -_OpenFile = Union[StrOrBytesPath, int] # copy/pasted from builtins.pyi +_OpenFile = StrOrBytesPath | int # copy/pasted from builtins.pyi # TODO: use lower-case tuple once mypy updated def get_all_lexers() -> Iterator[tuple[str, Tuple[str, ...], Tuple[str, ...], Tuple[str, ...]]]: ... diff --git a/stubs/aiofiles/aiofiles/os.pyi b/stubs/aiofiles/aiofiles/os.pyi index b48884c4430e..73bbaa1ab7fb 100644 --- a/stubs/aiofiles/aiofiles/os.pyi +++ b/stubs/aiofiles/aiofiles/os.pyi @@ -1,9 +1,9 @@ import sys from _typeshed import StrOrBytesPath from os import stat_result -from typing import Sequence, Union, overload +from typing import Sequence, overload -_FdOrAnyPath = Union[int, StrOrBytesPath] +_FdOrAnyPath = int | StrOrBytesPath async def stat(path: _FdOrAnyPath, *, dir_fd: int | None = ..., follow_symlinks: bool = ...) -> stat_result: ... async def rename( diff --git a/stubs/aiofiles/aiofiles/threadpool/__init__.pyi b/stubs/aiofiles/aiofiles/threadpool/__init__.pyi index a43b5ab0defb..47fc9a429275 100644 --- a/stubs/aiofiles/aiofiles/threadpool/__init__.pyi +++ b/stubs/aiofiles/aiofiles/threadpool/__init__.pyi @@ -7,14 +7,14 @@ from _typeshed import ( StrOrBytesPath, ) from asyncio import AbstractEventLoop -from typing import Any, Callable, Union, overload +from typing import Any, Callable, overload from typing_extensions import Literal from ..base import AiofilesContextManager from .binary import AsyncBufferedIOBase, AsyncBufferedReader, AsyncFileIO, _UnknownAsyncBinaryIO from .text import AsyncTextIOWrapper -_OpenFile = Union[StrOrBytesPath, int] +_OpenFile = StrOrBytesPath | int _Opener = Callable[[str, int], int] # Text mode: always returns AsyncTextIOWrapper diff --git a/stubs/beautifulsoup4/bs4/element.pyi b/stubs/beautifulsoup4/bs4/element.pyi index 9e7b2d1c2a35..eb7fe47bc5ea 100644 --- a/stubs/beautifulsoup4/bs4/element.pyi +++ b/stubs/beautifulsoup4/bs4/element.pyi @@ -1,6 +1,6 @@ from _typeshed import Self from collections.abc import Iterator -from typing import Any, Callable, Generic, Iterable, List, Mapping, Pattern, Tuple, Type, TypeVar, Union, overload +from typing import Any, Callable, Generic, Iterable, List, Mapping, Pattern, Tuple, Type, TypeVar, overload from . import BeautifulSoup from .builder import TreeBuilder @@ -28,10 +28,10 @@ class ContentMetaAttributeValue(AttributeValueWithCharsetSubstitution): _PageElementT = TypeVar("_PageElementT", bound=PageElement) # The wrapping Union[] can be removed once mypy fully supports | in type aliases. -_SimpleStrainable = Union[str, bool, None, bytes, Pattern[str], Callable[[str], bool], Callable[[Tag], bool]] -_Strainable = Union[_SimpleStrainable, Iterable[_SimpleStrainable]] -_SimpleNormalizedStrainable = Union[str, bool, None, Pattern[str], Callable[[str], bool], Callable[[Tag], bool]] -_NormalizedStrainable = Union[_SimpleNormalizedStrainable, Iterable[_SimpleNormalizedStrainable]] +_SimpleStrainable = str | bool | None | bytes | Pattern[str] | Callable[[str], bool] | Callable[[Tag], bool] +_Strainable = _SimpleStrainable | Iterable[_SimpleStrainable] +_SimpleNormalizedStrainable = str | bool | None | Pattern[str] | Callable[[str], bool] | Callable[[Tag], bool] +_NormalizedStrainable = _SimpleNormalizedStrainable | Iterable[_SimpleNormalizedStrainable] class PageElement: parent: Tag | None diff --git a/stubs/bleach/bleach/sanitizer.pyi b/stubs/bleach/bleach/sanitizer.pyi index 0966af2096d6..c6b5d1be7ad7 100644 --- a/stubs/bleach/bleach/sanitizer.pyi +++ b/stubs/bleach/bleach/sanitizer.pyi @@ -1,5 +1,5 @@ from collections.abc import Callable, Container, Iterable -from typing import Any, Dict, List, Pattern, Union +from typing import Any, Dict, List, Pattern from .html5lib_shim import BleachHTMLParser, BleachHTMLSerializer, SanitizerFilter @@ -39,8 +39,8 @@ class Cleaner(object): def clean(self, text: str) -> str: ... _AttributeFilter = Callable[[str, str, str], bool] -_AttributeDict = Union[Dict[str, Union[List[str], _AttributeFilter]], Dict[str, List[str]], Dict[str, _AttributeFilter]] -_Attributes = Union[_AttributeFilter, _AttributeDict, List[str]] +_AttributeDict = Dict[str, List[str] | _AttributeFilter] | Dict[str, List[str]] | Dict[str, _AttributeFilter] +_Attributes = _AttributeFilter | _AttributeDict | List[str] def attribute_filter_factory(attributes: _Attributes) -> _AttributeFilter: ... diff --git a/stubs/colorama/colorama/ansitowin32.pyi b/stubs/colorama/colorama/ansitowin32.pyi index 117fe8f6265c..17de1c1358d0 100644 --- a/stubs/colorama/colorama/ansitowin32.pyi +++ b/stubs/colorama/colorama/ansitowin32.pyi @@ -1,6 +1,6 @@ import sys from _typeshed import SupportsWrite -from typing import Any, Callable, Dict, Optional, Pattern, Sequence, TextIO, Tuple, Union +from typing import Any, Callable, Dict, Pattern, Sequence, TextIO, Tuple if sys.platform == "win32": from .winterm import WinTerm @@ -19,8 +19,8 @@ class StreamWrapper: @property def closed(self) -> bool: ... -_WinTermCall = Callable[[Optional[int], bool, bool], None] -_WinTermCallDict = Dict[int, Union[Tuple[_WinTermCall], Tuple[_WinTermCall, int], Tuple[_WinTermCall, int, bool]]] +_WinTermCall = Callable[[int | None, bool, bool], None] +_WinTermCallDict = Dict[int, Tuple[_WinTermCall] | Tuple[_WinTermCall, int] | Tuple[_WinTermCall, int, bool]] class AnsiToWin32: ANSI_CSI_RE: Pattern[str] = ... diff --git a/stubs/croniter/croniter.pyi b/stubs/croniter/croniter.pyi index 820e0ee50a42..68d0969f9123 100644 --- a/stubs/croniter/croniter.pyi +++ b/stubs/croniter/croniter.pyi @@ -1,8 +1,8 @@ import datetime -from typing import Any, Iterator, Text, Tuple, Type, TypeVar, Union +from typing import Any, Iterator, Text, Tuple, Type, TypeVar from typing_extensions import Literal -_RetType = Union[Type[float], Type[datetime.datetime]] +_RetType = Type[float] | Type[datetime.datetime] _SelfT = TypeVar("_SelfT", bound=croniter) class CroniterError(ValueError): ... diff --git a/stubs/docopt/docopt.pyi b/stubs/docopt/docopt.pyi index 7f7bba6a7e69..d3774d4c558c 100644 --- a/stubs/docopt/docopt.pyi +++ b/stubs/docopt/docopt.pyi @@ -1,8 +1,8 @@ -from typing import Any, Iterable, Union +from typing import Any, Iterable __version__: str -_Argv = Union[Iterable[str], str] +_Argv = Iterable[str] | str def docopt( doc: str, argv: _Argv | None = ..., help: bool = ..., version: Any | None = ..., options_first: bool = ... diff --git a/stubs/freezegun/freezegun/api.pyi b/stubs/freezegun/freezegun/api.pyi index d2aaaf4a19ea..e1b8757fd004 100644 --- a/stubs/freezegun/freezegun/api.pyi +++ b/stubs/freezegun/freezegun/api.pyi @@ -1,10 +1,10 @@ from collections.abc import Awaitable, Callable, Iterator, Sequence from datetime import date, datetime, timedelta from numbers import Real -from typing import Any, Type, TypeVar, Union, overload +from typing import Any, Type, TypeVar, overload _T = TypeVar("_T") -_Freezable = Union[str, datetime, date, timedelta] +_Freezable = str | datetime | date | timedelta class TickingDateTimeFactory(object): def __init__(self, time_to_freeze: datetime, start: datetime) -> None: ... diff --git a/stubs/paramiko/paramiko/common.pyi b/stubs/paramiko/paramiko/common.pyi index 26c09d4f3e40..e5e6da5a99c4 100644 --- a/stubs/paramiko/paramiko/common.pyi +++ b/stubs/paramiko/paramiko/common.pyi @@ -1,5 +1,5 @@ import sys -from typing import Protocol, Text, Union +from typing import Protocol, Text MSG_DISCONNECT: int MSG_IGNORE: int @@ -109,7 +109,7 @@ else: class _SupportsAsBytes(Protocol): def asbytes(self) -> bytes: ... -_LikeBytes = Union[bytes, Text, _SupportsAsBytes] +_LikeBytes = bytes | Text | _SupportsAsBytes def asbytes(s: _LikeBytes) -> bytes: ... diff --git a/stubs/pyOpenSSL/OpenSSL/crypto.pyi b/stubs/pyOpenSSL/OpenSSL/crypto.pyi index abfb1e3ab85d..adad55c91c68 100644 --- a/stubs/pyOpenSSL/OpenSSL/crypto.pyi +++ b/stubs/pyOpenSSL/OpenSSL/crypto.pyi @@ -1,11 +1,11 @@ from datetime import datetime -from typing import Any, Callable, Iterable, Sequence, Text, Tuple, Union +from typing import Any, Callable, Iterable, Sequence, Text, Tuple from cryptography.hazmat.primitives.asymmetric.dsa import DSAPrivateKey, DSAPublicKey from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey, RSAPublicKey from cryptography.x509 import Certificate, CertificateRevocationList, CertificateSigningRequest -_Key = Union[DSAPrivateKey, DSAPublicKey, RSAPrivateKey, RSAPublicKey] +_Key = DSAPrivateKey | DSAPublicKey | RSAPrivateKey | RSAPublicKey FILETYPE_PEM: int FILETYPE_ASN1: int diff --git a/stubs/pyaudio/pyaudio.pyi b/stubs/pyaudio/pyaudio.pyi index 6849056b1d47..188114f82cf2 100644 --- a/stubs/pyaudio/pyaudio.pyi +++ b/stubs/pyaudio/pyaudio.pyi @@ -1,4 +1,4 @@ -from typing import Callable, Mapping, Optional, Sequence, Tuple, Union +from typing import Callable, Mapping, Sequence, Tuple from typing_extensions import Final paFloat32: Final[int] = ... @@ -68,9 +68,9 @@ paMacCoreStreamInfo: PaMacCoreStreamInfo # Auxiliary types _ChannelMap = Sequence[int] -_PaHostApiInfo = Mapping[str, Union[str, int]] -_PaDeviceInfo = Mapping[str, Union[str, int, float]] -_StreamCallback = Callable[[Optional[bytes], int, Mapping[str, float], int], Tuple[Optional[bytes], int]] +_PaHostApiInfo = Mapping[str, str | int] +_PaDeviceInfo = Mapping[str, str | int | float] +_StreamCallback = Callable[[bytes | None, int, Mapping[str, float], int], Tuple[bytes | None, int]] def get_format_from_width(width: int, unsigned: bool = ...) -> int: ... def get_portaudio_version() -> int: ... diff --git a/stubs/pysftp/pysftp/__init__.pyi b/stubs/pysftp/pysftp/__init__.pyi index 58e051248fc2..16cab1a30ddf 100644 --- a/stubs/pysftp/pysftp/__init__.pyi +++ b/stubs/pysftp/pysftp/__init__.pyi @@ -1,6 +1,6 @@ from stat import S_IMODE as S_IMODE from types import TracebackType -from typing import IO, Any, Callable, ContextManager, Sequence, Text, Type, Union +from typing import IO, Any, Callable, ContextManager, Sequence, Text, Type from typing_extensions import Literal import paramiko @@ -31,7 +31,7 @@ class CnOpts: def get_hostkey(self, host: str) -> paramiko.PKey: ... _Callback = Callable[[int, int], Any] -_Path = Union[Text, bytes] +_Path = Text | bytes class Connection: def __init__( diff --git a/stubs/python-dateutil/dateutil/parser/__init__.pyi b/stubs/python-dateutil/dateutil/parser/__init__.pyi index a408f649bc54..a3c5282a3ebc 100644 --- a/stubs/python-dateutil/dateutil/parser/__init__.pyi +++ b/stubs/python-dateutil/dateutil/parser/__init__.pyi @@ -1,9 +1,9 @@ from datetime import datetime, tzinfo -from typing import IO, Any, Mapping, Text, Union +from typing import IO, Any, Mapping, Text from .isoparser import isoparse as isoparse, isoparser as isoparser -_FileOrStr = Union[bytes, Text, IO[str], IO[Any]] +_FileOrStr = bytes | Text | IO[str] | IO[Any] class parserinfo(object): JUMP: list[str] diff --git a/stubs/python-dateutil/dateutil/parser/isoparser.pyi b/stubs/python-dateutil/dateutil/parser/isoparser.pyi index ed24582d43c4..69d983ae71fb 100644 --- a/stubs/python-dateutil/dateutil/parser/isoparser.pyi +++ b/stubs/python-dateutil/dateutil/parser/isoparser.pyi @@ -1,9 +1,9 @@ from _typeshed import SupportsRead from datetime import date, datetime, time, tzinfo -from typing import Text, Union +from typing import Text -_Readable = SupportsRead[Union[Text, bytes]] -_TakesAscii = Union[Text, bytes, _Readable] +_Readable = SupportsRead[Text | bytes] +_TakesAscii = Text | bytes | _Readable class isoparser: def __init__(self, sep: Text | bytes | None = ...): ... diff --git a/stubs/python-dateutil/dateutil/tz/tz.pyi b/stubs/python-dateutil/dateutil/tz/tz.pyi index dad7fa15a0b3..296d4418e128 100644 --- a/stubs/python-dateutil/dateutil/tz/tz.pyi +++ b/stubs/python-dateutil/dateutil/tz/tz.pyi @@ -1,10 +1,10 @@ import datetime -from typing import IO, Any, Text, TypeVar, Union +from typing import IO, Any, Text, TypeVar from ..relativedelta import relativedelta from ._common import _tzinfo as _tzinfo, enfold as enfold, tzname_in_python2 as tzname_in_python2, tzrangebase as tzrangebase -_FileObj = Union[str, Text, IO[str], IO[Text]] +_FileObj = str | Text | IO[str] | IO[Text] _DT = TypeVar("_DT", bound=datetime.datetime) ZERO: datetime.timedelta diff --git a/stubs/redis/redis/client.pyi b/stubs/redis/redis/client.pyi index 90655ab8f910..bac369bcc92f 100644 --- a/stubs/redis/redis/client.pyi +++ b/stubs/redis/redis/client.pyi @@ -2,22 +2,7 @@ import builtins import threading from _typeshed import Self, SupportsItems from datetime import datetime, timedelta -from typing import ( - Any, - Callable, - ClassVar, - Dict, - Generic, - Iterable, - Iterator, - Mapping, - Pattern, - Sequence, - Type, - TypeVar, - Union, - overload, -) +from typing import Any, Callable, ClassVar, Dict, Generic, Iterable, Iterator, Mapping, Pattern, Sequence, Type, TypeVar, overload from typing_extensions import Literal from .commands import CoreCommands, RedisModuleCommands, SentinelCommands @@ -27,11 +12,11 @@ from .retry import Retry _ScoreCastFuncReturn = TypeVar("_ScoreCastFuncReturn") -_Value = Union[bytes, float, int, str] -_Key = Union[str, bytes] +_Value = bytes | float | int | str +_Key = str | bytes # Lib returns str or bytes depending on value of decode_responses -_StrType = TypeVar("_StrType", bound=Union[str, bytes]) +_StrType = TypeVar("_StrType", bound=str | bytes) _VT = TypeVar("_VT") _T = TypeVar("_T") diff --git a/stubs/redis/redis/commands/core.pyi b/stubs/redis/redis/commands/core.pyi index 49b69575250d..f6638262587d 100644 --- a/stubs/redis/redis/commands/core.pyi +++ b/stubs/redis/redis/commands/core.pyi @@ -1,12 +1,12 @@ from collections.abc import Callable, Iterable, Mapping, Sequence from datetime import timedelta -from typing import Any, Generic, TypeVar, Union, overload +from typing import Any, Generic, TypeVar, overload from typing_extensions import Literal from ..client import _Key, _Value _ScoreCastFuncReturn = TypeVar("_ScoreCastFuncReturn") -_StrType = TypeVar("_StrType", bound=Union[str, bytes]) +_StrType = TypeVar("_StrType", bound=str | bytes) class CoreCommands(Generic[_StrType]): def acl_cat(self, category: str | None = ...) -> list[str]: ... diff --git a/stubs/requests/requests/sessions.pyi b/stubs/requests/requests/sessions.pyi index 89ba100c02af..73bca99c0e56 100644 --- a/stubs/requests/requests/sessions.pyi +++ b/stubs/requests/requests/sessions.pyi @@ -1,5 +1,5 @@ from _typeshed import SupportsItems -from typing import IO, Any, Callable, Iterable, List, Mapping, MutableMapping, Optional, Text, Tuple, TypeVar, Union +from typing import IO, Any, Callable, Iterable, List, Mapping, MutableMapping, Text, Tuple, TypeVar, Union from . import adapters, auth as _auth, compat, cookies, exceptions, hooks, models, status_codes, structures, utils from .models import Response @@ -43,20 +43,21 @@ class SessionRedirectMixin: def rebuild_proxies(self, prepared_request, proxies): ... def should_strip_auth(self, old_url, new_url): ... -_Data = Union[None, Text, bytes, Mapping[str, Any], Mapping[Text, Any], Iterable[Tuple[Text, Optional[Text]]], IO[Any]] +_Data = Union[None, Text, bytes, Mapping[str, Any], Mapping[Text, Any], Iterable[Tuple[Text, Text | None]], IO[Any]] _Hook = Callable[[Response], Any] _Hooks = MutableMapping[Text, List[_Hook]] -_HooksInput = MutableMapping[Text, Union[Iterable[_Hook], _Hook]] +_HooksInput = MutableMapping[Text, Iterable[_Hook] | _Hook] -_ParamsMappingKeyType = Union[Text, bytes, int, float] -_ParamsMappingValueType = Union[Text, bytes, int, float, Iterable[Union[Text, bytes, int, float]], None] -_Params = Union[ - SupportsItems[_ParamsMappingKeyType, _ParamsMappingValueType], - Tuple[_ParamsMappingKeyType, _ParamsMappingValueType], - Iterable[Tuple[_ParamsMappingKeyType, _ParamsMappingValueType]], - Union[Text, bytes], -] +_ParamsMappingKeyType = Text | bytes | int | float +_ParamsMappingValueType = Text | bytes | int | float | Iterable[Text | bytes | int | float] | None +_Params = ( + SupportsItems[_ParamsMappingKeyType, _ParamsMappingValueType] + | Tuple[_ParamsMappingKeyType, _ParamsMappingValueType] + | Iterable[Tuple[_ParamsMappingKeyType, _ParamsMappingValueType]] + | Text + | bytes +) _TextMapping = MutableMapping[Text, Text] _SessionT = TypeVar("_SessionT", bound=Session) diff --git a/stubs/setuptools/pkg_resources/__init__.pyi b/stubs/setuptools/pkg_resources/__init__.pyi index 9f121f3340fc..9b89c5f7dfdd 100644 --- a/stubs/setuptools/pkg_resources/__init__.pyi +++ b/stubs/setuptools/pkg_resources/__init__.pyi @@ -2,17 +2,17 @@ import importlib.abc import types import zipimport from abc import ABCMeta -from typing import IO, Any, Callable, Generator, Iterable, Optional, Sequence, Tuple, TypeVar, Union, overload +from typing import IO, Any, Callable, Generator, Iterable, Sequence, Tuple, TypeVar, overload LegacyVersion = Any # from packaging.version Version = Any # from packaging.version _T = TypeVar("_T") -_NestedStr = Union[str, Iterable[Union[str, Iterable[Any]]]] -_InstallerType = Callable[[Requirement], Optional[Distribution]] -_EPDistType = Union[Distribution, Requirement, str] -_MetadataType = Optional[IResourceProvider] -_PkgReqType = Union[str, Requirement] +_NestedStr = str | Iterable[str | Iterable[Any]] +_InstallerType = Callable[[Requirement], Distribution | None] +_EPDistType = Distribution | Requirement | str +_MetadataType = IResourceProvider | None +_PkgReqType = str | Requirement _DistFinderType = Callable[[_Importer, str, bool], Generator[Distribution, None, None]] _NSHandlerType = Callable[[_Importer, str, str, types.ModuleType], str] diff --git a/stubs/simplejson/simplejson/__init__.pyi b/stubs/simplejson/simplejson/__init__.pyi index 798a77062823..9e3401e78bb1 100644 --- a/stubs/simplejson/simplejson/__init__.pyi +++ b/stubs/simplejson/simplejson/__init__.pyi @@ -1,11 +1,11 @@ -from typing import IO, Any, Text, Union +from typing import IO, Any, Text from simplejson.decoder import JSONDecoder as JSONDecoder from simplejson.encoder import JSONEncoder as JSONEncoder, JSONEncoderForHTML as JSONEncoderForHTML from simplejson.raw_json import RawJSON as RawJSON from simplejson.scanner import JSONDecodeError as JSONDecodeError -_LoadsString = Union[Text, bytes, bytearray] +_LoadsString = Text | bytes | bytearray def dumps(obj: Any, *args: Any, **kwds: Any) -> str: ... def dump(obj: Any, fp: IO[str], *args: Any, **kwds: Any) -> None: ... diff --git a/stubs/toml/toml.pyi b/stubs/toml/toml.pyi index 3f8580b33376..2bb7d57a07aa 100644 --- a/stubs/toml/toml.pyi +++ b/stubs/toml/toml.pyi @@ -1,13 +1,13 @@ import sys from _typeshed import StrPath, SupportsWrite -from typing import IO, Any, Mapping, MutableMapping, Text, Type, Union +from typing import IO, Any, Mapping, MutableMapping, Text, Type if sys.version_info >= (3, 6): _PathLike = StrPath elif sys.version_info >= (3, 4): import pathlib - _PathLike = Union[StrPath, pathlib.PurePath] + _PathLike = StrPath | pathlib.PurePath else: _PathLike = StrPath diff --git a/tests/check_new_syntax.py b/tests/check_new_syntax.py index 09efdac84428..5b1f7dab1517 100755 --- a/tests/check_new_syntax.py +++ b/tests/check_new_syntax.py @@ -12,6 +12,36 @@ CONTEXT_MANAGER_ALIASES = {"ContextManager": "AbstractContextManager", "AsyncContextManager": "AbstractAsyncContextManager"} CONTEXTLIB_ALIAS_ALLOWLIST = frozenset({Path("stdlib/contextlib.pyi"), Path("stdlib/typing_extensions.pyi")}) +union_exclude_list = [ + # TODO: figure out why new union syntax doesn't work + Path("stdlib/_typeshed/__init__.pyi"), + Path("stdlib/asyncio/tasks.pyi"), + Path("stdlib/builtins.pyi"), + Path("stdlib/copyreg.pyi"), + Path("stdlib/distutils/ccompiler.pyi"), + Path("stdlib/email/message.pyi"), + Path("stdlib/email/mime/application.pyi"), + Path("stdlib/email/mime/audio.pyi"), + Path("stdlib/email/mime/base.pyi"), + Path("stdlib/email/mime/image.pyi"), + Path("stdlib/email/mime/multipart.pyi"), + Path("stdlib/email/utils.pyi"), + Path("stdlib/logging/__init__.pyi"), + Path("stdlib/pickle.pyi"), + Path("stdlib/readline.pyi"), + Path("stdlib/signal.pyi"), + Path("stdlib/ssl.pyi"), + Path("stdlib/subprocess.pyi"), + Path("stdlib/tempfile.pyi"), + Path("stdlib/tkinter/__init__.pyi"), + Path("stdlib/tracemalloc.pyi"), + Path("stdlib/typing.pyi"), + Path("stdlib/xmlrpc/client.pyi"), + Path("stdlib/xmlrpc/server.pyi"), + Path("stubs/requests/requests/sessions.pyi"), + Path("stubs/tabulate/tabulate.pyi"), +] + def check_new_syntax(tree: ast.AST, path: Path) -> list[str]: errors = [] @@ -28,6 +58,8 @@ def is_dotdotdot(node: ast.AST) -> bool: def add_contextlib_alias_error(node: ast.ImportFrom | ast.Attribute, alias: str) -> None: errors.append(f"{path}:{node.lineno}: Use `contextlib.{CONTEXT_MANAGER_ALIASES[alias]}` instead of `typing.{alias}`") + # TODO: Get rid of this class. It skips checking type aliases and base + # classes, but those can now be checked too, with new mypy version. class OldSyntaxFinder(ast.NodeVisitor): def __init__(self, *, set_from_collections_abc: bool) -> None: self.set_from_collections_abc = set_from_collections_abc @@ -67,10 +99,6 @@ def visit_Subscript(self, node: ast.Subscript) -> None: self.generic_visit(node) - # This doesn't check type aliases (or type var bounds, etc), since those are not - # currently supported - # - # TODO: can use built-in generics in type aliases class AnnotationFinder(ast.NodeVisitor): def __init__(self) -> None: self.set_from_collections_abc = False @@ -79,6 +107,16 @@ def old_syntax_finder(self) -> OldSyntaxFinder: """Convenience method to create an `OldSyntaxFinder` instance with the correct state""" return OldSyntaxFinder(set_from_collections_abc=self.set_from_collections_abc) + def visit_Subscript(self, node: ast.Subscript) -> None: + if path not in union_exclude_list and 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) + def visit_ImportFrom(self, node: ast.ImportFrom) -> None: if node.module == "collections.abc": imported_classes = node.names @@ -102,10 +140,12 @@ def visit_Attribute(self, node: ast.Attribute) -> None: def visit_AnnAssign(self, node: ast.AnnAssign) -> None: self.old_syntax_finder().visit(node.annotation) + self.generic_visit(node) def visit_arg(self, node: ast.arg) -> None: if node.annotation is not None: self.old_syntax_finder().visit(node.annotation) + self.generic_visit(node) def visit_FunctionDef(self, node: ast.FunctionDef) -> None: if node.returns is not None: @@ -135,9 +175,7 @@ def visit_If(self, node: ast.If) -> None: def main() -> None: errors = [] for path in chain(Path("stdlib").rglob("*.pyi"), Path("stubs").rglob("*.pyi")): - if "@python2" in path.parts: - continue - if Path("stubs/protobuf/google/protobuf") in path.parents: # TODO: fix protobuf stubs + if "@python2" in path.parts or Path("stubs/protobuf/google/protobuf") in path.parents: continue with open(path) as f: