From 3ab250eec828a15d5649053e3613e16c0369263d Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Wed, 16 Mar 2022 15:01:33 +0000 Subject: [PATCH] Use PEP 604 syntax wherever possible (#7493) --- stdlib/@python2/SocketServer.pyi | 2 +- stdlib/@python2/_codecs.pyi | 12 ++--- stdlib/@python2/_curses.pyi | 4 +- stdlib/@python2/_dummy_threading.pyi | 4 +- stdlib/@python2/_io.pyi | 4 +- stdlib/@python2/_typeshed/__init__.pyi | 12 ++--- stdlib/@python2/_typeshed/wsgi.pyi | 2 +- stdlib/@python2/_winreg.pyi | 4 +- stdlib/@python2/aifc.pyi | 4 +- stdlib/@python2/argparse.pyi | 4 +- stdlib/@python2/array.pyi | 4 +- stdlib/@python2/asyncore.pyi | 2 +- stdlib/@python2/base64.pyi | 6 +-- stdlib/@python2/binhex.pyi | 4 +- stdlib/@python2/bz2.pyi | 4 +- stdlib/@python2/cmath.pyi | 4 +- stdlib/@python2/codecs.pyi | 2 +- stdlib/@python2/contextlib.pyi | 4 +- stdlib/@python2/ctypes/__init__.pyi | 34 ++++++------- stdlib/@python2/datetime.pyi | 4 +- stdlib/@python2/dbm/__init__.pyi | 6 +-- stdlib/@python2/dbm/dumb.pyi | 6 +-- stdlib/@python2/dbm/gnu.pyi | 6 +-- stdlib/@python2/dbm/ndbm.pyi | 6 +-- stdlib/@python2/decimal.pyi | 4 +- stdlib/@python2/difflib.pyi | 4 +- stdlib/@python2/dis.pyi | 6 +-- stdlib/@python2/fnmatch.pyi | 4 +- stdlib/@python2/fractions.pyi | 4 +- stdlib/@python2/ftplib.pyi | 4 +- stdlib/@python2/genericpath.pyi | 2 +- stdlib/@python2/hashlib.pyi | 4 +- stdlib/@python2/hmac.pyi | 4 +- stdlib/@python2/imghdr.pyi | 4 +- stdlib/@python2/lib2to3/pytree.pyi | 4 +- stdlib/@python2/logging/__init__.pyi | 6 +-- stdlib/@python2/mailbox.pyi | 19 +------ stdlib/@python2/mailcap.pyi | 4 +- stdlib/@python2/nntplib.pyi | 4 +- stdlib/@python2/optparse.pyi | 4 +- stdlib/@python2/plistlib.pyi | 4 +- stdlib/@python2/pstats.pyi | 4 +- stdlib/@python2/py_compile.pyi | 4 +- stdlib/@python2/readline.pyi | 4 +- stdlib/@python2/rlcompleter.pyi | 4 +- stdlib/@python2/sets.pyi | 4 +- stdlib/@python2/shutil.pyi | 4 +- stdlib/@python2/signal.pyi | 4 +- stdlib/@python2/socket.pyi | 2 +- stdlib/@python2/sre_parse.pyi | 6 +-- stdlib/@python2/ssl.pyi | 10 ++-- stdlib/@python2/struct.pyi | 8 +-- stdlib/@python2/subprocess.pyi | 10 ++-- stdlib/@python2/sunau.pyi | 4 +- stdlib/@python2/termios.pyi | 4 +- stdlib/@python2/threading.pyi | 4 +- stdlib/@python2/timeit.pyi | 6 +-- stdlib/@python2/tty.pyi | 4 +- stdlib/@python2/turtle.pyi | 2 +- stdlib/@python2/unittest.pyi | 2 +- stdlib/@python2/urllib2.pyi | 4 +- stdlib/@python2/urlparse.pyi | 4 +- stdlib/@python2/uu.pyi | 4 +- stdlib/@python2/wave.pyi | 4 +- stdlib/@python2/xml/etree/ElementTree.pyi | 7 ++- stdlib/@python2/xmlrpclib.pyi | 2 +- stdlib/@python2/zipfile.pyi | 4 +- stdlib/_codecs.pyi | 4 +- stdlib/_curses.pyi | 4 +- stdlib/_dummy_threading.pyi | 4 +- stdlib/_typeshed/__init__.pyi | 20 ++++---- stdlib/aifc.pyi | 4 +- stdlib/array.pyi | 4 +- stdlib/asyncio/base_events.pyi | 4 +- stdlib/asyncio/base_subprocess.pyi | 4 +- stdlib/asyncio/events.pyi | 4 +- stdlib/asyncio/format_helpers.pyi | 4 +- stdlib/asyncio/streams.pyi | 4 +- stdlib/asyncio/subprocess.pyi | 4 +- stdlib/asyncio/tasks.pyi | 6 +-- stdlib/asyncio/trsock.pyi | 2 +- stdlib/binhex.pyi | 4 +- stdlib/builtins.pyi | 4 +- stdlib/cmath.pyi | 6 +-- stdlib/configparser.pyi | 4 +- stdlib/contextlib.pyi | 7 ++- stdlib/ctypes/__init__.pyi | 10 ++-- stdlib/dbm/__init__.pyi | 6 +-- stdlib/dbm/dumb.pyi | 6 +-- stdlib/dbm/gnu.pyi | 6 +-- stdlib/dbm/ndbm.pyi | 6 +-- stdlib/decimal.pyi | 4 +- stdlib/dis.pyi | 6 +-- stdlib/email/_header_value_parser.pyi | 4 +- stdlib/email/message.pyi | 4 +- stdlib/enum.pyi | 4 +- stdlib/fractions.pyi | 4 +- stdlib/hmac.pyi | 4 +- stdlib/http/client.pyi | 4 +- stdlib/http/cookies.pyi | 4 +- stdlib/importlib/abc.pyi | 4 +- stdlib/importlib/resources.pyi | 6 +-- stdlib/itertools.pyi | 16 +----- stdlib/lib2to3/pytree.pyi | 4 +- stdlib/logging/__init__.pyi | 6 +-- stdlib/lzma.pyi | 4 +- stdlib/mailbox.pyi | 4 +- stdlib/mailcap.pyi | 4 +- stdlib/math.pyi | 4 +- stdlib/multiprocessing/__init__.pyi | 4 +- stdlib/multiprocessing/context.pyi | 4 +- stdlib/multiprocessing/synchronize.pyi | 4 +- stdlib/nntplib.pyi | 4 +- stdlib/os/__init__.pyi | 12 ++--- stdlib/pickle.pyi | 2 +- stdlib/pstats.pyi | 4 +- stdlib/re.pyi | 4 +- stdlib/shutil.pyi | 4 +- stdlib/signal.pyi | 6 +-- stdlib/sre_parse.pyi | 4 +- stdlib/ssl.pyi | 10 ++-- stdlib/statistics.pyi | 4 +- stdlib/subprocess.pyi | 12 ++--- stdlib/sunau.pyi | 4 +- stdlib/sys.pyi | 19 ++----- stdlib/tempfile.pyi | 4 +- stdlib/termios.pyi | 4 +- stdlib/threading.pyi | 4 +- stdlib/time.pyi | 4 +- stdlib/timeit.pyi | 4 +- stdlib/tkinter/__init__.pyi | 20 ++++---- stdlib/tkinter/ttk.pyi | 4 +- stdlib/tokenize.pyi | 4 +- stdlib/tty.pyi | 4 +- stdlib/turtle.pyi | 2 +- stdlib/unittest/suite.pyi | 4 +- stdlib/urllib/parse.pyi | 4 +- stdlib/uu.pyi | 4 +- stdlib/wave.pyi | 4 +- stdlib/winreg.pyi | 4 +- stdlib/xml/dom/pulldom.pyi | 6 +-- stdlib/xml/dom/xmlbuilder.pyi | 10 ++-- stdlib/xml/etree/ElementTree.pyi | 7 ++- stdlib/xmlrpc/client.pyi | 2 +- stdlib/xmlrpc/server.pyi | 2 +- stdlib/zipapp.pyi | 4 +- stubs/Pillow/PIL/ImageColor.pyi | 2 +- stubs/PyMySQL/pymysql/converters.pyi | 4 +- stubs/PyYAML/yaml/constructor.pyi | 4 +- stubs/PyYAML/yaml/cyaml.pyi | 4 +- stubs/Pygments/pygments/lexers/__init__.pyi | 4 +- stubs/aiofiles/aiofiles/os.pyi | 4 +- .../aiofiles/aiofiles/threadpool/__init__.pyi | 4 +- stubs/beautifulsoup4/bs4/element.pyi | 10 ++-- stubs/bleach/bleach/sanitizer.pyi | 6 +-- stubs/colorama/colorama/ansitowin32.pyi | 4 +- stubs/croniter/croniter.pyi | 4 +- stubs/docopt/docopt.pyi | 4 +- stubs/freezegun/freezegun/api.pyi | 4 +- stubs/paramiko/paramiko/common.pyi | 4 +- stubs/paramiko/paramiko/transport.pyi | 4 +- stubs/pyOpenSSL/OpenSSL/crypto.pyi | 4 +- stubs/pyaudio/pyaudio.pyi | 6 +-- stubs/pysftp/pysftp/__init__.pyi | 4 +- .../dateutil/parser/__init__.pyi | 4 +- .../dateutil/parser/isoparser.pyi | 6 +-- stubs/python-dateutil/dateutil/tz/tz.pyi | 4 +- stubs/redis/redis/client.pyi | 8 +-- stubs/redis/redis/commands/core.pyi | 4 +- stubs/requests/requests/sessions.pyi | 8 +-- stubs/setuptools/pkg_resources/__init__.pyi | 12 ++--- stubs/simplejson/simplejson/__init__.pyi | 4 +- stubs/tabulate/tabulate.pyi | 6 +-- tests/check_new_syntax.py | 51 ++++++++++++++----- 174 files changed, 472 insertions(+), 490 deletions(-) diff --git a/stdlib/@python2/SocketServer.pyi b/stdlib/@python2/SocketServer.pyi index 7c72675e6..545ee8464 100644 --- a/stdlib/@python2/SocketServer.pyi +++ b/stdlib/@python2/SocketServer.pyi @@ -1,6 +1,6 @@ import sys from socket import SocketType -from typing import Any, BinaryIO, Callable, ClassVar, Text, Union +from typing import Any, BinaryIO, Callable, ClassVar, Text class BaseServer: address_family: int diff --git a/stdlib/@python2/_codecs.pyi b/stdlib/@python2/_codecs.pyi index fa6922207..1028cfec1 100644 --- a/stdlib/@python2/_codecs.pyi +++ b/stdlib/@python2/_codecs.pyi @@ -1,19 +1,19 @@ import codecs import sys -from typing import Any, Callable, Text, Union +from typing import Any, Callable, Text # For convenience: _Handler = Callable[[Exception], tuple[Text, int]] -_String = Union[bytes, str] -_Errors = Union[str, Text, None] -_Decodable = Union[bytes, Text] -_Encodable = Union[bytes, Text] +_String = bytes | str +_Errors = str | Text | None +_Decodable = bytes | Text +_Encodable = bytes | Text # This type is not exposed; it is defined in unicodeobject.c class _EncodingMap(object): def size(self) -> int: ... -_MapT = Union[dict[int, int], _EncodingMap] +_MapT = dict[int, int] | _EncodingMap def register(__search_function: Callable[[str], Any]) -> None: ... def register_error(__errors: str | Text, __handler: _Handler) -> None: ... diff --git a/stdlib/@python2/_curses.pyi b/stdlib/@python2/_curses.pyi index 4b2941e74..81de0ea96 100644 --- a/stdlib/@python2/_curses.pyi +++ b/stdlib/@python2/_curses.pyi @@ -1,6 +1,6 @@ -from typing import IO, Any, BinaryIO, Union, overload +from typing import IO, Any, BinaryIO, 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/@python2/_dummy_threading.pyi b/stdlib/@python2/_dummy_threading.pyi index c03c52a79..e7b0a9e4b 100644 --- a/stdlib/@python2/_dummy_threading.pyi +++ b/stdlib/@python2/_dummy_threading.pyi @@ -1,8 +1,8 @@ from types import FrameType, TracebackType -from typing import Any, Callable, Iterable, Mapping, Optional, Text +from typing import Any, Callable, Iterable, Mapping, Text # 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] diff --git a/stdlib/@python2/_io.pyi b/stdlib/@python2/_io.pyi index 3671bbd21..65c59ccf7 100644 --- a/stdlib/@python2/_io.pyi +++ b/stdlib/@python2/_io.pyi @@ -1,8 +1,8 @@ from _typeshed import Self from mmap import mmap -from typing import IO, Any, BinaryIO, Iterable, Text, TextIO, Union +from typing import IO, Any, BinaryIO, Iterable, Text, TextIO -_bytearray_like = Union[bytearray, mmap] +_bytearray_like = bytearray | mmap DEFAULT_BUFFER_SIZE: int diff --git a/stdlib/@python2/_typeshed/__init__.pyi b/stdlib/@python2/_typeshed/__init__.pyi index 0d1dc3866..a3399a8ca 100644 --- a/stdlib/@python2/_typeshed/__init__.pyi +++ b/stdlib/@python2/_typeshed/__init__.pyi @@ -14,7 +14,7 @@ import array import mmap -from typing import Any, Container, Iterable, Protocol, Text, TypeVar, Union +from typing import Any, Container, Iterable, Protocol, Text, TypeVar from typing_extensions import Literal, final _KT = TypeVar("_KT") @@ -104,7 +104,7 @@ OpenTextModeUpdating = Literal[ ] OpenTextModeWriting = Literal["w", "wt", "tw", "a", "at", "ta", "x", "xt", "tx"] OpenTextModeReading = Literal["r", "rt", "tr", "U", "rU", "Ur", "rtU", "rUt", "Urt", "trU", "tUr", "Utr"] -OpenTextMode = Union[OpenTextModeUpdating, OpenTextModeWriting, OpenTextModeReading] +OpenTextMode = OpenTextModeUpdating | OpenTextModeWriting | OpenTextModeReading OpenBinaryModeUpdating = Literal[ "rb+", "r+b", @@ -133,13 +133,13 @@ OpenBinaryModeUpdating = Literal[ ] OpenBinaryModeWriting = Literal["wb", "bw", "ab", "ba", "xb", "bx"] OpenBinaryModeReading = Literal["rb", "br", "rbU", "rUb", "Urb", "brU", "bUr", "Ubr"] -OpenBinaryMode = Union[OpenBinaryModeUpdating, OpenBinaryModeReading, OpenBinaryModeWriting] +OpenBinaryMode = OpenBinaryModeUpdating | OpenBinaryModeReading | OpenBinaryModeWriting class HasFileno(Protocol): def fileno(self) -> int: ... FileDescriptor = int -FileDescriptorLike = Union[int, HasFileno] +FileDescriptorLike = int | HasFileno class SupportsRead(Protocol[_T_co]): def read(self, __length: int = ...) -> _T_co: ... @@ -153,8 +153,8 @@ class SupportsNoArgReadline(Protocol[_T_co]): class SupportsWrite(Protocol[_T_contra]): def write(self, __s: _T_contra) -> Any: ... -ReadableBuffer = Union[bytes, bytearray, memoryview, array.array[Any], mmap.mmap, buffer] -WriteableBuffer = Union[bytearray, memoryview, array.array[Any], mmap.mmap, buffer] +ReadableBuffer = bytes | bytearray | memoryview | array.array[Any] | mmap.mmap | buffer +WriteableBuffer = bytearray | memoryview | array.array[Any] | mmap.mmap | buffer # Used by type checkers for checks involving None (does not exist at runtime) @final diff --git a/stdlib/@python2/_typeshed/wsgi.pyi b/stdlib/@python2/_typeshed/wsgi.pyi index 6dc2b5cc0..4380949c9 100644 --- a/stdlib/@python2/_typeshed/wsgi.pyi +++ b/stdlib/@python2/_typeshed/wsgi.pyi @@ -4,7 +4,7 @@ # file. They are provided for type checking purposes. from sys import _OptExcInfo -from typing import Any, Callable, Iterable, Optional, Protocol, Text +from typing import Any, Callable, Iterable, Protocol, Text class StartResponse(Protocol): def __call__( diff --git a/stdlib/@python2/_winreg.pyi b/stdlib/@python2/_winreg.pyi index e432d883e..395024fcc 100644 --- a/stdlib/@python2/_winreg.pyi +++ b/stdlib/@python2/_winreg.pyi @@ -1,10 +1,10 @@ import sys from _typeshed import Self from types import TracebackType -from typing import Any, Union +from typing import Any if sys.platform == "win32": - _KeyType = Union[HKEYType, int] + _KeyType = HKEYType | int def CloseKey(__hkey: _KeyType) -> None: ... def ConnectRegistry(__computer_name: str | None, __key: _KeyType) -> HKEYType: ... def CreateKey(__key: _KeyType, __sub_key: str | None) -> HKEYType: ... diff --git a/stdlib/@python2/aifc.pyi b/stdlib/@python2/aifc.pyi index b8049e857..766ccde95 100644 --- a/stdlib/@python2/aifc.pyi +++ b/stdlib/@python2/aifc.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, NamedTuple, Text, Union, overload +from typing import IO, Any, NamedTuple, Text, overload from typing_extensions import Literal class Error(Exception): ... @@ -11,7 +11,7 @@ class _aifc_params(NamedTuple): comptype: bytes compname: bytes -_File = Union[Text, IO[bytes]] +_File = Text | IO[bytes] _Marker = tuple[int, int, bytes] class Aifc_read: diff --git a/stdlib/@python2/argparse.pyi b/stdlib/@python2/argparse.pyi index e82a8c621..3eacc7b1d 100644 --- a/stdlib/@python2/argparse.pyi +++ b/stdlib/@python2/argparse.pyi @@ -1,10 +1,10 @@ -from typing import IO, Any, Callable, Generator, Iterable, NoReturn, Pattern, Protocol, Sequence, Text, TypeVar, Union, overload +from typing import IO, Any, Callable, Generator, Iterable, NoReturn, Pattern, Protocol, Sequence, Text, TypeVar, overload _T = TypeVar("_T") _ActionT = TypeVar("_ActionT", bound=Action) _N = TypeVar("_N") -_Text = Union[str, unicode] +_Text = str | unicode ONE_OR_MORE: str OPTIONAL: str diff --git a/stdlib/@python2/array.pyi b/stdlib/@python2/array.pyi index 1ef8c3a7c..fcd1d7bfa 100644 --- a/stdlib/@python2/array.pyi +++ b/stdlib/@python2/array.pyi @@ -1,11 +1,11 @@ from _typeshed import Self -from typing import Any, BinaryIO, Generic, Iterable, MutableSequence, Text, TypeVar, Union, overload +from typing import Any, BinaryIO, Generic, Iterable, MutableSequence, Text, TypeVar, overload from typing_extensions import Literal _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, Text) diff --git a/stdlib/@python2/asyncore.pyi b/stdlib/@python2/asyncore.pyi index 1daa1aac8..a9f07613b 100644 --- a/stdlib/@python2/asyncore.pyi +++ b/stdlib/@python2/asyncore.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import FileDescriptorLike from socket import SocketType -from typing import Any, Optional, overload +from typing import Any, overload # cyclic dependence with asynchat _maptype = dict[int, Any] diff --git a/stdlib/@python2/base64.pyi b/stdlib/@python2/base64.pyi index 00856aafd..4a32006ea 100644 --- a/stdlib/@python2/base64.pyi +++ b/stdlib/@python2/base64.pyi @@ -1,7 +1,7 @@ -from typing import IO, Union +from typing import IO -_encodable = Union[bytes, unicode] -_decodable = Union[bytes, unicode] +_encodable = bytes | unicode +_decodable = bytes | unicode def b64encode(s: _encodable, altchars: bytes | None = ...) -> bytes: ... def b64decode(s: _decodable, altchars: bytes | None = ..., validate: bool = ...) -> bytes: ... diff --git a/stdlib/@python2/binhex.pyi b/stdlib/@python2/binhex.pyi index 4e295b8ed..10a5a3ee5 100644 --- a/stdlib/@python2/binhex.pyi +++ b/stdlib/@python2/binhex.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, Union +from typing import IO, Any 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/@python2/bz2.pyi b/stdlib/@python2/bz2.pyi index bec8994db..e182aa428 100644 --- a/stdlib/@python2/bz2.pyi +++ b/stdlib/@python2/bz2.pyi @@ -1,9 +1,9 @@ import io from _typeshed import ReadableBuffer, Self, WriteableBuffer -from typing import IO, Any, Iterable, Text, Union +from typing import IO, Any, Iterable, Text from typing_extensions import SupportsIndex -_PathOrFile = Union[Text, IO[bytes]] +_PathOrFile = Text | IO[bytes] def compress(data: bytes, compresslevel: int = ...) -> bytes: ... def decompress(data: bytes) -> bytes: ... diff --git a/stdlib/@python2/cmath.pyi b/stdlib/@python2/cmath.pyi index ef54d7f43..1053b2269 100644 --- a/stdlib/@python2/cmath.pyi +++ b/stdlib/@python2/cmath.pyi @@ -1,8 +1,8 @@ -from typing import SupportsComplex, SupportsFloat, Union +from typing import SupportsComplex, SupportsFloat e: float pi: float -_C = Union[SupportsFloat, SupportsComplex, complex] +_C = SupportsFloat | SupportsComplex | complex def acos(__z: _C) -> complex: ... def acosh(__z: _C) -> complex: ... diff --git a/stdlib/@python2/codecs.pyi b/stdlib/@python2/codecs.pyi index 2780d473b..0f97a4401 100644 --- a/stdlib/@python2/codecs.pyi +++ b/stdlib/@python2/codecs.pyi @@ -1,7 +1,7 @@ import types from _typeshed import Self from abc import abstractmethod -from typing import IO, Any, BinaryIO, Callable, Generator, Iterable, Iterator, Protocol, Text, TextIO, Union, overload +from typing import IO, Any, BinaryIO, Callable, Generator, Iterable, Iterator, Protocol, Text, TextIO, overload from typing_extensions import Literal # TODO: this only satisfies the most common interface, where diff --git a/stdlib/@python2/contextlib.pyi b/stdlib/@python2/contextlib.pyi index 8e68238fc..4f39ba5da 100644 --- a/stdlib/@python2/contextlib.pyi +++ b/stdlib/@python2/contextlib.pyi @@ -1,5 +1,5 @@ from types import TracebackType -from typing import IO, Any, Callable, ContextManager, Iterable, Iterator, Optional, Protocol, TypeVar +from typing import IO, Any, Callable, ContextManager, Iterable, Iterator, Protocol, TypeVar from typing_extensions import ParamSpec _T = TypeVar("_T") @@ -7,7 +7,7 @@ _T_co = TypeVar("_T_co", covariant=True) _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] class GeneratorContextManager(ContextManager[_T_co]): def __call__(self, func: _F) -> _F: ... diff --git a/stdlib/@python2/ctypes/__init__.pyi b/stdlib/@python2/ctypes/__init__.pyi index 9fab35ebd..ef627f10f 100644 --- a/stdlib/@python2/ctypes/__init__.pyi +++ b/stdlib/@python2/ctypes/__init__.pyi @@ -59,9 +59,9 @@ pythonapi: PyDLL # Anything that implements the read-write buffer interface. # The buffer interface is defined purely on the C level, so we cannot define a normal Protocol # for it. Instead we have to list the most common stdlib buffer classes in a Union. -_WritableBuffer = _UnionT[bytearray, memoryview, array[Any], _CData] +_WritableBuffer = bytearray | memoryview | array[Any] | _CData # Same as _WritableBuffer, but also includes read-only buffer types (like bytes). -_ReadOnlyBuffer = _UnionT[_WritableBuffer, bytes] +_ReadOnlyBuffer = _WritableBuffer | bytes class _CDataMeta(type): # By default mypy complains about the following two methods, because strictly speaking cls @@ -81,7 +81,7 @@ class _CData(metaclass=_CDataMeta): @classmethod def from_address(cls: type[Self], address: int) -> Self: ... @classmethod - def from_param(cls: type[_CT], obj: Any) -> _UnionT[_CT, _CArgObject]: ... + def from_param(cls: type[_CT], obj: Any) -> _CT | _CArgObject: ... @classmethod def in_dll(cls: type[Self], library: CDLL, name: str) -> Self: ... @@ -92,7 +92,7 @@ _ECT = Callable[[Optional[type[_CData]], _FuncPointer, tuple[_CData, ...]], _CDa _PF = _UnionT[tuple[int], tuple[int, str], tuple[int, str, Any]] class _FuncPointer(_PointerLike, _CData): - restype: _UnionT[type[_CData], Callable[[int], Any], None] = ... + restype: type[_CData] | Callable[[int], Any] | None = ... argtypes: Sequence[type[_CData]] = ... errcheck: _ECT = ... @overload @@ -125,25 +125,25 @@ class _CArgObject: ... # Any type that can be implicitly converted to c_void_p when passed as a C function argument. # (bytes is not included here, see below.) -_CVoidPLike = _UnionT[_PointerLike, Array[Any], _CArgObject, int] +_CVoidPLike = _PointerLike | Array[Any] | _CArgObject | int # Same as above, but including types known to be read-only (i. e. bytes). # This distinction is not strictly necessary (ctypes doesn't differentiate between const # and non-const pointers), but it catches errors like memmove(b'foo', buf, 4) # when memmove(buf, b'foo', 4) was intended. -_CVoidConstPLike = _UnionT[_CVoidPLike, bytes] +_CVoidConstPLike = _CVoidPLike | bytes def addressof(obj: _CData) -> int: ... -def alignment(obj_or_type: _UnionT[_CData, type[_CData]]) -> int: ... +def alignment(obj_or_type: _CData | type[_CData]) -> int: ... def byref(obj: _CData, offset: int = ...) -> _CArgObject: ... _CastT = TypeVar("_CastT", bound=_CanCastTo) -def cast(obj: _UnionT[_CData, _CArgObject, int], typ: type[_CastT]) -> _CastT: ... -def create_string_buffer(init: _UnionT[int, bytes], size: int | None = ...) -> Array[c_char]: ... +def cast(obj: _CData | _CArgObject | int, typ: type[_CastT]) -> _CastT: ... +def create_string_buffer(init: int | bytes, size: int | None = ...) -> Array[c_char]: ... c_buffer = create_string_buffer -def create_unicode_buffer(init: _UnionT[int, Text], size: int | None = ...) -> Array[c_wchar]: ... +def create_unicode_buffer(init: int | Text, size: int | None = ...) -> Array[c_wchar]: ... if sys.platform == "win32": def DllCanUnloadNow() -> int: ... @@ -183,7 +183,7 @@ def set_errno(value: int) -> int: ... if sys.platform == "win32": def set_last_error(value: int) -> int: ... -def sizeof(obj_or_type: _UnionT[_CData, type[_CData]]) -> int: ... +def sizeof(obj_or_type: _CData | type[_CData]) -> int: ... def string_at(address: _CVoidConstPLike, size: int = ...) -> bytes: ... if sys.platform == "win32": @@ -198,10 +198,10 @@ class _SimpleCData(Generic[_T], _CData): class c_byte(_SimpleCData[int]): ... class c_char(_SimpleCData[bytes]): - def __init__(self, value: _UnionT[int, bytes] = ...) -> None: ... + def __init__(self, value: int | bytes = ...) -> None: ... -class c_char_p(_PointerLike, _SimpleCData[Optional[bytes]]): - def __init__(self, value: _UnionT[int, bytes] | None = ...) -> None: ... +class c_char_p(_PointerLike, _SimpleCData[bytes | None]): + def __init__(self, value: int | bytes | None = ...) -> None: ... class c_double(_SimpleCData[float]): ... class c_longdouble(_SimpleCData[float]): ... @@ -225,11 +225,11 @@ 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[Text]): ... -class c_wchar_p(_PointerLike, _SimpleCData[Optional[Text]]): - def __init__(self, value: _UnionT[int, Text] | None = ...) -> None: ... +class c_wchar_p(_PointerLike, _SimpleCData[Text | None]): + def __init__(self, value: int | Text | None = ...) -> None: ... class c_bool(_SimpleCData[bool]): def __init__(self, value: bool = ...) -> None: ... diff --git a/stdlib/@python2/datetime.pyi b/stdlib/@python2/datetime.pyi index 6a259cf4d..bdd32a8e7 100644 --- a/stdlib/@python2/datetime.pyi +++ b/stdlib/@python2/datetime.pyi @@ -1,8 +1,8 @@ from _typeshed import Self from time import struct_time -from typing import AnyStr, ClassVar, SupportsAbs, Union, overload +from typing import AnyStr, ClassVar, SupportsAbs, overload -_Text = Union[str, unicode] +_Text = str | unicode MINYEAR: int MAXYEAR: int diff --git a/stdlib/@python2/dbm/__init__.pyi b/stdlib/@python2/dbm/__init__.pyi index 9c867074d..e9c1d01a5 100644 --- a/stdlib/@python2/dbm/__init__.pyi +++ b/stdlib/@python2/dbm/__init__.pyi @@ -1,10 +1,10 @@ from _typeshed import Self from types import TracebackType -from typing import Iterator, MutableMapping, Union +from typing import Iterator, MutableMapping from typing_extensions import Literal -_KeyType = Union[str, bytes] -_ValueType = Union[str, bytes] +_KeyType = str | bytes +_ValueType = str | bytes class _Database(MutableMapping[_KeyType, bytes]): def close(self) -> None: ... diff --git a/stdlib/@python2/dbm/dumb.pyi b/stdlib/@python2/dbm/dumb.pyi index e040f23ce..acb4b3b7a 100644 --- a/stdlib/@python2/dbm/dumb.pyi +++ b/stdlib/@python2/dbm/dumb.pyi @@ -1,9 +1,9 @@ from _typeshed import Self from types import TracebackType -from typing import Iterator, MutableMapping, Union +from typing import Iterator, MutableMapping -_KeyType = Union[str, bytes] -_ValueType = Union[str, bytes] +_KeyType = str | bytes +_ValueType = str | bytes error = OSError diff --git a/stdlib/@python2/dbm/gnu.pyi b/stdlib/@python2/dbm/gnu.pyi index 1eecfac66..019711f62 100644 --- a/stdlib/@python2/dbm/gnu.pyi +++ b/stdlib/@python2/dbm/gnu.pyi @@ -1,10 +1,10 @@ from _typeshed import Self from types import TracebackType -from typing import TypeVar, Union, overload +from typing import 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/@python2/dbm/ndbm.pyi b/stdlib/@python2/dbm/ndbm.pyi index 12d9f3188..92ec92ebd 100644 --- a/stdlib/@python2/dbm/ndbm.pyi +++ b/stdlib/@python2/dbm/ndbm.pyi @@ -1,10 +1,10 @@ from _typeshed import Self from types import TracebackType -from typing import TypeVar, Union, overload +from typing import 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/@python2/decimal.pyi b/stdlib/@python2/decimal.pyi index f798d8811..5ea7348c2 100644 --- a/stdlib/@python2/decimal.pyi +++ b/stdlib/@python2/decimal.pyi @@ -2,9 +2,9 @@ from _typeshed import Self from types import TracebackType from typing import Any, Container, NamedTuple, Sequence, Text, Union -_Decimal = Union[Decimal, int] +_Decimal = Decimal | int _DecimalNew = Union[Decimal, float, Text, tuple[int, Sequence[int], int]] -_ComparableNum = Union[Decimal, float] +_ComparableNum = Decimal | float class DecimalTuple(NamedTuple): sign: int diff --git a/stdlib/@python2/difflib.pyi b/stdlib/@python2/difflib.pyi index c4e59f54c..30b624b8f 100644 --- a/stdlib/@python2/difflib.pyi +++ b/stdlib/@python2/difflib.pyi @@ -1,11 +1,11 @@ -from typing import Any, AnyStr, Callable, Generic, Iterable, Iterator, NamedTuple, Sequence, Text, TypeVar, Union, overload +from typing import Any, AnyStr, Callable, Generic, Iterable, Iterator, NamedTuple, Sequence, Text, TypeVar, overload _T = TypeVar("_T") # Aliases can't point to type vars, so we need to redeclare AnyStr _StrType = TypeVar("_StrType", Text, bytes) -_JunkCallback = Union[Callable[[Text], bool], Callable[[str], bool]] +_JunkCallback = Callable[[Text], bool] | Callable[[str], bool] class Match(NamedTuple): a: int diff --git a/stdlib/@python2/dis.pyi b/stdlib/@python2/dis.pyi index f6be1a8df..79cc30a68 100644 --- a/stdlib/@python2/dis.pyi +++ b/stdlib/@python2/dis.pyi @@ -13,12 +13,12 @@ from opcode import ( opmap as opmap, opname as opname, ) -from typing import Any, Callable, Iterator, Union +from typing import Any, Callable, Iterator # Strictly this should not have to include Callable, but mypy doesn't use FunctionType # for functions (python/mypy#3171) -_have_code = Union[types.MethodType, types.FunctionType, types.CodeType, type, Callable[..., Any]] -_have_code_or_string = Union[_have_code, str, bytes] +_have_code = types.MethodType | types.FunctionType | types.CodeType | type | Callable[..., Any] +_have_code_or_string = _have_code | str | bytes COMPILER_FLAG_NAMES: dict[int, str] diff --git a/stdlib/@python2/fnmatch.pyi b/stdlib/@python2/fnmatch.pyi index ead2dd5bf..942a52bba 100644 --- a/stdlib/@python2/fnmatch.pyi +++ b/stdlib/@python2/fnmatch.pyi @@ -1,6 +1,6 @@ -from typing import AnyStr, Iterable, Union +from typing import AnyStr, Iterable -_EitherStr = Union[str, unicode] +_EitherStr = str | unicode def fnmatch(filename: _EitherStr, pattern: _EitherStr) -> bool: ... def fnmatchcase(filename: _EitherStr, pattern: _EitherStr) -> bool: ... diff --git a/stdlib/@python2/fractions.pyi b/stdlib/@python2/fractions.pyi index 7835e9aa5..27de79248 100644 --- a/stdlib/@python2/fractions.pyi +++ b/stdlib/@python2/fractions.pyi @@ -1,10 +1,10 @@ from _typeshed import Self from decimal import Decimal from numbers import Integral, Rational, Real -from typing import Union, overload +from typing import overload from typing_extensions import Literal -_ComparableNum = Union[int, float, Decimal, Real] +_ComparableNum = int | float | Decimal | Real @overload def gcd(a: int, b: int) -> int: ... diff --git a/stdlib/@python2/ftplib.pyi b/stdlib/@python2/ftplib.pyi index b8c2bbd40..870d00d80 100644 --- a/stdlib/@python2/ftplib.pyi +++ b/stdlib/@python2/ftplib.pyi @@ -1,10 +1,10 @@ from _typeshed import SupportsRead, SupportsReadline from socket import socket from ssl import SSLContext -from typing import Any, BinaryIO, Callable, Text, Union +from typing import Any, BinaryIO, Callable, Text from typing_extensions import Literal -_IntOrStr = Union[int, Text] +_IntOrStr = int | Text MSG_OOB: int FTP_PORT: int diff --git a/stdlib/@python2/genericpath.pyi b/stdlib/@python2/genericpath.pyi index fecb3b70a..66b9d5fc3 100644 --- a/stdlib/@python2/genericpath.pyi +++ b/stdlib/@python2/genericpath.pyi @@ -1,5 +1,5 @@ from _typeshed import SupportsLessThanT -from typing import Sequence, Text, Union, overload +from typing import Sequence, Text, overload from typing_extensions import Literal # All overloads can return empty string. Ideally, Literal[""] would be a valid diff --git a/stdlib/@python2/hashlib.pyi b/stdlib/@python2/hashlib.pyi index 8f881aaaf..86e6c2115 100644 --- a/stdlib/@python2/hashlib.pyi +++ b/stdlib/@python2/hashlib.pyi @@ -1,6 +1,4 @@ -from typing import Union - -_DataType = Union[str, unicode, bytearray, buffer, memoryview] +_DataType = str | unicode | bytearray | buffer | memoryview class _hash(object): # This is not actually in the module namespace. @property diff --git a/stdlib/@python2/hmac.pyi b/stdlib/@python2/hmac.pyi index cc39d8c65..a244f4112 100644 --- a/stdlib/@python2/hmac.pyi +++ b/stdlib/@python2/hmac.pyi @@ -1,10 +1,10 @@ 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/@python2/imghdr.pyi b/stdlib/@python2/imghdr.pyi index dcfc3506f..36db49902 100644 --- a/stdlib/@python2/imghdr.pyi +++ b/stdlib/@python2/imghdr.pyi @@ -1,11 +1,11 @@ -from typing import Any, BinaryIO, Callable, Protocol, Text, Union, overload +from typing import Any, BinaryIO, Callable, Protocol, Text, overload class _ReadableBinary(Protocol): def tell(self) -> int: ... def read(self, size: int) -> bytes: ... def seek(self, offset: int) -> Any: ... -_File = Union[Text, _ReadableBinary] +_File = Text | _ReadableBinary @overload def what(file: _File, h: None = ...) -> str | None: ... diff --git a/stdlib/@python2/lib2to3/pytree.pyi b/stdlib/@python2/lib2to3/pytree.pyi index 130f03dab..29699f651 100644 --- a/stdlib/@python2/lib2to3/pytree.pyi +++ b/stdlib/@python2/lib2to3/pytree.pyi @@ -1,9 +1,9 @@ from _typeshed import Self from lib2to3.pgen2.grammar import Grammar -from typing import Any, Callable, Iterator, Optional, Text, TypeVar, Union +from typing import Any, Callable, Iterator, Optional, Text, TypeVar _P = TypeVar("_P") -_NL = Union[Node, Leaf] +_NL = Node | Leaf _Context = tuple[Text, int, int] _Results = dict[Text, _NL] _RawNode = tuple[int, Text, _Context, Optional[list[_NL]]] diff --git a/stdlib/@python2/logging/__init__.pyi b/stdlib/@python2/logging/__init__.pyi index 9ca64dc96..4e0a9dedf 100644 --- a/stdlib/@python2/logging/__init__.pyi +++ b/stdlib/@python2/logging/__init__.pyi @@ -5,10 +5,10 @@ from types import FrameType, TracebackType from typing import IO, Any, Callable, Generic, Mapping, MutableMapping, Optional, Sequence, Text, TypeVar, Union, overload _SysExcInfoType = Union[tuple[type, BaseException, Optional[TracebackType]], tuple[None, None, None]] -_ExcInfoType = Union[None, bool, _SysExcInfoType] +_ExcInfoType = None | bool | _SysExcInfoType _ArgsType = Union[tuple[Any, ...], Mapping[str, Any]] -_FilterType = Union[Filter, Callable[[LogRecord], int]] -_Level = Union[int, Text] +_FilterType = Filter | Callable[[LogRecord], int] +_Level = int | Text raiseExceptions: bool logThreads: bool diff --git a/stdlib/@python2/mailbox.pyi b/stdlib/@python2/mailbox.pyi index 9c4aa66cd..9d3f4d866 100644 --- a/stdlib/@python2/mailbox.pyi +++ b/stdlib/@python2/mailbox.pyi @@ -1,26 +1,11 @@ import email.message from types import TracebackType -from typing import ( - IO, - Any, - AnyStr, - Callable, - Generic, - Iterable, - Iterator, - Mapping, - Protocol, - Sequence, - Text, - TypeVar, - Union, - overload, -) +from typing import IO, Any, AnyStr, Callable, Generic, Iterable, Iterator, Mapping, Protocol, Sequence, Text, TypeVar, overload from typing_extensions import Literal _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/@python2/mailcap.pyi b/stdlib/@python2/mailcap.pyi index 56218d137..6e0c91828 100644 --- a/stdlib/@python2/mailcap.pyi +++ b/stdlib/@python2/mailcap.pyi @@ -1,6 +1,6 @@ -from typing import Mapping, Sequence, Union +from typing import 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/@python2/nntplib.pyi b/stdlib/@python2/nntplib.pyi index 602617665..7cacb07bd 100644 --- a/stdlib/@python2/nntplib.pyi +++ b/stdlib/@python2/nntplib.pyi @@ -3,9 +3,9 @@ import socket import ssl from _typeshed import Self from builtins import list as List # alias to avoid a name clash with a method named `list` in `_NNTPBase` -from typing import IO, Any, Iterable, NamedTuple, Union +from typing import IO, Any, Iterable, NamedTuple -_File = Union[IO[bytes], bytes, str, None] +_File = IO[bytes] | bytes | str | None class NNTPError(Exception): response: str diff --git a/stdlib/@python2/optparse.pyi b/stdlib/@python2/optparse.pyi index a99bc0a6f..d033cb9a6 100644 --- a/stdlib/@python2/optparse.pyi +++ b/stdlib/@python2/optparse.pyi @@ -1,7 +1,7 @@ -from typing import IO, Any, AnyStr, Callable, Iterable, Mapping, Sequence, Union, overload +from typing import IO, Any, AnyStr, Callable, Iterable, Mapping, Sequence, overload # See https://groups.google.com/forum/#!topic/python-ideas/gA1gdj3RZ5g -_Text = Union[str, unicode] +_Text = str | unicode NO_DEFAULT: tuple[_Text, ...] SUPPRESS_HELP: _Text diff --git a/stdlib/@python2/plistlib.pyi b/stdlib/@python2/plistlib.pyi index 02a1cb506..488757b4c 100644 --- a/stdlib/@python2/plistlib.pyi +++ b/stdlib/@python2/plistlib.pyi @@ -1,6 +1,6 @@ -from typing import IO, Any, Mapping, Text, Union +from typing import IO, Any, Mapping, Text -_Path = Union[str, Text] +_Path = str | Text def readPlist(pathOrFile: _Path | IO[bytes]) -> Any: ... def writePlist(value: Mapping[str, Any], pathOrFile: _Path | IO[bytes]) -> None: ... diff --git a/stdlib/@python2/pstats.pyi b/stdlib/@python2/pstats.pyi index e2cf6e437..6b956764e 100644 --- a/stdlib/@python2/pstats.pyi +++ b/stdlib/@python2/pstats.pyi @@ -1,9 +1,9 @@ from _typeshed import Self from cProfile import Profile as _cProfile from profile import Profile -from typing import IO, Any, Iterable, Text, TypeVar, Union, overload +from typing import IO, Any, Iterable, Text, TypeVar, overload -_Selector = Union[str, float, int] +_Selector = str | float | int _T = TypeVar("_T", bound=Stats) class Stats: diff --git a/stdlib/@python2/py_compile.pyi b/stdlib/@python2/py_compile.pyi index 3c26f4511..ccd05029f 100644 --- a/stdlib/@python2/py_compile.pyi +++ b/stdlib/@python2/py_compile.pyi @@ -1,6 +1,6 @@ -from typing import Text, Union +from typing import Text -_EitherStr = Union[bytes, Text] +_EitherStr = bytes | Text class PyCompileError(Exception): exc_type_name: str diff --git a/stdlib/@python2/readline.pyi b/stdlib/@python2/readline.pyi index 9b82d9bae..af642410b 100644 --- a/stdlib/@python2/readline.pyi +++ b/stdlib/@python2/readline.pyi @@ -2,8 +2,8 @@ import sys from typing import Callable, Optional, Sequence, Text if sys.platform != "win32": - _CompleterT = Optional[Callable[[str, int], Optional[str]]] - _CompDispT = Optional[Callable[[str, Sequence[str], int], None]] + _CompleterT = Optional[Callable[[str, int], str | None]] + _CompDispT = Callable[[str, Sequence[str], int], None] | None def parse_and_bind(__string: str) -> None: ... def read_init_file(__filename: Text | None = ...) -> None: ... def get_line_buffer() -> str: ... diff --git a/stdlib/@python2/rlcompleter.pyi b/stdlib/@python2/rlcompleter.pyi index e075e241b..6cf58fbf2 100644 --- a/stdlib/@python2/rlcompleter.pyi +++ b/stdlib/@python2/rlcompleter.pyi @@ -1,6 +1,6 @@ -from typing import Any, Union +from typing import Any -_Text = Union[str, unicode] +_Text = str | unicode class Completer: def __init__(self, namespace: dict[str, Any] | None = ...) -> None: ... diff --git a/stdlib/@python2/sets.pyi b/stdlib/@python2/sets.pyi index 7cafbaf8a..637bc879f 100644 --- a/stdlib/@python2/sets.pyi +++ b/stdlib/@python2/sets.pyi @@ -1,8 +1,8 @@ from _typeshed import Self -from typing import Any, Hashable, Iterable, Iterator, MutableMapping, TypeVar, Union +from typing import Any, Hashable, Iterable, Iterator, MutableMapping, TypeVar _T = TypeVar("_T") -_Setlike = Union[BaseSet[_T], Iterable[_T]] +_Setlike = BaseSet[_T] | Iterable[_T] class BaseSet(Iterable[_T]): def __init__(self) -> None: ... diff --git a/stdlib/@python2/shutil.pyi b/stdlib/@python2/shutil.pyi index f92cf1c9f..173ce9c28 100644 --- a/stdlib/@python2/shutil.pyi +++ b/stdlib/@python2/shutil.pyi @@ -1,5 +1,5 @@ from _typeshed import SupportsRead, SupportsWrite -from typing import Any, AnyStr, Callable, Iterable, Sequence, Text, TypeVar, Union +from typing import Any, AnyStr, Callable, Iterable, Sequence, Text, TypeVar _AnyStr = TypeVar("_AnyStr", str, unicode) _AnyPath = TypeVar("_AnyPath", str, unicode) @@ -21,7 +21,7 @@ def copytree( ) -> _PathReturn: ... def rmtree(path: _AnyPath, ignore_errors: bool = ..., onerror: Callable[[Any, _AnyPath, Any], Any] | None = ...) -> None: ... -_CopyFn = Union[Callable[[str, str], None], Callable[[Text, Text], None]] +_CopyFn = Callable[[str, str], None] | Callable[[Text, Text], None] def move(src: Text, dst: Text) -> _PathReturn: ... def make_archive( diff --git a/stdlib/@python2/signal.pyi b/stdlib/@python2/signal.pyi index 7f86f03e6..f39f38c41 100644 --- a/stdlib/@python2/signal.pyi +++ b/stdlib/@python2/signal.pyi @@ -1,5 +1,5 @@ from types import FrameType -from typing import Callable, Union +from typing import Callable SIG_DFL: int SIG_IGN: int @@ -55,7 +55,7 @@ CTRL_BREAK_EVENT: int class ItimerError(IOError): ... -_HANDLER = Union[Callable[[int, FrameType], None], int, None] +_HANDLER = Callable[[int, FrameType], None] | int | None def alarm(time: int) -> int: ... def getsignal(signalnum: int) -> _HANDLER: ... diff --git a/stdlib/@python2/socket.pyi b/stdlib/@python2/socket.pyi index 0981ce28a..29f4fe125 100644 --- a/stdlib/@python2/socket.pyi +++ b/stdlib/@python2/socket.pyi @@ -377,7 +377,7 @@ _Address = Union[tuple[Any, ...], str] _RetAddress = Any # TODO Most methods allow bytes as address objects -_WriteBuffer = Union[bytearray, memoryview] +_WriteBuffer = bytearray | memoryview _CMSG = tuple[int, int, bytes] diff --git a/stdlib/@python2/sre_parse.pyi b/stdlib/@python2/sre_parse.pyi index c4307bb9b..81f14aca6 100644 --- a/stdlib/@python2/sre_parse.pyi +++ b/stdlib/@python2/sre_parse.pyi @@ -1,4 +1,4 @@ -from typing import Any, Iterable, Match, Optional, Pattern as _Pattern, Union +from typing import Any, Iterable, Match, Optional, Pattern as _Pattern SPECIAL_CHARS: str REPEAT_CHARS: str @@ -25,8 +25,8 @@ _OpSubpatternType = tuple[Optional[int], int, int, SubPattern] _OpGroupRefExistsType = tuple[int, SubPattern, SubPattern] _OpInType = list[tuple[str, int]] _OpBranchType = tuple[None, list[SubPattern]] -_AvType = Union[_OpInType, _OpBranchType, Iterable[SubPattern], _OpGroupRefExistsType, _OpSubpatternType] -_CodeType = Union[str, _AvType] +_AvType = _OpInType | _OpBranchType | Iterable[SubPattern] | _OpGroupRefExistsType | _OpSubpatternType +_CodeType = str | _AvType class SubPattern: pattern: str diff --git a/stdlib/@python2/ssl.pyi b/stdlib/@python2/ssl.pyi index 4eccf5875..2c6b32567 100644 --- a/stdlib/@python2/ssl.pyi +++ b/stdlib/@python2/ssl.pyi @@ -1,18 +1,18 @@ import socket import sys from _typeshed import Self, StrPath -from typing import Any, Callable, ClassVar, Iterable, NamedTuple, Optional, Text, Union, overload +from typing import Any, Callable, ClassVar, Iterable, NamedTuple, Text, Union, overload from typing_extensions import Literal _PCTRTT = tuple[tuple[str, str], ...] _PCTRTTT = tuple[_PCTRTT, ...] -_PeerCertRetDictType = dict[str, Union[str, _PCTRTTT, _PCTRTT]] -_PeerCertRetType = Union[_PeerCertRetDictType, bytes, None] +_PeerCertRetDictType = dict[str, str | _PCTRTTT | _PCTRTT] +_PeerCertRetType = _PeerCertRetDictType | bytes | None _EnumRetType = list[tuple[bytes, str, Union[set[str], bool]]] -_PasswordType = Union[Callable[[], Union[str, bytes]], str, bytes] +_PasswordType = Union[Callable[[], str | bytes], str, bytes] _SC1ArgT = SSLSocket -_SrvnmeCbType = Callable[[_SC1ArgT, Optional[str], SSLSocket], Optional[int]] +_SrvnmeCbType = Callable[[_SC1ArgT, str | None, SSLSocket], int | None] class SSLError(OSError): library: str diff --git a/stdlib/@python2/struct.pyi b/stdlib/@python2/struct.pyi index 7129fbc4c..0296c7370 100644 --- a/stdlib/@python2/struct.pyi +++ b/stdlib/@python2/struct.pyi @@ -1,12 +1,12 @@ from array import array from mmap import mmap -from typing import Any, Text, Union +from typing import Any, Text class error(Exception): ... -_FmtType = Union[bytes, Text] -_BufferType = Union[array[int], bytes, bytearray, buffer, memoryview, mmap] -_WriteBufferType = Union[array[Any], bytearray, buffer, memoryview, mmap] +_FmtType = bytes | Text +_BufferType = array[int] | bytes | bytearray | buffer | memoryview | mmap +_WriteBufferType = array[Any] | bytearray | buffer | memoryview | mmap def pack(fmt: _FmtType, *v: Any) -> bytes: ... def pack_into(fmt: _FmtType, buffer: _WriteBufferType, offset: int, *v: Any) -> None: ... diff --git a/stdlib/@python2/subprocess.pyi b/stdlib/@python2/subprocess.pyi index d2149c81a..e6ab3dfcb 100644 --- a/stdlib/@python2/subprocess.pyi +++ b/stdlib/@python2/subprocess.pyi @@ -1,9 +1,9 @@ -from typing import IO, Any, Callable, Generic, Mapping, Optional, Sequence, Text, TypeVar, Union +from typing import IO, Any, Callable, Generic, Mapping, Sequence, Text, TypeVar -_FILE = Union[None, int, IO[Any]] -_TXT = Union[bytes, Text] -_CMD = Union[_TXT, Sequence[_TXT]] -_ENV = Union[Mapping[bytes, _TXT], Mapping[Text, _TXT]] +_FILE = None | int | IO[Any] +_TXT = bytes | Text +_CMD = _TXT | Sequence[_TXT] +_ENV = Mapping[bytes, _TXT] | Mapping[Text, _TXT] # Same args as Popen.__init__ def call( diff --git a/stdlib/@python2/sunau.pyi b/stdlib/@python2/sunau.pyi index 6d5caee7b..85b4d12b4 100644 --- a/stdlib/@python2/sunau.pyi +++ b/stdlib/@python2/sunau.pyi @@ -1,6 +1,6 @@ -from typing import IO, Any, NoReturn, Text, Union +from typing import IO, Any, NoReturn, Text -_File = Union[Text, IO[bytes]] +_File = Text | IO[bytes] class Error(Exception): ... diff --git a/stdlib/@python2/termios.pyi b/stdlib/@python2/termios.pyi index 6ef2f6818..c6a90df31 100644 --- a/stdlib/@python2/termios.pyi +++ b/stdlib/@python2/termios.pyi @@ -1,9 +1,9 @@ import sys from _typeshed import FileDescriptorLike -from typing import Any, Union +from typing import Any if sys.platform != "win32": - _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/@python2/threading.pyi b/stdlib/@python2/threading.pyi index 611552dc9..b62b3a121 100644 --- a/stdlib/@python2/threading.pyi +++ b/stdlib/@python2/threading.pyi @@ -1,8 +1,8 @@ from types import FrameType, TracebackType -from typing import Any, Callable, Iterable, Mapping, Optional, Text, TypeVar +from typing import Any, Callable, Iterable, Mapping, Text, 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] diff --git a/stdlib/@python2/timeit.pyi b/stdlib/@python2/timeit.pyi index 3a7f6e0e0..b95c89fa3 100644 --- a/stdlib/@python2/timeit.pyi +++ b/stdlib/@python2/timeit.pyi @@ -1,8 +1,8 @@ -from typing import IO, Any, Callable, Sequence, Text, Union +from typing import IO, Any, Callable, Sequence, Text -_str = Union[str, Text] +_str = str | Text _Timer = Callable[[], float] -_stmt = Union[_str, Callable[[], Any]] +_stmt = _str | Callable[[], Any] default_timer: _Timer diff --git a/stdlib/@python2/tty.pyi b/stdlib/@python2/tty.pyi index 56e85108c..fc7e90bc0 100644 --- a/stdlib/@python2/tty.pyi +++ b/stdlib/@python2/tty.pyi @@ -1,7 +1,7 @@ import sys -from typing import IO, Union +from typing import IO -_FD = Union[int, IO[str]] +_FD = int | IO[str] if sys.platform != "win32": # XXX: Undocumented integer constants diff --git a/stdlib/@python2/turtle.pyi b/stdlib/@python2/turtle.pyi index cb5247986..7b104bec7 100644 --- a/stdlib/@python2/turtle.pyi +++ b/stdlib/@python2/turtle.pyi @@ -15,7 +15,7 @@ _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/@python2/unittest.pyi b/stdlib/@python2/unittest.pyi index 9db413d99..887e70552 100644 --- a/stdlib/@python2/unittest.pyi +++ b/stdlib/@python2/unittest.pyi @@ -10,7 +10,7 @@ _FT = TypeVar("_FT") _P = ParamSpec("_P") _ExceptionType = Union[type[BaseException], tuple[type[BaseException], ...]] -_Regexp = Union[Text, Pattern[Text]] +_Regexp = Text | Pattern[Text] _SysExcInfoType = Union[tuple[type[BaseException], BaseException, types.TracebackType], tuple[None, None, None]] diff --git a/stdlib/@python2/urllib2.pyi b/stdlib/@python2/urllib2.pyi index 990384ebd..1ea1bce28 100644 --- a/stdlib/@python2/urllib2.pyi +++ b/stdlib/@python2/urllib2.pyi @@ -1,9 +1,9 @@ import ssl from httplib import HTTPConnectionProtocol, HTTPResponse -from typing import Any, AnyStr, Callable, Mapping, Sequence, Text, Union +from typing import Any, AnyStr, Callable, Mapping, Sequence, Text from urllib import addinfourl -_string = Union[str, unicode] +_string = str | unicode class URLError(IOError): reason: str | BaseException diff --git a/stdlib/@python2/urlparse.pyi b/stdlib/@python2/urlparse.pyi index 625928a74..16c32753c 100644 --- a/stdlib/@python2/urlparse.pyi +++ b/stdlib/@python2/urlparse.pyi @@ -1,6 +1,6 @@ -from typing import AnyStr, NamedTuple, Sequence, Union, overload +from typing import AnyStr, NamedTuple, Sequence, overload -_String = Union[str, unicode] +_String = str | unicode uses_relative: list[str] uses_netloc: list[str] diff --git a/stdlib/@python2/uu.pyi b/stdlib/@python2/uu.pyi index e8717aecb..a9585bac6 100644 --- a/stdlib/@python2/uu.pyi +++ b/stdlib/@python2/uu.pyi @@ -1,6 +1,6 @@ -from typing import BinaryIO, Text, Union +from typing import BinaryIO, Text -_File = Union[Text, BinaryIO] +_File = Text | BinaryIO class Error(Exception): ... diff --git a/stdlib/@python2/wave.pyi b/stdlib/@python2/wave.pyi index ceae30114..d13f74664 100644 --- a/stdlib/@python2/wave.pyi +++ b/stdlib/@python2/wave.pyi @@ -1,6 +1,6 @@ -from typing import IO, Any, BinaryIO, NoReturn, Text, Union +from typing import IO, Any, BinaryIO, NoReturn, Text -_File = Union[Text, IO[bytes]] +_File = Text | IO[bytes] class Error(Exception): ... diff --git a/stdlib/@python2/xml/etree/ElementTree.pyi b/stdlib/@python2/xml/etree/ElementTree.pyi index a6cbae35d..f17ae5211 100644 --- a/stdlib/@python2/xml/etree/ElementTree.pyi +++ b/stdlib/@python2/xml/etree/ElementTree.pyi @@ -12,7 +12,6 @@ from typing import ( Sequence, Text, TypeVar, - Union, overload, ) @@ -29,7 +28,7 @@ _T = TypeVar("_T") # Type for parser inputs. Parser will accept any unicode/str/bytes and coerce, # and this is true in py2 and py3 (even fromstringlist() in python3 can be # called with a heterogeneous list) -_parser_input_type = Union[bytes, Text] +_parser_input_type = bytes | Text # Type for individual tag/attr/ns/text values in args to most functions. # In py2, the library accepts str or unicode everywhere and coerces @@ -38,7 +37,7 @@ _parser_input_type = Union[bytes, Text] # so we exclude it. (why? the parser never produces bytes when it parses XML, # so e.g., element.get(b'name') will always return None for parsed XML, even if # there is a 'name' attribute.) -_str_argument_type = Union[str, Text] +_str_argument_type = str | Text # Type for return values from individual tag/attr/text values # in python2, if the tag/attribute/text wasn't decode-able as ascii, it @@ -46,7 +45,7 @@ _str_argument_type = Union[str, Text] # _fixtext function in the source). Client code knows best: _str_result_type = Any -_file_or_filename = Union[Text, FileDescriptor, IO[Any]] +_file_or_filename = Text | FileDescriptor | IO[Any] class Element(MutableSequence[Element]): tag: _str_result_type diff --git a/stdlib/@python2/xmlrpclib.pyi b/stdlib/@python2/xmlrpclib.pyi index 0defb96bf..8d2766e65 100644 --- a/stdlib/@python2/xmlrpclib.pyi +++ b/stdlib/@python2/xmlrpclib.pyi @@ -10,7 +10,7 @@ from typing import IO, Any, AnyStr, Callable, Iterable, Mapping, MutableMapping, _Unmarshaller = Any _timeTuple = tuple[int, int, int, int, int, int, int, int, int] # Represents types that can be compared against a DateTime object -_dateTimeComp = Union[unicode, DateTime, datetime] +_dateTimeComp = unicode | DateTime | datetime # A "host description" used by Transport factories _hostDesc = Union[str, tuple[str, Mapping[Any, Any]]] diff --git a/stdlib/@python2/zipfile.pyi b/stdlib/@python2/zipfile.pyi index 0f376d2d9..777692598 100644 --- a/stdlib/@python2/zipfile.pyi +++ b/stdlib/@python2/zipfile.pyi @@ -1,9 +1,9 @@ import io from _typeshed import Self, StrPath from types import TracebackType -from typing import IO, Any, Callable, Iterable, Pattern, Protocol, Sequence, Text, Union +from typing import IO, Any, Callable, Iterable, Pattern, Protocol, Sequence, Text -_SZI = Union[Text, ZipInfo] +_SZI = Text | ZipInfo _DT = tuple[int, int, int, int, int, int] class BadZipfile(Exception): ... diff --git a/stdlib/_codecs.pyi b/stdlib/_codecs.pyi index 470722a29..1781a2418 100644 --- a/stdlib/_codecs.pyi +++ b/stdlib/_codecs.pyi @@ -1,12 +1,12 @@ import codecs import sys -from typing import Any, Callable, Union +from typing import Any, Callable # 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/_curses.pyi b/stdlib/_curses.pyi index 702209762..e193759bd 100644 --- a/stdlib/_curses.pyi +++ b/stdlib/_curses.pyi @@ -1,10 +1,10 @@ import sys from _typeshed import SupportsRead -from typing import IO, Any, NamedTuple, Union, overload +from typing import IO, Any, NamedTuple, overload from typing_extensions import final if sys.platform != "win32": - _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 f63bec448..630ca3392 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, TypeVar +from typing import Any, Callable, Iterable, Mapping, 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/_typeshed/__init__.pyi b/stdlib/_typeshed/__init__.pyi index 103af47c7..73b1f9054 100644 --- a/stdlib/_typeshed/__init__.pyi +++ b/stdlib/_typeshed/__init__.pyi @@ -7,7 +7,7 @@ import ctypes import mmap import sys from os import PathLike -from typing import AbstractSet, Any, Container, Generic, Iterable, Protocol, TypeVar, Union +from typing import AbstractSet, Any, Container, Generic, Iterable, Protocol, TypeVar from typing_extensions import Final, Literal, final _KT = TypeVar("_KT") @@ -51,7 +51,7 @@ class SupportsDunderGE(Protocol): class SupportsAllComparisons(SupportsDunderLT, SupportsDunderGT, SupportsDunderLE, SupportsDunderGE, Protocol): ... -SupportsRichComparison = Union[SupportsDunderLT, SupportsDunderGT] +SupportsRichComparison = SupportsDunderLT | SupportsDunderGT SupportsRichComparisonT = TypeVar("SupportsRichComparisonT", bound=SupportsRichComparison) # noqa: Y001 class SupportsDivMod(Protocol[_T_contra, _T_co]): @@ -88,9 +88,9 @@ class SupportsItemAccess(SupportsGetItem[_KT_contra, _VT], Protocol[_KT_contra, def __delitem__(self, __v: _KT_contra) -> None: ... # These aliases are simple strings in Python 2. -StrPath = Union[str, PathLike[str]] # stable -BytesPath = Union[bytes, PathLike[bytes]] # stable -StrOrBytesPath = Union[str, bytes, PathLike[str], PathLike[bytes]] # stable +StrPath = str | PathLike[str] # stable +BytesPath = bytes | PathLike[bytes] # stable +StrOrBytesPath = str | bytes | PathLike[str] | PathLike[bytes] # stable OpenTextModeUpdating = Literal[ "r+", @@ -128,7 +128,7 @@ OpenTextModeUpdating = Literal[ ] OpenTextModeWriting = Literal["w", "wt", "tw", "a", "at", "ta", "x", "xt", "tx"] OpenTextModeReading = Literal["r", "rt", "tr", "U", "rU", "Ur", "rtU", "rUt", "Urt", "trU", "tUr", "Utr"] -OpenTextMode = Union[OpenTextModeUpdating, OpenTextModeWriting, OpenTextModeReading] +OpenTextMode = OpenTextModeUpdating | OpenTextModeWriting | OpenTextModeReading OpenBinaryModeUpdating = Literal[ "rb+", "r+b", @@ -157,14 +157,14 @@ OpenBinaryModeUpdating = Literal[ ] OpenBinaryModeWriting = Literal["wb", "bw", "ab", "ba", "xb", "bx"] OpenBinaryModeReading = Literal["rb", "br", "rbU", "rUb", "Urb", "brU", "bUr", "Ubr"] -OpenBinaryMode = Union[OpenBinaryModeUpdating, OpenBinaryModeReading, OpenBinaryModeWriting] +OpenBinaryMode = OpenBinaryModeUpdating | OpenBinaryModeReading | OpenBinaryModeWriting # stable class HasFileno(Protocol): def fileno(self) -> int: ... FileDescriptor = int # stable -FileDescriptorLike = Union[int, HasFileno] # stable +FileDescriptorLike = int | HasFileno # stable # stable class SupportsRead(Protocol[_T_co]): @@ -186,9 +186,9 @@ ReadOnlyBuffer = bytes # stable # Anything that implements the read-write buffer interface. # The buffer interface is defined purely on the C level, so we cannot define a normal Protocol # for it. Instead we have to list the most common stdlib buffer classes in a Union. -WriteableBuffer = Union[bytearray, memoryview, array.array[Any], mmap.mmap, ctypes._CData] # stable +WriteableBuffer = bytearray | memoryview | array.array[Any] | mmap.mmap | ctypes._CData # stable # Same as _WriteableBuffer, but also includes read-only buffer types (like bytes). -ReadableBuffer = Union[ReadOnlyBuffer, WriteableBuffer] # stable +ReadableBuffer = ReadOnlyBuffer | WriteableBuffer # stable # stable if sys.version_info >= (3, 10): diff --git a/stdlib/aifc.pyi b/stdlib/aifc.pyi index 8fc188980..db3d8d991 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, Union, overload +from typing import IO, Any, NamedTuple, overload from typing_extensions import Literal if sys.version_info >= (3, 9): @@ -19,7 +19,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 a13052707..69b4d35d9 100644 --- a/stdlib/array.pyi +++ b/stdlib/array.pyi @@ -1,12 +1,12 @@ import sys from _typeshed import Self -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 1d52942bf..9eea2e166 100644 --- a/stdlib/asyncio/base_events.pyi +++ b/stdlib/asyncio/base_events.pyi @@ -8,7 +8,7 @@ from asyncio.tasks import Task from asyncio.transports import BaseTransport, ReadTransport, SubprocessTransport, WriteTransport from collections.abc import Iterable from socket import AddressFamily, SocketKind, _Address, _RetAddress, socket -from typing import IO, Any, Awaitable, Callable, Coroutine, Generator, Sequence, TypeVar, Union, overload +from typing import IO, Any, Awaitable, Callable, Coroutine, Generator, Sequence, TypeVar, overload from typing_extensions import Literal if sys.version_info >= (3, 7): @@ -23,7 +23,7 @@ _ProtocolT = TypeVar("_ProtocolT", bound=BaseProtocol) _Context = dict[str, Any] _ExceptionHandler = Callable[[AbstractEventLoop, _Context], Any] _ProtocolFactory = Callable[[], BaseProtocol] -_SSLContext = Union[bool, None, ssl.SSLContext] +_SSLContext = bool | None | ssl.SSLContext class Server(AbstractServer): if sys.version_info >= (3, 7): diff --git a/stdlib/asyncio/base_subprocess.pyi b/stdlib/asyncio/base_subprocess.pyi index 94c7c01dd..21c56bde1 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, Union +from typing import IO, Any, Callable, Sequence 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 37079dc09..fbd09ec5c 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, Coroutine, Generator, Sequence, TypeVar, Union, overload +from typing import IO, Any, Awaitable, Callable, Coroutine, Generator, Sequence, TypeVar, overload from typing_extensions import Literal from .base_events import Server @@ -78,7 +78,7 @@ _ProtocolT = TypeVar("_ProtocolT", bound=BaseProtocol) _Context = dict[str, Any] _ExceptionHandler = Callable[[AbstractEventLoop, _Context], Any] _ProtocolFactory = Callable[[], BaseProtocol] -_SSLContext = Union[bool, None, ssl.SSLContext] +_SSLContext = bool | None | ssl.SSLContext class Handle: _cancelled: bool diff --git a/stdlib/asyncio/format_helpers.pyi b/stdlib/asyncio/format_helpers.pyi index bf4412264..5e483a578 100644 --- a/stdlib/asyncio/format_helpers.pyi +++ b/stdlib/asyncio/format_helpers.pyi @@ -1,12 +1,12 @@ import functools 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] @overload def _get_function_source(func: _FuncType) -> tuple[str, int]: ... diff --git a/stdlib/asyncio/streams.pyi b/stdlib/asyncio/streams.pyi index 2b0993ee0..1fd7c31c7 100644 --- a/stdlib/asyncio/streams.pyi +++ b/stdlib/asyncio/streams.pyi @@ -1,6 +1,6 @@ import sys from _typeshed import Self, 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 @@ -64,7 +64,7 @@ else: "start_unix_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 f2725a899..3a617d6fb 100644 --- a/stdlib/asyncio/subprocess.pyi +++ b/stdlib/asyncio/subprocess.pyi @@ -2,7 +2,7 @@ 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, 7): @@ -13,7 +13,7 @@ else: 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/tasks.pyi b/stdlib/asyncio/tasks.pyi index 140fc106b..885688065 100644 --- a/stdlib/asyncio/tasks.pyi +++ b/stdlib/asyncio/tasks.pyi @@ -2,7 +2,7 @@ import concurrent.futures import sys from collections.abc import Awaitable, Generator, Iterable, Iterator from types import FrameType -from typing import Any, Coroutine, Generic, Optional, TextIO, TypeVar, Union, overload +from typing import Any, Coroutine, Generic, TextIO, TypeVar, overload from typing_extensions import Literal from .events import AbstractEventLoop @@ -56,8 +56,8 @@ _T3 = TypeVar("_T3") _T4 = TypeVar("_T4") _T5 = TypeVar("_T5") _FT = TypeVar("_FT", bound=Future[Any]) -_FutureT = Union[Future[_T], Generator[Any, None, _T], Awaitable[_T]] -_TaskYieldType = Optional[Future[object]] +_FutureT = Future[_T] | Generator[Any, None, _T] | Awaitable[_T] +_TaskYieldType = Future[object] | None FIRST_COMPLETED = concurrent.futures.FIRST_COMPLETED FIRST_EXCEPTION = concurrent.futures.FIRST_EXCEPTION diff --git a/stdlib/asyncio/trsock.pyi b/stdlib/asyncio/trsock.pyi index 5bbdadf8c..7973704d7 100644 --- a/stdlib/asyncio/trsock.pyi +++ b/stdlib/asyncio/trsock.pyi @@ -7,7 +7,7 @@ from typing import Any, BinaryIO, Iterable, NoReturn, Union, overload # These are based in socket, maybe move them out into _typeshed.pyi or such _Address = Union[tuple[Any, ...], str] _RetAddress = Any -_WriteBuffer = Union[bytearray, memoryview] +_WriteBuffer = bytearray | memoryview _CMSG = tuple[int, int, bytes] class TransportSocket: diff --git a/stdlib/binhex.pyi b/stdlib/binhex.pyi index e531ccd50..db002503c 100644 --- a/stdlib/binhex.pyi +++ b/stdlib/binhex.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, Union +from typing import IO, Any from typing_extensions import Literal __all__ = ["binhex", "hexbin", "Error"] @@ -16,7 +16,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 176d07a9d..c668ca40e 100644 --- a/stdlib/builtins.pyi +++ b/stdlib/builtins.pyi @@ -1252,7 +1252,7 @@ def next(__i: SupportsNext[_T]) -> _T: ... def next(__i: SupportsNext[_T], __default: _VT) -> _T | _VT: ... def oct(__number: int | SupportsIndex) -> str: ... -_OpenFile = Union[StrOrBytesPath, int] +_OpenFile = StrOrBytesPath | int _Opener = Callable[[str, int], int] # Text mode: always returns a TextIOWrapper @@ -1371,7 +1371,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/cmath.pyi b/stdlib/cmath.pyi index 04c2b632d..ee51861fd 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 6b0432637..55df2ce58 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, Optional, Pattern, TypeVar, overload +from typing import Any, ClassVar, Pattern, TypeVar, overload from typing_extensions import Literal __all__ = [ @@ -205,7 +205,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 c2731dea7..294fb2c0f 100644 --- a/stdlib/contextlib.pyi +++ b/stdlib/contextlib.pyi @@ -12,7 +12,6 @@ from typing import ( # noqa Y027 Generator, Generic, Iterator, - Optional, Protocol, TypeVar, overload, @@ -87,11 +86,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]], Optional[bool]] +_ExitFunc = Callable[[type[BaseException] | None, BaseException | None, TracebackType | None], bool | None] _CM_EF = TypeVar("_CM_EF", AbstractContextManager[Any], _ExitFunc) class ContextDecorator: @@ -190,7 +189,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]] _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 d4caa7a88..7513948e6 100644 --- a/stdlib/ctypes/__init__.pyi +++ b/stdlib/ctypes/__init__.pyi @@ -134,12 +134,12 @@ class _CArgObject: ... # Any type that can be implicitly converted to c_void_p when passed as a C function argument. # (bytes is not included here, see below.) -_CVoidPLike = _UnionT[_PointerLike, Array[Any], _CArgObject, int] +_CVoidPLike = _PointerLike | Array[Any] | _CArgObject | int # Same as above, but including types known to be read-only (i. e. bytes). # This distinction is not strictly necessary (ctypes doesn't differentiate between const # and non-const pointers), but it catches errors like memmove(b'foo', buf, 4) # when memmove(buf, b'foo', 4) was intended. -_CVoidConstPLike = _UnionT[_CVoidPLike, bytes] +_CVoidConstPLike = _CVoidPLike | bytes def addressof(obj: _CData) -> int: ... def alignment(obj_or_type: _CData | type[_CData]) -> int: ... @@ -208,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]): ... @@ -233,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 630a0d16c..d43a2415c 100644 --- a/stdlib/dbm/__init__.pyi +++ b/stdlib/dbm/__init__.pyi @@ -1,12 +1,12 @@ from _typeshed import Self from types import TracebackType -from typing import Iterator, MutableMapping, Union +from typing import Iterator, MutableMapping from typing_extensions import Literal __all__ = ["open", "whichdb", "error"] -_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 c877ef859..5af95ace7 100644 --- a/stdlib/dbm/dumb.pyi +++ b/stdlib/dbm/dumb.pyi @@ -1,11 +1,11 @@ from _typeshed import Self from types import TracebackType -from typing import Iterator, MutableMapping, Union +from typing import Iterator, MutableMapping __all__ = ["error", "open"] -_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 b0e657d6a..9a603228a 100644 --- a/stdlib/dbm/gnu.pyi +++ b/stdlib/dbm/gnu.pyi @@ -1,12 +1,12 @@ import sys from _typeshed import Self from types import TracebackType -from typing import TypeVar, Union, overload +from typing import TypeVar, overload if sys.platform != "win32": _T = TypeVar("_T") - _KeyType = Union[str, bytes] - _ValueType = Union[str, bytes] + _KeyType = str | bytes + _ValueType = str | bytes open_flags: str diff --git a/stdlib/dbm/ndbm.pyi b/stdlib/dbm/ndbm.pyi index 336720c79..8405bec2b 100644 --- a/stdlib/dbm/ndbm.pyi +++ b/stdlib/dbm/ndbm.pyi @@ -1,12 +1,12 @@ import sys from _typeshed import Self from types import TracebackType -from typing import TypeVar, Union, overload +from typing import TypeVar, overload if sys.platform != "win32": _T = TypeVar("_T") - _KeyType = Union[str, bytes] - _ValueType = Union[str, bytes] + _KeyType = str | bytes + _ValueType = str | bytes class error(OSError): ... library: str diff --git a/stdlib/decimal.pyi b/stdlib/decimal.pyi index dfd0670e4..819ed1641 100644 --- a/stdlib/decimal.pyi +++ b/stdlib/decimal.pyi @@ -4,9 +4,9 @@ from _typeshed import Self from types import TracebackType from typing import Any, Container, NamedTuple, Sequence, Union, overload -_Decimal = Union[Decimal, int] +_Decimal = Decimal | int _DecimalNew = Union[Decimal, float, str, tuple[int, Sequence[int], int]] -_ComparableNum = Union[Decimal, float, numbers.Rational] +_ComparableNum = Decimal | float | numbers.Rational __libmpdec_version__: str diff --git a/stdlib/dis.pyi b/stdlib/dis.pyi index dcb82cb7a..910458c08 100644 --- a/stdlib/dis.pyi +++ b/stdlib/dis.pyi @@ -2,7 +2,7 @@ import sys import types from _typeshed import Self from opcode import * # `dis` re-exports it as a part of public API -from typing import IO, Any, Callable, Iterator, NamedTuple, Union +from typing import IO, Any, Callable, Iterator, NamedTuple __all__ = [ "code_info", @@ -34,8 +34,8 @@ __all__ = [ # 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/email/_header_value_parser.pyi b/stdlib/email/_header_value_parser.pyi index 18d5f1b9a..749b6454a 100644 --- a/stdlib/email/_header_value_parser.pyi +++ b/stdlib/email/_header_value_parser.pyi @@ -2,7 +2,7 @@ import sys from _typeshed import Self from email.errors import HeaderParseError, MessageDefect from email.policy import Policy -from typing import Any, Iterable, Iterator, Pattern, Union +from typing import Any, Iterable, Iterator, Pattern from typing_extensions import Final WSP: Final[set[str]] @@ -22,7 +22,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/email/message.pyi b/stdlib/email/message.pyi index d6857328a..42c25c798 100644 --- a/stdlib/email/message.pyi +++ b/stdlib/email/message.pyi @@ -10,8 +10,8 @@ __all__ = ["Message", "EmailMessage"] _T = TypeVar("_T") -_PayloadType = Union[list[Message], str, bytes] -_CharsetType = Union[Charset, str, None] +_PayloadType = list[Message] | str | bytes +_CharsetType = Charset | str | None _ParamsType = Union[str, None, tuple[str, Optional[str], str]] _ParamType = Union[str, tuple[Optional[str], Optional[str], str]] diff --git a/stdlib/enum.pyi b/stdlib/enum.pyi index 077a2f423..a7075e030 100644 --- a/stdlib/enum.pyi +++ b/stdlib/enum.pyi @@ -4,7 +4,7 @@ from _typeshed import Self from abc import ABCMeta from builtins import property as _builtins_property from collections.abc import Iterable, Iterator, Mapping -from typing import Any, TypeVar, Union, overload +from typing import Any, TypeVar, overload from typing_extensions import Literal if sys.version_info >= (3, 11): @@ -52,7 +52,7 @@ _EnumerationT = TypeVar("_EnumerationT", 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 ecbfb07e1..00989fb1f 100644 --- a/stdlib/fractions.pyi +++ b/stdlib/fractions.pyi @@ -2,10 +2,10 @@ import sys from _typeshed import Self from decimal import Decimal from numbers import Integral, Rational, Real -from typing import Any, Union, overload +from typing import Any, overload from typing_extensions import Literal -_ComparableNum = Union[int, float, Decimal, Real] +_ComparableNum = int | float | Decimal | Real if sys.version_info >= (3, 9): __all__ = ["Fraction"] diff --git a/stdlib/hmac.pyi b/stdlib/hmac.pyi index fbb0397ac..6d355147f 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 trans_5C: bytes trans_36: bytes diff --git a/stdlib/http/client.pyi b/stdlib/http/client.pyi index 857d69db7..64452dc70 100644 --- a/stdlib/http/client.pyi +++ b/stdlib/http/client.pyi @@ -5,7 +5,7 @@ import sys import types from _typeshed import Self, WriteableBuffer from socket import socket -from typing import IO, Any, BinaryIO, Callable, Iterable, Iterator, Mapping, Protocol, TypeVar, Union, overload +from typing import IO, Any, BinaryIO, Callable, Iterable, Iterator, Mapping, Protocol, TypeVar, overload __all__ = [ "HTTPResponse", @@ -29,7 +29,7 @@ __all__ = [ "HTTPSConnection", ] -_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 5e01e6037..2cc05961a 100644 --- a/stdlib/http/cookies.pyi +++ b/stdlib/http/cookies.pyi @@ -1,12 +1,12 @@ import sys -from typing import Any, Generic, Iterable, Mapping, TypeVar, Union, overload +from typing import Any, Generic, Iterable, Mapping, TypeVar, overload if sys.version_info >= (3, 9): from types import GenericAlias __all__ = ["CookieError", "BaseCookie", "SimpleCookie"] -_DataType = Union[str, Mapping[str, Union[str, Morsel[Any]]]] +_DataType = str | Mapping[str, str | Morsel[Any]] _T = TypeVar("_T") @overload diff --git a/stdlib/importlib/abc.pyi b/stdlib/importlib/abc.pyi index 16f514a74..877f8ff1a 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, runtime_checkable +from typing import IO, Any, BinaryIO, Iterator, Mapping, NoReturn, Protocol, Sequence, overload, runtime_checkable from typing_extensions import Literal -_Path = Union[bytes, str] +_Path = bytes | str class Finder(metaclass=ABCMeta): ... diff --git a/stdlib/importlib/resources.pyi b/stdlib/importlib/resources.pyi index cee325933..e6e3035e5 100644 --- a/stdlib/importlib/resources.pyi +++ b/stdlib/importlib/resources.pyi @@ -3,7 +3,7 @@ import sys from contextlib import AbstractContextManager from pathlib import Path from types import ModuleType -from typing import Any, BinaryIO, Iterator, TextIO, Union +from typing import Any, BinaryIO, Iterator, TextIO if sys.version_info >= (3, 10): __all__ = [ @@ -37,8 +37,8 @@ elif sys.version_info >= (3, 9): else: __all__ = ["Package", "Resource", "contents", "is_resource", "open_binary", "open_text", "path", "read_binary", "read_text"] -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: ... diff --git a/stdlib/itertools.pyi b/stdlib/itertools.pyi index 357657122..bec03b187 100644 --- a/stdlib/itertools.pyi +++ b/stdlib/itertools.pyi @@ -1,18 +1,6 @@ import sys from _typeshed import Self, _T_co -from typing import ( - Any, - Callable, - Generic, - Iterable, - Iterator, - SupportsComplex, - SupportsFloat, - SupportsInt, - TypeVar, - Union, - overload, -) +from typing import Any, Callable, Generic, Iterable, Iterator, SupportsComplex, SupportsFloat, SupportsInt, TypeVar, overload from typing_extensions import Literal, SupportsIndex if sys.version_info >= (3, 9): @@ -21,7 +9,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/pytree.pyi b/stdlib/lib2to3/pytree.pyi index b0e61c3a3..ccd347e39 100644 --- a/stdlib/lib2to3/pytree.pyi +++ b/stdlib/lib2to3/pytree.pyi @@ -1,8 +1,8 @@ from _typeshed import Self from lib2to3.pgen2.grammar import Grammar -from typing import Any, Callable, Iterator, Optional, Union +from typing import Any, Callable, Iterator, Optional -_NL = Union[Node, Leaf] +_NL = Node | Leaf _Context = tuple[str, int, int] _Results = dict[str, _NL] _RawNode = tuple[int, str, _Context, Optional[list[_NL]]] diff --git a/stdlib/logging/__init__.pyi b/stdlib/logging/__init__.pyi index c860938c3..ac4631e8c 100644 --- a/stdlib/logging/__init__.pyi +++ b/stdlib/logging/__init__.pyi @@ -55,10 +55,10 @@ __all__ = [ ] _SysExcInfoType = Union[tuple[type[BaseException], BaseException, Optional[TracebackType]], tuple[None, None, None]] -_ExcInfoType = Union[None, bool, _SysExcInfoType, BaseException] +_ExcInfoType = None | bool | _SysExcInfoType | BaseException _ArgsType = Union[tuple[object, ...], Mapping[str, object]] -_FilterType = Union[Filter, Callable[[LogRecord], int]] -_Level = Union[int, str] +_FilterType = Filter | Callable[[LogRecord], int] +_Level = int | str _FormatStyle = Literal["%", "{", "$"] raiseExceptions: bool diff --git a/stdlib/lzma.pyi b/stdlib/lzma.pyi index c469c218a..45bf24b3e 100644 --- a/stdlib/lzma.pyi +++ b/stdlib/lzma.pyi @@ -1,6 +1,6 @@ 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 __all__ = [ @@ -45,7 +45,7 @@ __all__ = [ _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 3fafd8891..143891d32 100644 --- a/stdlib/mailbox.pyi +++ b/stdlib/mailbox.pyi @@ -3,7 +3,7 @@ import sys from _typeshed import Self, StrOrBytesPath from abc import ABCMeta, abstractmethod from types import TracebackType -from typing import IO, Any, AnyStr, Callable, Generic, Iterable, Iterator, Mapping, Protocol, Sequence, TypeVar, Union, overload +from typing import IO, Any, AnyStr, Callable, Generic, Iterable, Iterator, Mapping, Protocol, Sequence, TypeVar, overload from typing_extensions import Literal if sys.version_info >= (3, 9): @@ -31,7 +31,7 @@ __all__ = [ _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 7bf2ebd1b..232ab99c3 100644 --- a/stdlib/mailcap.pyi +++ b/stdlib/mailcap.pyi @@ -1,6 +1,6 @@ -from typing import Mapping, Sequence, Union +from typing import Mapping, Sequence -_Cap = dict[str, Union[str, int]] +_Cap = dict[str, str | int] __all__ = ["getcaps", "findmatch"] diff --git a/stdlib/math.pyi b/stdlib/math.pyi index 2218f6817..e4ab31199 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/multiprocessing/__init__.pyi b/stdlib/multiprocessing/__init__.pyi index 3f489ca43..3a8a382b8 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): @@ -134,7 +134,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/context.pyi b/stdlib/multiprocessing/context.pyi index db8e6216b..315918a04 100644 --- a/stdlib/multiprocessing/context.pyi +++ b/stdlib/multiprocessing/context.pyi @@ -8,7 +8,7 @@ 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, ClassVar, TypeVar, Union, overload +from typing import Any, ClassVar, TypeVar, overload from typing_extensions import Literal if sys.version_info >= (3, 8): @@ -16,7 +16,7 @@ if sys.version_info >= (3, 8): else: __all__: list[str] = [] -_LockLike = Union[synchronize.Lock, synchronize.RLock] +_LockLike = synchronize.Lock | synchronize.RLock _CT = TypeVar("_CT", bound=_CData) class ProcessError(Exception): ... diff --git a/stdlib/multiprocessing/synchronize.pyi b/stdlib/multiprocessing/synchronize.pyi index cb576abcc..0cfc815b2 100644 --- a/stdlib/multiprocessing/synchronize.pyi +++ b/stdlib/multiprocessing/synchronize.pyi @@ -3,11 +3,11 @@ import threading from contextlib import AbstractContextManager from multiprocessing.context import BaseContext from types import TracebackType -from typing import Any, Callable, Union +from typing import Any, Callable __all__ = ["Lock", "RLock", "Semaphore", "BoundedSemaphore", "Condition", "Event"] -_LockLike = Union[Lock, RLock] +_LockLike = Lock | RLock class Barrier(threading.Barrier): def __init__( diff --git a/stdlib/nntplib.pyi b/stdlib/nntplib.pyi index 77cab1e15..1b129b7ec 100644 --- a/stdlib/nntplib.pyi +++ b/stdlib/nntplib.pyi @@ -3,7 +3,7 @@ import socket import ssl import sys from _typeshed import Self -from typing import IO, Any, Iterable, NamedTuple, Union +from typing import IO, Any, Iterable, NamedTuple from typing_extensions import Literal __all__ = [ @@ -18,7 +18,7 @@ __all__ = [ "NNTP_SSL", ] -_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 615dff880..c87ed7e4d 100644 --- a/stdlib/os/__init__.pyi +++ b/stdlib/os/__init__.pyi @@ -382,7 +382,7 @@ def listdir(path: BytesPath) -> list[bytes]: ... @overload def listdir(path: int) -> list[str]: ... -_FdOrAnyPath = Union[int, StrOrBytesPath] +_FdOrAnyPath = int | StrOrBytesPath @final class DirEntry(Generic[AnyStr]): @@ -837,12 +837,12 @@ _ExecVArgs = Union[ 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]]], + list[bytes | str], + list[bytes | PathLike[Any]], + list[str | PathLike[Any]], + list[bytes | str | PathLike[Any]], ] -_ExecEnv = Union[Mapping[bytes, Union[bytes, str]], Mapping[str, Union[bytes, str]]] +_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/pickle.pyi b/stdlib/pickle.pyi index d48d3ead7..3a9fd9c08 100644 --- a/stdlib/pickle.pyi +++ b/stdlib/pickle.pyi @@ -189,7 +189,7 @@ if sys.version_info >= (3, 8): def __init__(self, buffer: Any) -> None: ... def raw(self) -> memoryview: ... def release(self) -> None: ... - _BufferCallback = Optional[Callable[[PickleBuffer], Any]] + _BufferCallback = Callable[[PickleBuffer], Any] | None def dump( obj: Any, file: _WritableFileobj, diff --git a/stdlib/pstats.pyi b/stdlib/pstats.pyi index c4fe28477..a7b8bebe4 100644 --- a/stdlib/pstats.pyi +++ b/stdlib/pstats.pyi @@ -2,7 +2,7 @@ import sys from _typeshed import Self, StrOrBytesPath from cProfile import Profile as _cProfile from profile import Profile -from typing import IO, Any, Iterable, Union, overload +from typing import IO, Any, Iterable, overload from typing_extensions import Literal if sys.version_info >= (3, 9): @@ -12,7 +12,7 @@ elif sys.version_info >= (3, 7): else: __all__ = ["Stats"] -_Selector = Union[str, float, int] +_Selector = str | float | int if sys.version_info >= (3, 7): from enum import Enum diff --git a/stdlib/re.pyi b/stdlib/re.pyi index b9c41e1ca..57dab8eb8 100644 --- a/stdlib/re.pyi +++ b/stdlib/re.pyi @@ -2,7 +2,7 @@ import enum import sre_compile 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): @@ -147,7 +147,7 @@ T = RegexFlag.T TEMPLATE = RegexFlag.TEMPLATE if sys.version_info >= (3, 11): NOFLAG = RegexFlag.NOFLAG -_FlagsType = Union[int, RegexFlag] +_FlagsType = int | RegexFlag if sys.version_info < (3, 7): # undocumented diff --git a/stdlib/shutil.pyi b/stdlib/shutil.pyi index 030f16cd9..5fa5f6669 100644 --- a/stdlib/shutil.pyi +++ b/stdlib/shutil.pyi @@ -1,7 +1,7 @@ import os import sys from _typeshed import BytesPath, 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 __all__ = [ "copyfileobj", @@ -82,7 +82,7 @@ else: def rmtree(path: StrOrBytesPath, 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] # N.B. shutil.move appears to take bytes arguments, however, # this does not work when dst is (or is within) an existing directory. diff --git a/stdlib/signal.pyi b/stdlib/signal.pyi index 50f1e0ff0..632539bf7 100644 --- a/stdlib/signal.pyi +++ b/stdlib/signal.pyi @@ -2,7 +2,7 @@ import sys from _typeshed import structseq from enum import IntEnum from types import FrameType -from typing import Any, Callable, Iterable, Optional, Union +from typing import Any, Callable, Iterable, Union from typing_extensions import final NSIG: int @@ -60,8 +60,8 @@ class Handlers(IntEnum): SIG_DFL: Handlers SIG_IGN: Handlers -_SIGNUM = Union[int, Signals] -_HANDLER = Union[Callable[[int, Optional[FrameType]], Any], int, Handlers, None] +_SIGNUM = int | Signals +_HANDLER = Union[Callable[[int, FrameType | None], Any], int, Handlers, None] def default_int_handler(__signalnum: int, __frame: FrameType | None) -> None: ... diff --git a/stdlib/sre_parse.pyi b/stdlib/sre_parse.pyi index 56d551180..8d50b4419 100644 --- a/stdlib/sre_parse.pyi +++ b/stdlib/sre_parse.pyi @@ -1,7 +1,7 @@ import sys from sre_constants import * from sre_constants import _NamedIntConstant as _NIC, error as _Error -from typing import Any, Iterable, Match, Optional, Pattern as _Pattern, Union, overload +from typing import Any, Iterable, Match, Optional, Pattern as _Pattern, overload SPECIAL_CHARS: str REPEAT_CHARS: str @@ -41,7 +41,7 @@ _OpSubpatternType = tuple[Optional[int], 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: diff --git a/stdlib/ssl.pyi b/stdlib/ssl.pyi index 83932e579..dbf3309c5 100644 --- a/stdlib/ssl.pyi +++ b/stdlib/ssl.pyi @@ -2,17 +2,17 @@ import enum import socket import sys from _typeshed import ReadableBuffer, Self, StrOrBytesPath, WriteableBuffer -from typing import Any, Callable, Iterable, NamedTuple, Optional, Union, overload +from typing import Any, Callable, Iterable, NamedTuple, Union, overload from typing_extensions import Literal, TypedDict, final _PCTRTT = tuple[tuple[str, str], ...] _PCTRTTT = tuple[_PCTRTT, ...] -_PeerCertRetDictType = dict[str, Union[str, _PCTRTTT, _PCTRTT]] -_PeerCertRetType = Union[_PeerCertRetDictType, bytes, None] +_PeerCertRetDictType = dict[str, str | _PCTRTTT | _PCTRTT] +_PeerCertRetType = _PeerCertRetDictType | bytes | None _EnumRetType = list[tuple[bytes, str, Union[set[str], bool]]] -_PasswordType = Union[Callable[[], Union[str, bytes]], str, bytes] +_PasswordType = Union[Callable[[], str | bytes], str, bytes] -_SrvnmeCbType = Callable[[Union[SSLSocket, SSLObject], Optional[str], SSLSocket], Optional[int]] +_SrvnmeCbType = Callable[[SSLSocket | SSLObject, str | None, SSLSocket], int | None] class _Cipher(TypedDict): aead: bool diff --git a/stdlib/statistics.pyi b/stdlib/statistics.pyi index 879ea3c74..446a77879 100644 --- a/stdlib/statistics.pyi +++ b/stdlib/statistics.pyi @@ -2,7 +2,7 @@ import sys from _typeshed import Self, SupportsRichComparisonT from decimal import Decimal from fractions import Fraction -from typing import Any, Hashable, Iterable, NamedTuple, Sequence, SupportsFloat, TypeVar, Union +from typing import Any, Hashable, Iterable, NamedTuple, Sequence, SupportsFloat, TypeVar from typing_extensions import Literal if sys.version_info >= (3, 10): @@ -65,7 +65,7 @@ else: ] # 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 a0e446d19..ced2e708f 100644 --- a/stdlib/subprocess.pyi +++ b/stdlib/subprocess.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import Self, StrOrBytesPath from types import TracebackType -from typing import IO, Any, AnyStr, Callable, Generic, Iterable, Mapping, Sequence, TypeVar, Union, overload +from typing import IO, Any, AnyStr, Callable, Generic, Iterable, Mapping, Sequence, TypeVar, overload from typing_extensions import Literal if sys.version_info >= (3, 9): @@ -102,18 +102,18 @@ else: # reveal_type(x) # bytes, based on the overloads # except TimeoutError as e: # reveal_type(e.cmd) # Any, but morally is _CMD -_FILE = Union[None, int, IO[Any]] -_TXT = Union[bytes, str] +_FILE = None | int | IO[Any] +_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 f96dbaaf7..b5a16f5e2 100644 --- a/stdlib/sunau.pyi +++ b/stdlib/sunau.pyi @@ -1,9 +1,9 @@ import sys from _typeshed import Self -from typing import IO, Any, NamedTuple, NoReturn, Union, overload +from typing import IO, Any, NamedTuple, NoReturn, overload from typing_extensions import Literal -_File = Union[str, IO[bytes]] +_File = str | IO[bytes] class Error(Exception): ... diff --git a/stdlib/sys.pyi b/stdlib/sys.pyi index 89b636cd0..4fca35a2c 100644 --- a/stdlib/sys.pyi +++ b/stdlib/sys.pyi @@ -5,20 +5,7 @@ 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, - Coroutine, - NoReturn, - Optional, - Protocol, - Sequence, - TextIO, - TypeVar, - Union, - overload, -) +from typing import Any, AsyncGenerator, Callable, Coroutine, NoReturn, Protocol, Sequence, TextIO, TypeVar, Union, overload from typing_extensions import Literal, final _T = TypeVar("_T") @@ -255,7 +242,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: ... @@ -322,7 +309,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 @final class _asyncgen_hooks(structseq[_AsyncgenHook], tuple[_AsyncgenHook, _AsyncgenHook]): diff --git a/stdlib/tempfile.pyi b/stdlib/tempfile.pyi index fe8e3af2e..19a4dbee2 100644 --- a/stdlib/tempfile.pyi +++ b/stdlib/tempfile.pyi @@ -2,7 +2,7 @@ import os import sys from _typeshed import Self from types import TracebackType -from typing import IO, Any, AnyStr, Generic, Iterable, Iterator, Union, overload +from typing import IO, Any, AnyStr, Generic, Iterable, Iterator, overload from typing_extensions import Literal if sys.version_info >= (3, 9): @@ -29,7 +29,7 @@ TMP_MAX: int tempdir: str | None template: str -_DirT = Union[AnyStr, os.PathLike[AnyStr]] +_DirT = AnyStr | os.PathLike[AnyStr] if sys.version_info >= (3, 8): @overload diff --git a/stdlib/termios.pyi b/stdlib/termios.pyi index 6ef2f6818..c6a90df31 100644 --- a/stdlib/termios.pyi +++ b/stdlib/termios.pyi @@ -1,9 +1,9 @@ import sys from _typeshed import FileDescriptorLike -from typing import Any, Union +from typing import Any if sys.platform != "win32": - _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 d6a64d0ae..c3fa57faf 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, TypeVar +from typing import Any, Callable, Iterable, Mapping, 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/time.pyi b/stdlib/time.pyi index c1a8727b1..844aba90f 100644 --- a/stdlib/time.pyi +++ b/stdlib/time.pyi @@ -1,6 +1,6 @@ import sys from _typeshed import structseq -from typing import Any, Protocol, Union +from typing import Any, Protocol from typing_extensions import Literal, final _TimeTuple = tuple[int, int, int, int, int, int, int, int, int] @@ -37,7 +37,7 @@ if sys.version_info >= (3, 9) and sys.platform == "linux": # even if an iterable with length >9 is passed. # https://github.com/python/typeshed/pull/6560#discussion_r767162532 @final -class struct_time(structseq[Union[Any, int]], _TimeTuple): +class struct_time(structseq[Any | int], _TimeTuple): @property def tm_year(self) -> int: ... @property diff --git a/stdlib/timeit.pyi b/stdlib/timeit.pyi index 3135c21a6..bfaea728f 100644 --- a/stdlib/timeit.pyi +++ b/stdlib/timeit.pyi @@ -1,9 +1,9 @@ -from typing import IO, Any, Callable, Sequence, Union +from typing import IO, Any, Callable, Sequence __all__ = ["Timer", "timeit", "repeat", "default_timer"] _Timer = Callable[[], float] -_Stmt = Union[str, Callable[[], Any]] +_Stmt = str | Callable[[], Any] default_timer: _Timer diff --git a/stdlib/tkinter/__init__.pyi b/stdlib/tkinter/__init__.pyi index 2393b0e5b..74844e94a 100644 --- a/stdlib/tkinter/__init__.pyi +++ b/stdlib/tkinter/__init__.pyi @@ -5,7 +5,7 @@ from enum import Enum from tkinter.constants import * from tkinter.font import _FontDescription from types import TracebackType -from typing import Any, Callable, Generic, Mapping, Optional, Protocol, Sequence, TypeVar, Union, overload +from typing import Any, Callable, Generic, Mapping, Protocol, Sequence, TypeVar, Union, overload from typing_extensions import Literal, TypedDict if sys.version_info >= (3, 9): @@ -173,7 +173,7 @@ EXCEPTION = _tkinter.EXCEPTION # than the _Compound defined here. Many other options have similar things. _Anchor = Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] # manual page: Tk_GetAnchor _Bitmap = str # manual page: Tk_GetBitmap -_ButtonCommand = Union[str, Callable[[], Any]] # accepts string of tcl code, return value is returned from Button.invoke() +_ButtonCommand = str | Callable[[], Any] # accepts string of tcl code, return value is returned from Button.invoke() _CanvasItemId = int _Color = str # typically '#rrggbb', '#rgb' or color names. _Compound = Literal["top", "left", "center", "right", "bottom", "none"] # -compound in manual page named 'options' @@ -181,8 +181,8 @@ _Cursor = Union[str, tuple[str], tuple[str, str], tuple[str, str, str], tuple[st _EntryValidateCommand = Union[ Callable[[], bool], str, list[str], tuple[str, ...] ] # example when it's sequence: entry['invalidcommand'] = [entry.register(print), '%P'] -_GridIndex = Union[int, str, Literal["all"]] -_ImageSpec = Union[_Image, str] # str can be from e.g. tkinter.image_names() +_GridIndex = int | str | Literal["all"] +_ImageSpec = _Image | str # str can be from e.g. tkinter.image_names() _Padding = Union[ _ScreenUnits, tuple[_ScreenUnits], @@ -191,9 +191,9 @@ _Padding = Union[ tuple[_ScreenUnits, _ScreenUnits, _ScreenUnits, _ScreenUnits], ] _Relief = Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] # manual page: Tk_GetRelief -_ScreenUnits = Union[str, float] # Often the right type instead of int. Manual page: Tk_GetPixels -_XYScrollCommand = Union[str, Callable[[float, float], Any]] # -xscrollcommand and -yscrollcommand in 'options' manual page -_TakeFocusValue = Union[int, Literal[""], Callable[[str], Optional[bool]]] # -takefocus in manual page named 'options' +_ScreenUnits = str | float # Often the right type instead of int. Manual page: Tk_GetPixels +_XYScrollCommand = str | Callable[[float, float], Any] # -xscrollcommand and -yscrollcommand in 'options' manual page +_TakeFocusValue = Union[int, Literal[""], Callable[[str], bool | None]] # -takefocus in manual page named 'options' class EventType(str, Enum): Activate: str @@ -1696,7 +1696,7 @@ class Checkbutton(Widget): def select(self) -> None: ... def toggle(self) -> None: ... -_EntryIndex = Union[str, int] # "INDICES" in manual page +_EntryIndex = str | int # "INDICES" in manual page class Entry(Widget, XView): def __init__( @@ -2054,7 +2054,7 @@ class Listbox(Widget, XView, YView): def itemconfigure(self, index, cnf: Any | None = ..., **kw): ... itemconfig: Any -_MenuIndex = Union[str, int] +_MenuIndex = str | int class Menu(Widget): def __init__( @@ -2740,7 +2740,7 @@ class Scrollbar(Widget): def get(self) -> tuple[float, float, float, float] | tuple[float, float]: ... def set(self, first: float, last: float) -> None: ... -_TextIndex = Union[_tkinter.Tcl_Obj, str, float, Misc] +_TextIndex = _tkinter.Tcl_Obj | str | float | Misc class Text(Widget, XView, YView): def __init__( diff --git a/stdlib/tkinter/ttk.pyi b/stdlib/tkinter/ttk.pyi index 41a5b64c5..c48b5cd7a 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, Union, overload +from typing import Any, Callable, overload from typing_extensions import Literal, TypedDict if sys.version_info >= (3, 7): @@ -972,7 +972,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 e8f64a7d0..7b17e8de6 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 * -from typing import Any, Callable, Generator, Iterable, NamedTuple, Pattern, Sequence, TextIO, Union +from typing import Any, Callable, Generator, Iterable, NamedTuple, Pattern, Sequence, TextIO if sys.version_info >= (3, 10): __all__ = [ @@ -331,7 +331,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/tty.pyi b/stdlib/tty.pyi index 015669a68..63f594a8f 100644 --- a/stdlib/tty.pyi +++ b/stdlib/tty.pyi @@ -1,8 +1,8 @@ import sys -from typing import IO, Union +from typing import IO if sys.platform != "win32": - _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 164ea4613..2ff965465 100644 --- a/stdlib/turtle.pyi +++ b/stdlib/turtle.pyi @@ -137,7 +137,7 @@ _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/suite.pyi b/stdlib/unittest/suite.pyi index f1e168a67..ca483b06a 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 b3cdc73e2..f8ba0988c 100644 --- a/stdlib/urllib/parse.pyi +++ b/stdlib/urllib/parse.pyi @@ -1,5 +1,5 @@ import sys -from typing import Any, AnyStr, Callable, Generic, Mapping, NamedTuple, Sequence, Union, overload +from typing import Any, AnyStr, Callable, Generic, Mapping, NamedTuple, Sequence, overload if sys.version_info >= (3, 9): from types import GenericAlias @@ -28,7 +28,7 @@ __all__ = [ "SplitResultBytes", ] -_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 05aa4afef..d75df67a1 100644 --- a/stdlib/uu.pyi +++ b/stdlib/uu.pyi @@ -1,9 +1,9 @@ import sys -from typing import BinaryIO, Union +from typing import BinaryIO __all__ = ["Error", "encode", "decode"] -_File = Union[str, BinaryIO] +_File = str | BinaryIO class Error(Exception): ... diff --git a/stdlib/wave.pyi b/stdlib/wave.pyi index 13fa12348..8c2edb5b1 100644 --- a/stdlib/wave.pyi +++ b/stdlib/wave.pyi @@ -1,6 +1,6 @@ import sys from _typeshed import ReadableBuffer, Self -from typing import IO, Any, BinaryIO, NamedTuple, NoReturn, Union, overload +from typing import IO, Any, BinaryIO, NamedTuple, NoReturn, overload from typing_extensions import Literal if sys.version_info >= (3, 9): @@ -8,7 +8,7 @@ if sys.version_info >= (3, 9): else: __all__ = ["open", "openfp", "Error", "Wave_read", "Wave_write"] -_File = Union[str, IO[bytes]] +_File = str | IO[bytes] class Error(Exception): ... diff --git a/stdlib/winreg.pyi b/stdlib/winreg.pyi index e55be6b5e..5dc7e4363 100644 --- a/stdlib/winreg.pyi +++ b/stdlib/winreg.pyi @@ -1,11 +1,11 @@ import sys from _typeshed import Self from types import TracebackType -from typing import Any, Union +from typing import Any from typing_extensions import Literal, final if sys.platform == "win32": - _KeyType = Union[HKEYType, int] + _KeyType = HKEYType | int def CloseKey(__hkey: _KeyType) -> None: ... def ConnectRegistry(__computer_name: str | None, __key: _KeyType) -> HKEYType: ... def CreateKey(__key: _KeyType, __sub_key: str | None) -> HKEYType: ... diff --git a/stdlib/xml/dom/pulldom.pyi b/stdlib/xml/dom/pulldom.pyi index 7ae2dcf3e..b2bec64fd 100644 --- a/stdlib/xml/dom/pulldom.pyi +++ b/stdlib/xml/dom/pulldom.pyi @@ -1,6 +1,6 @@ import sys from _typeshed import SupportsRead -from typing import Any, Sequence, Union +from typing import Any, Sequence from typing_extensions import Literal from xml.dom.minidom import Document, DOMImplementation, Element, Text from xml.sax.handler import ContentHandler @@ -15,8 +15,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 0615edb80..ec47ec134 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 @@ -18,13 +18,13 @@ __all__ = ["DOMBuilder", "DOMEntityResolver", "DOMInputSource"] # 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 aef8285ee..7b50b4279 100644 --- a/stdlib/xml/etree/ElementTree.pyi +++ b/stdlib/xml/etree/ElementTree.pyi @@ -12,7 +12,6 @@ from typing import ( MutableSequence, Sequence, TypeVar, - Union, overload, ) from typing_extensions import Literal, SupportsIndex, TypeGuard @@ -102,9 +101,9 @@ else: ] _T = TypeVar("_T") -_FileRead = Union[StrOrBytesPath, FileDescriptor, SupportsRead[bytes], SupportsRead[str]] -_FileWriteC14N = Union[StrOrBytesPath, FileDescriptor, SupportsWrite[bytes]] -_FileWrite = Union[_FileWriteC14N, SupportsWrite[str]] +_FileRead = StrOrBytesPath | FileDescriptor | SupportsRead[bytes] | SupportsRead[str] +_FileWriteC14N = StrOrBytesPath | FileDescriptor | SupportsWrite[bytes] +_FileWrite = _FileWriteC14N | SupportsWrite[str] VERSION: str diff --git a/stdlib/xmlrpc/client.pyi b/stdlib/xmlrpc/client.pyi index d44c15cb6..0cf8545fe 100644 --- a/stdlib/xmlrpc/client.pyi +++ b/stdlib/xmlrpc/client.pyi @@ -12,7 +12,7 @@ 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] diff --git a/stdlib/xmlrpc/server.pyi b/stdlib/xmlrpc/server.pyi index 0a0742494..3675402fb 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 17c3503ad..c3cf8321d 100644 --- a/stdlib/zipapp.pyi +++ b/stdlib/zipapp.pyi @@ -1,10 +1,10 @@ import sys from pathlib import Path -from typing import BinaryIO, Callable, Union +from typing import BinaryIO, Callable __all__ = ["ZipAppError", "create_archive", "get_interpreter"] -_Path = Union[str, Path, BinaryIO] +_Path = str | Path | BinaryIO class ZipAppError(ValueError): ... diff --git a/stubs/Pillow/PIL/ImageColor.pyi b/stubs/Pillow/PIL/ImageColor.pyi index 79aaba0ba..d3debdd94 100644 --- a/stubs/Pillow/PIL/ImageColor.pyi +++ b/stubs/Pillow/PIL/ImageColor.pyi @@ -1,7 +1,7 @@ from typing import Union _RGB = Union[tuple[int, int, int], tuple[int, int, int, int]] -_Ink = Union[str, int, _RGB] +_Ink = str | int | _RGB _GreyScale = tuple[int, int] def getrgb(color: _Ink) -> _RGB: ... diff --git a/stubs/PyMySQL/pymysql/converters.pyi b/stubs/PyMySQL/pymysql/converters.pyi index f3d73fc3b..175a5f7cd 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, TypeVar +from typing import Any, 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 e503cba69..c030cd23a 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 d70b44148..74946311e 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 ce42fdfc3..8eacccb26 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, Union +from typing import Any from pygments.lexer import Lexer, LexerMeta -_OpenFile = Union[StrOrBytesPath, int] # copy/pasted from builtins.pyi +_OpenFile = StrOrBytesPath | int # copy/pasted from builtins.pyi def get_all_lexers() -> Iterator[tuple[str, tuple[str, ...], tuple[str, ...], tuple[str, ...]]]: ... def find_lexer_class(name: str) -> LexerMeta | None: ... diff --git a/stubs/aiofiles/aiofiles/os.pyi b/stubs/aiofiles/aiofiles/os.pyi index 761d42556..a625213e4 100644 --- a/stubs/aiofiles/aiofiles/os.pyi +++ b/stubs/aiofiles/aiofiles/os.pyi @@ -2,11 +2,11 @@ import sys from _typeshed import StrOrBytesPath from asyncio.events import AbstractEventLoop from os import stat_result -from typing import Any, Sequence, Union, overload +from typing import Any, Sequence, overload from . import ospath as path -_FdOrAnyPath = Union[int, StrOrBytesPath] +_FdOrAnyPath = int | StrOrBytesPath async def stat( path: _FdOrAnyPath, # noqa: F811 diff --git a/stubs/aiofiles/aiofiles/threadpool/__init__.pyi b/stubs/aiofiles/aiofiles/threadpool/__init__.pyi index 1a5cb9bf8..f1759567e 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 35d31dce7..06b8032bb 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, Pattern, TypeVar, Union, overload +from typing import Any, Callable, Generic, Iterable, Pattern, 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 76fe8f208..5d6f3552a 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, Pattern, Union +from typing import Any, Pattern from .html5lib_shim import BleachHTMLParser, BleachHTMLSerializer, SanitizerFilter @@ -39,8 +39,8 @@ class Cleaner: 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 9cf3008e8..e6474d870 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, Optional, Pattern, Sequence, TextIO, Union +from typing import Any, Callable, Pattern, Sequence, TextIO, Union if sys.platform == "win32": from .winterm import WinTerm @@ -19,7 +19,7 @@ class StreamWrapper: @property def closed(self) -> bool: ... -_WinTermCall = Callable[[Optional[int], bool, bool], None] +_WinTermCall = Callable[[int | None, bool, bool], None] _WinTermCallDict = dict[int, Union[tuple[_WinTermCall], tuple[_WinTermCall, int], tuple[_WinTermCall, int, bool]]] class AnsiToWin32: diff --git a/stubs/croniter/croniter.pyi b/stubs/croniter/croniter.pyi index c55b83672..891e76f79 100644 --- a/stubs/croniter/croniter.pyi +++ b/stubs/croniter/croniter.pyi @@ -1,9 +1,9 @@ import datetime from _typeshed import Self -from typing import Any, Iterator, Text, Union +from typing import Any, Iterator, Text from typing_extensions import Literal -_RetType = Union[type[float], type[datetime.datetime]] +_RetType = type[float | datetime.datetime] class CroniterError(ValueError): ... class CroniterBadCronError(CroniterError): ... diff --git a/stubs/docopt/docopt.pyi b/stubs/docopt/docopt.pyi index 7f7bba6a7..d3774d4c5 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 183443ede..fb11594ed 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, TypeVar, Union, overload +from typing import Any, TypeVar, overload _T = TypeVar("_T") -_Freezable = Union[str, datetime, date, timedelta] +_Freezable = str | datetime | date | timedelta class TickingDateTimeFactory: 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 4ee0b2846..0da180a86 100644 --- a/stubs/paramiko/paramiko/common.pyi +++ b/stubs/paramiko/paramiko/common.pyi @@ -1,5 +1,5 @@ import sys -from typing import Protocol, Union +from typing import Protocol MSG_DISCONNECT: int MSG_IGNORE: int @@ -109,7 +109,7 @@ else: class _SupportsAsBytes(Protocol): def asbytes(self) -> bytes: ... -_LikeBytes = Union[bytes, str, _SupportsAsBytes] +_LikeBytes = bytes | str | _SupportsAsBytes def asbytes(s: _LikeBytes) -> bytes: ... diff --git a/stubs/paramiko/paramiko/transport.pyi b/stubs/paramiko/paramiko/transport.pyi index ea20ff347..599afe0a9 100644 --- a/stubs/paramiko/paramiko/transport.pyi +++ b/stubs/paramiko/paramiko/transport.pyi @@ -2,7 +2,7 @@ from logging import Logger from socket import socket from threading import Condition, Event, Lock, Thread from types import ModuleType -from typing import Any, Callable, Iterable, Protocol, Sequence, Union +from typing import Any, Callable, Iterable, Protocol, Sequence from paramiko.auth_handler import AuthHandler, _InteractiveCallback from paramiko.channel import Channel @@ -15,7 +15,7 @@ from paramiko.ssh_gss import _SSH_GSSAuth from paramiko.util import ClosingContextManager _Addr = tuple[str, int] -_SocketLike = Union[str, _Addr, socket, Channel] +_SocketLike = str | _Addr | socket | Channel class _KexEngine(Protocol): def start_kex(self) -> None: ... diff --git a/stubs/pyOpenSSL/OpenSSL/crypto.pyi b/stubs/pyOpenSSL/OpenSSL/crypto.pyi index 9ffaa7412..851680321 100644 --- a/stubs/pyOpenSSL/OpenSSL/crypto.pyi +++ b/stubs/pyOpenSSL/OpenSSL/crypto.pyi @@ -1,12 +1,12 @@ from _typeshed import StrOrBytesPath from datetime import datetime -from typing import Any, Callable, Iterable, Sequence, Union +from typing import Any, Callable, Iterable, Sequence 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 6bce54a36..a6994f9b5 100644 --- a/stubs/pyaudio/pyaudio.pyi +++ b/stubs/pyaudio/pyaudio.pyi @@ -1,4 +1,4 @@ -from typing import Callable, Mapping, Optional, Sequence, Union +from typing import Callable, Mapping, Optional, Sequence from typing_extensions import Final paFloat32: Final[int] @@ -68,8 +68,8 @@ paMacCoreStreamInfo: PaMacCoreStreamInfo # Auxiliary types _ChannelMap = Sequence[int] -_PaHostApiInfo = Mapping[str, Union[str, int]] -_PaDeviceInfo = Mapping[str, Union[str, int, float]] +_PaHostApiInfo = Mapping[str, str | int] +_PaDeviceInfo = Mapping[str, str | int | float] _StreamCallback = Callable[[Optional[bytes], int, Mapping[str, float], int], tuple[Optional[bytes], int]] def get_format_from_width(width: int, unsigned: bool = ...) -> int: ... diff --git a/stubs/pysftp/pysftp/__init__.pyi b/stubs/pysftp/pysftp/__init__.pyi index 68bbb6c73..ab0d4dddb 100644 --- a/stubs/pysftp/pysftp/__init__.pyi +++ b/stubs/pysftp/pysftp/__init__.pyi @@ -2,7 +2,7 @@ from _typeshed import Self from contextlib import AbstractContextManager from stat import S_IMODE as S_IMODE from types import TracebackType -from typing import IO, Any, Callable, Sequence, Union +from typing import IO, Any, Callable, Sequence from typing_extensions import Literal import paramiko @@ -33,7 +33,7 @@ class CnOpts: def get_hostkey(self, host: str) -> paramiko.PKey: ... _Callback = Callable[[int, int], Any] -_Path = Union[str, bytes] +_Path = str | bytes class Connection: def __init__( diff --git a/stubs/python-dateutil/dateutil/parser/__init__.pyi b/stubs/python-dateutil/dateutil/parser/__init__.pyi index 7782cc007..d62990449 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 ed24582d4..69d983ae7 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 dad7fa15a..296d4418e 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 554cb1abc..5660f6b78 100644 --- a/stubs/redis/redis/client.pyi +++ b/stubs/redis/redis/client.pyi @@ -1,7 +1,7 @@ import threading from _typeshed import Self, SupportsItems from datetime import datetime, timedelta -from typing import Any, Callable, ClassVar, Generic, Iterable, Iterator, Mapping, Pattern, Sequence, TypeVar, Union, overload +from typing import Any, Callable, ClassVar, Generic, Iterable, Iterator, Mapping, Pattern, Sequence, TypeVar, overload from typing_extensions import Literal from .commands import CoreCommands, RedisModuleCommands, SentinelCommands @@ -9,11 +9,11 @@ from .connection import ConnectionPool, _ConnectionPoolOptions from .lock import Lock from .retry import Retry -_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 808227cdb..24e8cfb0a 100644 --- a/stubs/redis/redis/commands/core.pyi +++ b/stubs/redis/redis/commands/core.pyi @@ -1,13 +1,13 @@ import builtins from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence from datetime import datetime, timedelta -from typing import Any, Generic, TypeVar, Union, overload +from typing import Any, Generic, TypeVar, overload from typing_extensions import Literal from ..client import _CommandOptions, _Key, _Value _ScoreCastFuncReturn = TypeVar("_ScoreCastFuncReturn") -_StrType = TypeVar("_StrType", bound=Union[str, bytes]) +_StrType = TypeVar("_StrType", bound=str | bytes) class ACLCommands(Generic[_StrType]): def acl_cat(self, category: str | None = ..., **kwargs: _CommandOptions) -> list[str]: ... diff --git a/stubs/requests/requests/sessions.pyi b/stubs/requests/requests/sessions.pyi index 21693216e..07c2872c5 100644 --- a/stubs/requests/requests/sessions.pyi +++ b/stubs/requests/requests/sessions.pyi @@ -51,15 +51,15 @@ _Data = Union[None, Text, bytes, Mapping[str, Any], Mapping[Text, Any], Iterable _Hook = Callable[[Response], Any] _Hooks = MutableMapping[Text, _Hook | 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] +_ParamsMappingKeyType = Text | bytes | int | float +_ParamsMappingValueType = Text | bytes | int | float | Iterable[Text | bytes | int | float] | None _Params = Union[ SupportsItems[_ParamsMappingKeyType, _ParamsMappingValueType], tuple[_ParamsMappingKeyType, _ParamsMappingValueType], Iterable[tuple[_ParamsMappingKeyType, _ParamsMappingValueType]], - Union[Text, bytes], + Text | bytes, ] _TextMapping = MutableMapping[Text, Text] diff --git a/stubs/setuptools/pkg_resources/__init__.pyi b/stubs/setuptools/pkg_resources/__init__.pyi index d4f65651a..a9c7f01a4 100644 --- a/stubs/setuptools/pkg_resources/__init__.pyi +++ b/stubs/setuptools/pkg_resources/__init__.pyi @@ -3,17 +3,17 @@ import types import zipimport from _typeshed import Self from abc import ABCMeta -from typing import IO, Any, Callable, Generator, Iterable, Optional, Sequence, TypeVar, Union, overload +from typing import IO, Any, Callable, Generator, Iterable, Sequence, 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 798a77062..9e3401e78 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/tabulate/tabulate.pyi b/stubs/tabulate/tabulate.pyi index 1d0daa981..e5208e0be 100644 --- a/stubs/tabulate/tabulate.pyi +++ b/stubs/tabulate/tabulate.pyi @@ -1,4 +1,4 @@ -from typing import Any, Callable, Container, Iterable, Mapping, NamedTuple, Sequence, Union +from typing import Any, Callable, Container, Iterable, Mapping, NamedTuple, Sequence LATEX_ESCAPE_RULES: dict[str, str] MIN_PADDING: int @@ -18,8 +18,8 @@ class DataRow(NamedTuple): sep: str end: str -_TableFormatLine = Union[None, Line, Callable[[list[int], list[str]], str]] -_TableFormatRow = Union[None, DataRow, Callable[[list[Any], list[int], list[str]], str]] +_TableFormatLine = None | Line | Callable[[list[int], list[str]], str] +_TableFormatRow = None | DataRow | Callable[[list[Any], list[int], list[str]], str] class TableFormat(NamedTuple): lineabove: _TableFormatLine diff --git a/tests/check_new_syntax.py b/tests/check_new_syntax.py index f6945a003..4a63e8e84 100755 --- a/tests/check_new_syntax.py +++ b/tests/check_new_syntax.py @@ -10,11 +10,12 @@ STUBS_SUPPORTING_PYTHON_2 = frozenset( ) -def check_new_syntax(tree: ast.AST, path: Path) -> list[str]: +def check_new_syntax(tree: ast.AST, path: Path, stub: str) -> list[str]: errors = [] + sourcelines = stub.splitlines() python_2_support_required = any(directory in path.parents for directory in STUBS_SUPPORTING_PYTHON_2) - class UnionFinder(ast.NodeVisitor): + class AnnotationUnionFinder(ast.NodeVisitor): def visit_Subscript(self, node: ast.Subscript) -> None: if isinstance(node.value, ast.Name): if node.value.id == "Union" and isinstance(node.slice, ast.Tuple): @@ -26,23 +27,48 @@ def check_new_syntax(tree: ast.AST, path: Path) -> list[str]: self.generic_visit(node) + class NonAnnotationUnionFinder(ast.NodeVisitor): + def visit_Subscript(self, node: ast.Subscript) -> None: + if isinstance(node.value, ast.Name): + nodelines = sourcelines[(node.lineno - 1) : node.end_lineno] + for line in nodelines: + # A hack to workaround various PEP 604 bugs in mypy + if any(x in line for x in {"tuple[", "Callable[", "type["}): + return None + if node.value.id == "Union" and isinstance(node.slice, ast.Tuple): + new_syntax = " | ".join(ast.unparse(x) for x in node.slice.elts) + errors.append(f"{path}:{node.lineno}: Use PEP 604 syntax for Union, e.g. `{new_syntax}`") + elif node.value.id == "Optional": + new_syntax = f"{ast.unparse(node.slice)} | None" + errors.append(f"{path}:{node.lineno}: Use PEP 604 syntax for Optional, e.g. `{new_syntax}`") + + self.generic_visit(node) + class OldSyntaxFinder(ast.NodeVisitor): def visit_AnnAssign(self, node: ast.AnnAssign) -> None: - UnionFinder().visit(node.annotation) + AnnotationUnionFinder().visit(node.annotation) def visit_arg(self, node: ast.arg) -> None: if node.annotation is not None: - UnionFinder().visit(node.annotation) + AnnotationUnionFinder().visit(node.annotation) + + def _visit_function(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None: + if node.returns is not None: + AnnotationUnionFinder().visit(node.returns) + self.generic_visit(node) def visit_FunctionDef(self, node: ast.FunctionDef) -> None: - if node.returns is not None: - UnionFinder().visit(node.returns) - self.generic_visit(node) + self._visit_function(node) def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None: - if node.returns is not None: - UnionFinder().visit(node.returns) - self.generic_visit(node) + self._visit_function(node) + + def visit_Assign(self, node: ast.Assign) -> None: + NonAnnotationUnionFinder().visit(node.value) + + def visit_ClassDef(self, node: ast.ClassDef) -> None: + for base in node.bases: + NonAnnotationUnionFinder().visit(base) class ObjectClassdefFinder(ast.NodeVisitor): def visit_ClassDef(self, node: ast.ClassDef) -> None: @@ -85,8 +111,9 @@ def main() -> None: continue with open(path) as f: - tree = ast.parse(f.read()) - errors.extend(check_new_syntax(tree, path)) + stub = f.read() + tree = ast.parse(stub) + errors.extend(check_new_syntax(tree, path, stub)) if errors: print("\n".join(errors))