From c7926829062e47e2a73d5daa1fd34649c69a027a Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Tue, 15 Mar 2022 18:20:47 +0000 Subject: [PATCH 01/13] Refactor typeshed using script --- stdlib/@python2/SocketServer.pyi | 2 +- stdlib/@python2/_codecs.pyi | 12 +-- stdlib/@python2/_csv.pyi | 4 +- 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/inspect.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 | 6 +- 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/_csv.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/inspect.pyi | 4 +- 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 +- .../google/protobuf/descriptor_pool.pyi | 6 +- .../google/protobuf/internal/containers.pyi | 18 ++--- .../protobuf/internal/extension_dict.pyi | 4 +- .../protobuf/internal/well_known_types.pyi | 6 +- .../protobuf/google/protobuf/json_format.pyi | 17 ++-- .../google/protobuf/message_factory.pyi | 4 +- stubs/protobuf/google/protobuf/service.pyi | 12 +-- .../google/protobuf/symbol_database.pyi | 4 +- .../protobuf/google/protobuf/text_format.pyi | 80 +++++++++---------- 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 +- 186 files changed, 516 insertions(+), 564 deletions(-) diff --git a/stdlib/@python2/SocketServer.pyi b/stdlib/@python2/SocketServer.pyi index 7c72675e677c..545ee8464f16 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 fa6922207c25..1028cfec1aef 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/_csv.pyi b/stdlib/@python2/_csv.pyi index e01ccc19cb19..1033924f7e35 100644 --- a/stdlib/@python2/_csv.pyi +++ b/stdlib/@python2/_csv.pyi @@ -1,4 +1,4 @@ -from typing import Any, Iterable, Iterator, Protocol, Sequence, Text, Union +from typing import Any, Iterable, Iterator, Protocol, Sequence, Text QUOTE_ALL: int QUOTE_MINIMAL: int @@ -18,7 +18,7 @@ class Dialect: strict: int def __init__(self) -> None: ... -_DialectLike = Union[str, Dialect, type[Dialect]] +_DialectLike = str | Dialect | type[Dialect] class _reader(Iterator[list[str]]): dialect: Dialect diff --git a/stdlib/@python2/_curses.pyi b/stdlib/@python2/_curses.pyi index 4b2941e74753..81de0ea96e3f 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 c03c52a7907c..e7b0a9e4b363 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 3671bbd2177d..65c59ccf7715 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 0d1dc3866b56..a3399a8ca6b4 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 6dc2b5cc021d..4380949c9c1c 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 e432d883e4d5..395024fcc2fd 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 b8049e857304..766ccde956f9 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 e82a8c621e40..3eacc7b1dc3b 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 1ef8c3a7c8c3..fcd1d7bfa4d0 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 1daa1aac87a7..a9f07613bb9c 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 00856aafddbe..4a32006ea98b 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 4e295b8ed903..10a5a3ee5633 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 bec8994dbe29..e182aa428e06 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 ef54d7f43854..1053b2269812 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 2780d473b781..0f97a4401556 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 8e68238fc6e2..4f39ba5dad5e 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 9fab35ebd022..ef627f10f656 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 6a259cf4d0e4..bdd32a8e7ef7 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 9c867074df06..e9c1d01a5c9b 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 e040f23ce2b0..acb4b3b7ae7f 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 1eecfac66a5f..019711f62ed1 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 12d9f31881c1..92ec92ebd0cd 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 f798d8811c87..5ea7348c2eaf 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 c4e59f54c66d..30b624b8fd15 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 f6be1a8dfa83..79cc30a68a0a 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 ead2dd5bf38e..942a52bbac9a 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 7835e9aa56b6..27de79248c03 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 b8c2bbd40371..870d00d804ce 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 fecb3b70af42..66b9d5fc34a5 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 8f881aaaf419..86e6c21159a6 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 cc39d8c65c8f..a244f4112e87 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 dcfc3506fb9a..36db49902983 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/inspect.pyi b/stdlib/@python2/inspect.pyi index aa0450ce6785..a6f2af2cd600 100644 --- a/stdlib/@python2/inspect.pyi +++ b/stdlib/@python2/inspect.pyi @@ -1,5 +1,5 @@ from types import CodeType, FrameType, FunctionType, MethodType, ModuleType, TracebackType -from typing import Any, AnyStr, Callable, NamedTuple, Optional, Sequence, Union +from typing import Any, AnyStr, Callable, NamedTuple, Optional, Sequence # Types and members class EndOfBlock(Exception): ... @@ -50,7 +50,7 @@ def isgetsetdescriptor(object: object) -> bool: ... def ismemberdescriptor(object: object) -> bool: ... # Retrieving source code -_SourceObjectType = Union[ModuleType, type[Any], MethodType, FunctionType, TracebackType, FrameType, CodeType, Callable[..., Any]] +_SourceObjectType = ModuleType | type[Any] | MethodType | FunctionType | TracebackType | FrameType | CodeType | Callable[..., Any] def findsource(object: _SourceObjectType) -> tuple[list[str], int]: ... def getabsfile(object: _SourceObjectType) -> str: ... diff --git a/stdlib/@python2/lib2to3/pytree.pyi b/stdlib/@python2/lib2to3/pytree.pyi index 130f03dabdb7..29699f651331 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 9ca64dc966ae..4e0a9dedfa21 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 9c4aa66cdbb7..9d3f4d866aba 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 56218d1370fe..6e0c918280ad 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 602617665ea8..7cacb07bdb77 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 a99bc0a6fb3b..d033cb9a6da6 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 02a1cb506d1d..488757b4c81e 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 e2cf6e437826..6b956764efa9 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 3c26f451116e..ccd05029fe0e 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 9b82d9bae636..56db3a626db1 100644 --- a/stdlib/@python2/readline.pyi +++ b/stdlib/@python2/readline.pyi @@ -1,9 +1,9 @@ import sys -from typing import Callable, Optional, Sequence, Text +from typing import Callable, Sequence, Text if sys.platform != "win32": - _CompleterT = Optional[Callable[[str, int], Optional[str]]] - _CompDispT = Optional[Callable[[str, Sequence[str], int], None]] + _CompleterT = Callable[[str, int], str | None] | 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 e075e241b794..6cf58fbf20cf 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 7cafbaf8a7c7..637bc879fa74 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 f92cf1c9f1a0..173ce9c284af 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 7f86f03e638a..f39f38c41c8f 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 0981ce28a786..29f4fe125ca2 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 c4307bb9bb53..81f14aca6c19 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 4eccf5875d55..dafba0b1d62b 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 = 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 7129fbc4cfb6..0296c737089a 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 d2149c81aaaf..e6ab3dfcbb73 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 6d5caee7b199..85b4d12b4d8a 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 6ef2f6818827..c6a90df31b59 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 611552dc92ab..b62b3a121b80 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 3a7f6e0e0841..b95c89fa312d 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 56e85108c75e..fc7e90bc0ff9 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 cb52479864a2..7b104bec7812 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 9db413d996bb..887e7055207d 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 990384ebdcd1..1ea1bce28db1 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 625928a74135..16c32753c7c5 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 e8717aecbe36..a9585bac60a1 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 ceae301145d8..d13f74664f43 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 a6cbae35d04f..f17ae5211252 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 0defb96bffb8..8d2766e6578a 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 0f376d2d93b8..777692598ab7 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 470722a293a3..1781a2418ca0 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/_csv.pyi b/stdlib/_csv.pyi index 161a89778de8..d0bc6cc22819 100644 --- a/stdlib/_csv.pyi +++ b/stdlib/_csv.pyi @@ -1,4 +1,4 @@ -from typing import Any, Iterable, Iterator, Protocol, Union +from typing import Any, Iterable, Iterator, Protocol from typing_extensions import Literal __version__: str @@ -21,7 +21,7 @@ class Dialect: strict: int def __init__(self) -> None: ... -_DialectLike = Union[str, Dialect, type[Dialect]] +_DialectLike = str | Dialect | type[Dialect] class _reader(Iterator[list[str]]): dialect: Dialect diff --git a/stdlib/_curses.pyi b/stdlib/_curses.pyi index 7022097628fc..e193759bdc6e 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 f63bec448f90..630ca3392e3f 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 103af47c7524..73b1f90541e6 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 8fc188980312..db3d8d991029 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 a13052707178..69b4d35d9fe9 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 1d52942bf6c5..9eea2e16641e 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 94c7c01dd1bc..21c56bde1eac 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 37079dc091e5..fbd09ec5c8d5 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 bf4412264ced..5e483a578c3e 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 2b0993ee03d7..1fd7c31c7fcb 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 f2725a8992ae..3a617d6fb628 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 140fc106bf42..885688065ddc 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 5bbdadf8c269..7973704d7635 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 e531ccd508bf..db002503c75f 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 176d07a9daa8..c668ca40e976 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 04c2b632d411..ee51861fdaa0 100644 --- a/stdlib/cmath.pyi +++ b/stdlib/cmath.pyi @@ -1,5 +1,5 @@ import sys -from typing import SupportsComplex, SupportsFloat, Union +from typing import SupportsComplex, SupportsFloat if sys.version_info >= (3, 8): from typing import SupportsIndex @@ -13,9 +13,9 @@ nanj: complex tau: float if sys.version_info >= (3, 8): - _C = Union[SupportsFloat, SupportsComplex, SupportsIndex, complex] + _C = SupportsFloat | SupportsComplex | SupportsIndex | complex else: - _C = Union[SupportsFloat, SupportsComplex, complex] + _C = SupportsFloat | SupportsComplex | complex def acos(__z: _C) -> complex: ... def acosh(__z: _C) -> complex: ... diff --git a/stdlib/configparser.pyi b/stdlib/configparser.pyi index 6b043263775c..55df2ce58de7 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 c2731dea7807..294fb2c0fc07 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 d4caa7a88d76..7513948e6a4c 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 630a0d16c1c7..d43a2415caff 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 c877ef8593d8..5af95ace72ad 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 b0e657d6ae4b..9a603228a691 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 336720c79f37..8405bec2bcf2 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 dfd0670e474e..819ed1641448 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 dcb82cb7aefc..910458c08e00 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 18d5f1b9ac22..749b6454a8f8 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 d6857328a4ee..42c25c798cb6 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 077a2f423e49..a7075e030429 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 ecbfb07e1dfd..00989fb1fc02 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 fbb0397ac40b..6d355147f51e 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 857d69db799c..64452dc70807 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 5e01e603781d..2cc05961a303 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 16f514a74eb5..877f8ff1a65c 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 cee3259332ff..e6e3035e5dac 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/inspect.pyi b/stdlib/inspect.pyi index f87cd0e55acb..3c1f6de08d43 100644 --- a/stdlib/inspect.pyi +++ b/stdlib/inspect.pyi @@ -29,7 +29,7 @@ if sys.version_info >= (3, 7): MethodWrapperType, ) -from typing import Any, ClassVar, Coroutine, NamedTuple, Protocol, TypeVar, Union +from typing import Any, ClassVar, Coroutine, NamedTuple, Protocol, TypeVar from typing_extensions import Literal, ParamSpec, TypeGuard if sys.version_info >= (3, 11): @@ -242,7 +242,7 @@ def isdatadescriptor(object: object) -> TypeGuard[_SupportsSet[Any, Any] | _Supp # # Retrieving source code # -_SourceObjectType = Union[ModuleType, type[Any], MethodType, FunctionType, TracebackType, FrameType, CodeType, Callable[..., Any]] +_SourceObjectType = ModuleType | type[Any] | MethodType | FunctionType | TracebackType | FrameType | CodeType | Callable[..., Any] def findsource(object: _SourceObjectType) -> tuple[list[str], int]: ... def getabsfile(object: _SourceObjectType, _filename: str | None = ...) -> str: ... diff --git a/stdlib/itertools.pyi b/stdlib/itertools.pyi index 35765712202a..bec03b1876ac 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 b0e61c3a38ac..ccd347e39296 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 c860938c31ea..ac4631e8c119 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 c469c218abcb..45bf24b3ef6d 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 3fafd8891840..143891d3240b 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 7bf2ebd1bdfe..232ab99c314d 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 2218f68174d1..e4ab311990be 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 3f489ca43dba..3a8a382b8a27 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 db8e6216b6ad..315918a04b98 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 cb576abcc815..0cfc815b2d82 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 77cab1e154e8..1b129b7ec609 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 615dff880689..c87ed7e4d4bc 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 d48d3ead75c5..3a9fd9c082ac 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 c4fe28477fb5..a7b8bebe4066 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 b9c41e1caa16..57dab8eb820f 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 030f16cd99b7..5fa5f6669f1b 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 50f1e0ff0cf1..bac837bebfa6 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 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 = 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 56d551180f5f..8d50b4419c8c 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 83932e5790c4..4fe30e97ea1c 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 = 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 879ea3c74ec7..446a778794f1 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 a0e446d19c8e..ced2e708f8ff 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 f96dbaaf7be8..b5a16f5e282b 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 89b636cd08af..4fca35a2c82d 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 fe8e3af2e1c1..19a4dbee2ee7 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 6ef2f6818827..c6a90df31b59 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 d6a64d0aefb5..c3fa57fafa7c 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 c1a8727b1ea0..844aba90f6b5 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 3135c21a6022..bfaea728ff42 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 2393b0e5be49..e2c9afba63e8 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 = 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 41a5b64c5c35..c48b5cd7aa0d 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 e8f64a7d0702..7b17e8de6153 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 015669a68084..63f594a8fbb1 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 164ea461399b..2ff965465be6 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 f1e168a674a7..ca483b06ac9f 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 b3cdc73e2fb1..f8ba0988cbd9 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 05aa4afef2a7..d75df67a1f76 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 13fa12348cb3..8c2edb5b19e2 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 e55be6b5e8ba..5dc7e4363d6f 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 7ae2dcf3eadd..b2bec64fd1dc 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 0615edb8073e..ec47ec134e08 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 aef8285eec5b..7b50b4279021 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 d44c15cb64ed..0cf8545fe2bb 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 0a07424949df..3675402fba80 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 17c3503ad6eb..c3cf8321dbc4 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 79aaba0ba7c1..d3debdd949de 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 f3d73fc3ba4d..175a5f7cd874 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 e503cba6949a..c030cd23a2bb 100644 --- a/stubs/PyYAML/yaml/constructor.pyi +++ b/stubs/PyYAML/yaml/constructor.pyi @@ -1,9 +1,9 @@ -from typing import Any, Pattern, Union +from typing import Any, Pattern from yaml.error import MarkedYAMLError from yaml.nodes import ScalarNode -_Scalar = Union[str, int, float, bool, None] +_Scalar = str | int | float | bool | None class ConstructorError(MarkedYAMLError): ... diff --git a/stubs/PyYAML/yaml/cyaml.pyi b/stubs/PyYAML/yaml/cyaml.pyi index d70b44148bec..74946311ec94 100644 --- a/stubs/PyYAML/yaml/cyaml.pyi +++ b/stubs/PyYAML/yaml/cyaml.pyi @@ -1,6 +1,6 @@ from _typeshed import SupportsRead from collections.abc import Mapping, Sequence -from typing import IO, Any, Union +from typing import IO, Any from ._yaml import CEmitter, CParser from .constructor import BaseConstructor, FullConstructor, SafeConstructor, UnsafeConstructor @@ -9,7 +9,7 @@ from .resolver import BaseResolver, Resolver __all__ = ["CBaseLoader", "CSafeLoader", "CFullLoader", "CUnsafeLoader", "CLoader", "CBaseDumper", "CSafeDumper", "CDumper"] -_Readable = SupportsRead[Union[str, bytes]] +_Readable = SupportsRead[str | bytes] class CBaseLoader(CParser, BaseConstructor, BaseResolver): def __init__(self, stream: str | bytes | _Readable) -> None: ... diff --git a/stubs/Pygments/pygments/lexers/__init__.pyi b/stubs/Pygments/pygments/lexers/__init__.pyi index ce42fdfc34f9..8eacccb26138 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 761d425564fb..a625213e463a 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 1a5cb9bf8dcd..f1759567eb64 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 35d31dce75d9..06b8032bb5b9 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 76fe8f208dc9..5d6f3552a343 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 9cf3008e86b2..e6474d870595 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 c55b83672fd7..56ef5eacd916 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] | type[datetime.datetime] class CroniterError(ValueError): ... class CroniterBadCronError(CroniterError): ... diff --git a/stubs/docopt/docopt.pyi b/stubs/docopt/docopt.pyi index 7f7bba6a7e69..d3774d4c558c 100644 --- a/stubs/docopt/docopt.pyi +++ b/stubs/docopt/docopt.pyi @@ -1,8 +1,8 @@ -from typing import Any, Iterable, Union +from typing import Any, Iterable __version__: str -_Argv = Union[Iterable[str], str] +_Argv = Iterable[str] | str def docopt( doc: str, argv: _Argv | None = ..., help: bool = ..., version: Any | None = ..., options_first: bool = ... diff --git a/stubs/freezegun/freezegun/api.pyi b/stubs/freezegun/freezegun/api.pyi index 183443ede1d6..fb11594ed872 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 4ee0b2846928..0da180a867cf 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 ea20ff3478f9..599afe0a98cb 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/protobuf/google/protobuf/descriptor_pool.pyi b/stubs/protobuf/google/protobuf/descriptor_pool.pyi index aabe9d9dca0a..f1ecee77622a 100644 --- a/stubs/protobuf/google/protobuf/descriptor_pool.pyi +++ b/stubs/protobuf/google/protobuf/descriptor_pool.pyi @@ -1,8 +1,8 @@ -from typing import Any, Optional +from typing import Any class DescriptorPool: - def __new__(cls, descriptor_db: Optional[Any] = ...): ... - def __init__(self, descriptor_db: Optional[Any] = ...) -> None: ... + def __new__(cls, descriptor_db: Any | None = ...): ... + def __init__(self, descriptor_db: Any | None = ...) -> None: ... def Add(self, file_desc_proto): ... def AddSerializedFile(self, serialized_file_desc_proto): ... def AddDescriptor(self, desc): ... diff --git a/stubs/protobuf/google/protobuf/internal/containers.pyi b/stubs/protobuf/google/protobuf/internal/containers.pyi index 1a86d45a1393..0d7a97a4a65b 100644 --- a/stubs/protobuf/google/protobuf/internal/containers.pyi +++ b/stubs/protobuf/google/protobuf/internal/containers.pyi @@ -1,5 +1,5 @@ from collections.abc import MutableMapping -from typing import Any, Callable, Iterable, Iterator, Optional, Sequence, Text, TypeVar, Union, overload +from typing import Any, Callable, Iterable, Iterator, Sequence, Text, TypeVar, overload from typing_extensions import SupportsIndex from google.protobuf.descriptor import Descriptor @@ -9,8 +9,8 @@ from google.protobuf.internal.type_checkers import _ValueChecker from google.protobuf.message import Message _T = TypeVar("_T") -_K = TypeVar("_K", bound=Union[bool, int, Text]) -_ScalarV = TypeVar("_ScalarV", bound=Union[bool, int, float, Text, bytes]) +_K = TypeVar("_K", bound=bool | int | Text) +_ScalarV = TypeVar("_ScalarV", bound=bool | int | float | Text | bytes) _MessageV = TypeVar("_MessageV", bound=Message) _M = TypeVar("_M") @@ -19,7 +19,7 @@ class BaseContainer(Sequence[_T]): def __len__(self) -> int: ... def __ne__(self, other: object) -> bool: ... def __hash__(self) -> int: ... - def sort(self, *, key: Optional[Callable[[_T], Any]] = ..., reverse: bool = ...) -> None: ... + def sort(self, *, key: Callable[[_T], Any] | None = ..., reverse: bool = ...) -> None: ... @overload def __getitem__(self, key: SupportsIndex) -> _T: ... @overload @@ -29,7 +29,7 @@ class RepeatedScalarFieldContainer(BaseContainer[_ScalarV]): def __init__(self, message_listener: MessageListener, type_checker: _ValueChecker[_ScalarV]) -> None: ... def append(self, value: _ScalarV) -> None: ... def insert(self, key: int, value: _ScalarV) -> None: ... - def extend(self, elem_seq: Optional[Iterable[_ScalarV]]) -> None: ... + def extend(self, elem_seq: Iterable[_ScalarV] | None) -> None: ... def MergeFrom(self: _M, other: _M) -> None: ... def remove(self, elem: _ScalarV) -> None: ... def pop(self, key: int = ...) -> _ScalarV: ... @@ -39,7 +39,7 @@ class RepeatedScalarFieldContainer(BaseContainer[_ScalarV]): def __setitem__(self, key: slice, value: Iterable[_ScalarV]) -> None: ... def __getslice__(self, start: int, stop: int) -> list[_ScalarV]: ... def __setslice__(self, start: int, stop: int, values: Iterable[_ScalarV]) -> None: ... - def __delitem__(self, key: Union[int, slice]) -> None: ... + def __delitem__(self, key: int | slice) -> None: ... def __delslice__(self, start: int, stop: int) -> None: ... def __eq__(self, other: object) -> bool: ... @@ -53,7 +53,7 @@ class RepeatedCompositeFieldContainer(BaseContainer[_MessageV]): def remove(self, elem: _MessageV) -> None: ... def pop(self, key: int = ...) -> _MessageV: ... def __getslice__(self, start: int, stop: int) -> list[_MessageV]: ... - def __delitem__(self, key: Union[int, slice]) -> None: ... + def __delitem__(self, key: int | slice) -> None: ... def __delslice__(self, start: int, stop: int) -> None: ... def __eq__(self, other: object) -> bool: ... @@ -74,7 +74,7 @@ class ScalarMap(MutableMapping[_K, _ScalarV]): @overload def get(self, key: _K, default: None = ...) -> _ScalarV: ... @overload - def get(self, key: _K, default: Union[_ScalarV, _T]) -> Union[_ScalarV, _T]: ... + def get(self, key: _K, default: _ScalarV | _T) -> _ScalarV | _T: ... def MergeFrom(self: _M, other: _M): ... def InvalidateIterators(self) -> None: ... def GetEntryClass(self) -> GeneratedProtocolMessageType: ... @@ -96,7 +96,7 @@ class MessageMap(MutableMapping[_K, _MessageV]): @overload def get(self, key: _K, default: None = ...) -> _MessageV: ... @overload - def get(self, key: _K, default: Union[_MessageV, _T]) -> Union[_MessageV, _T]: ... + def get(self, key: _K, default: _MessageV | _T) -> _MessageV | _T: ... def get_or_create(self, key: _K) -> _MessageV: ... def MergeFrom(self: _M, other: _M): ... def InvalidateIterators(self) -> None: ... diff --git a/stubs/protobuf/google/protobuf/internal/extension_dict.pyi b/stubs/protobuf/google/protobuf/internal/extension_dict.pyi index 486e367eaa15..a8aead6fd3ad 100644 --- a/stubs/protobuf/google/protobuf/internal/extension_dict.pyi +++ b/stubs/protobuf/google/protobuf/internal/extension_dict.pyi @@ -1,4 +1,4 @@ -from typing import Any, Generic, Iterator, Text, TypeVar, Union +from typing import Any, Generic, Iterator, Text, TypeVar from google.protobuf.descriptor import FieldDescriptor from google.protobuf.internal.containers import RepeatedCompositeFieldContainer, RepeatedScalarFieldContainer @@ -7,7 +7,7 @@ from google.protobuf.message import Message _ContainerMessageT = TypeVar("_ContainerMessageT", bound=Message) _ExtenderMessageT = TypeVar( "_ExtenderMessageT", - bound=Union[Message, RepeatedScalarFieldContainer[Any], RepeatedCompositeFieldContainer[Any], bool, int, float, Text, bytes], + bound=Message | RepeatedScalarFieldContainer[Any] | RepeatedCompositeFieldContainer[Any] | bool | int | float | Text | bytes, ) class _ExtensionFieldDescriptor(FieldDescriptor, Generic[_ContainerMessageT, _ExtenderMessageT]): ... diff --git a/stubs/protobuf/google/protobuf/internal/well_known_types.pyi b/stubs/protobuf/google/protobuf/internal/well_known_types.pyi index 146907ce31bc..1f00ecf295d4 100644 --- a/stubs/protobuf/google/protobuf/internal/well_known_types.pyi +++ b/stubs/protobuf/google/protobuf/internal/well_known_types.pyi @@ -1,10 +1,10 @@ from datetime import datetime, timedelta -from typing import Any as tAny, Optional +from typing import Any as tAny class Any: type_url: tAny = ... value: tAny = ... - def Pack(self, msg: tAny, type_url_prefix: str = ..., deterministic: Optional[tAny] = ...) -> None: ... + def Pack(self, msg: tAny, type_url_prefix: str = ..., deterministic: tAny | None = ...) -> None: ... def Unpack(self, msg: tAny): ... def TypeName(self): ... def Is(self, descriptor: tAny): ... @@ -55,7 +55,7 @@ class FieldMask: ) -> None: ... class _FieldMaskTree: - def __init__(self, field_mask: Optional[tAny] = ...) -> None: ... + def __init__(self, field_mask: tAny | None = ...) -> None: ... def MergeFromFieldMask(self, field_mask: tAny) -> None: ... def AddPath(self, path: tAny): ... def ToFieldMask(self, field_mask: tAny) -> None: ... diff --git a/stubs/protobuf/google/protobuf/json_format.pyi b/stubs/protobuf/google/protobuf/json_format.pyi index 6ecc10c520ca..f43d66e34012 100644 --- a/stubs/protobuf/google/protobuf/json_format.pyi +++ b/stubs/protobuf/google/protobuf/json_format.pyi @@ -1,4 +1,4 @@ -from typing import Any, Optional, Text, TypeVar, Union +from typing import Any, Text, TypeVar from google.protobuf.descriptor_pool import DescriptorPool from google.protobuf.message import Message @@ -16,23 +16,20 @@ def MessageToJson( indent: int = ..., sort_keys: bool = ..., use_integers_for_enums: bool = ..., - descriptor_pool: Optional[DescriptorPool] = ..., - float_precision: Optional[int] = ..., + descriptor_pool: DescriptorPool | None = ..., + float_precision: int | None = ..., ) -> str: ... def MessageToDict( message: Message, including_default_value_fields: bool = ..., preserving_proto_field_name: bool = ..., use_integers_for_enums: bool = ..., - descriptor_pool: Optional[DescriptorPool] = ..., - float_precision: Optional[int] = ..., + descriptor_pool: DescriptorPool | None = ..., + float_precision: int | None = ..., ) -> dict[Text, Any]: ... def Parse( - text: Union[bytes, Text], - message: _MessageT, - ignore_unknown_fields: bool = ..., - descriptor_pool: Optional[DescriptorPool] = ..., + text: bytes | Text, message: _MessageT, ignore_unknown_fields: bool = ..., descriptor_pool: DescriptorPool | None = ... ) -> _MessageT: ... def ParseDict( - js_dict: Any, message: _MessageT, ignore_unknown_fields: bool = ..., descriptor_pool: Optional[DescriptorPool] = ... + js_dict: Any, message: _MessageT, ignore_unknown_fields: bool = ..., descriptor_pool: DescriptorPool | None = ... ) -> _MessageT: ... diff --git a/stubs/protobuf/google/protobuf/message_factory.pyi b/stubs/protobuf/google/protobuf/message_factory.pyi index ae299d8aeb69..c8fb7983da25 100644 --- a/stubs/protobuf/google/protobuf/message_factory.pyi +++ b/stubs/protobuf/google/protobuf/message_factory.pyi @@ -1,4 +1,4 @@ -from typing import Any, Iterable, Optional +from typing import Any, Iterable from google.protobuf.descriptor import Descriptor from google.protobuf.descriptor_pb2 import FileDescriptorProto @@ -7,7 +7,7 @@ from google.protobuf.message import Message class MessageFactory: pool: Any - def __init__(self, pool: Optional[DescriptorPool] = ...) -> None: ... + def __init__(self, pool: DescriptorPool | None = ...) -> None: ... def GetPrototype(self, descriptor: Descriptor) -> type[Message]: ... def GetMessages(self, files: Iterable[str]) -> dict[str, type[Message]]: ... diff --git a/stubs/protobuf/google/protobuf/service.pyi b/stubs/protobuf/google/protobuf/service.pyi index 7f7a762ac9fa..757c2449e63d 100644 --- a/stubs/protobuf/google/protobuf/service.pyi +++ b/stubs/protobuf/google/protobuf/service.pyi @@ -1,5 +1,5 @@ from concurrent.futures import Future -from typing import Callable, Optional, Text +from typing import Callable, Text from google.protobuf.descriptor import MethodDescriptor, ServiceDescriptor from google.protobuf.message import Message @@ -14,15 +14,15 @@ class Service: method_descriptor: MethodDescriptor, rpc_controller: RpcController, request: Message, - done: Optional[Callable[[Message], None]], - ) -> Optional[Future[Message]]: ... + done: Callable[[Message], None] | None, + ) -> Future[Message] | None: ... def GetRequestClass(self, method_descriptor: MethodDescriptor) -> type[Message]: ... def GetResponseClass(self, method_descriptor: MethodDescriptor) -> type[Message]: ... class RpcController: def Reset(self) -> None: ... def Failed(self) -> bool: ... - def ErrorText(self) -> Optional[Text]: ... + def ErrorText(self) -> Text | None: ... def StartCancel(self) -> None: ... def SetFailed(self, reason: Text) -> None: ... def IsCanceled(self) -> bool: ... @@ -35,5 +35,5 @@ class RpcChannel: rpc_controller: RpcController, request: Message, response_class: type[Message], - done: Optional[Callable[[Message], None]], - ) -> Optional[Future[Message]]: ... + done: Callable[[Message], None] | None, + ) -> Future[Message] | None: ... diff --git a/stubs/protobuf/google/protobuf/symbol_database.pyi b/stubs/protobuf/google/protobuf/symbol_database.pyi index 0644a9be82f3..73edfe2398fe 100644 --- a/stubs/protobuf/google/protobuf/symbol_database.pyi +++ b/stubs/protobuf/google/protobuf/symbol_database.pyi @@ -1,11 +1,11 @@ -from typing import Iterable, Union +from typing import Iterable from google.protobuf.descriptor import Descriptor, EnumDescriptor, FileDescriptor, ServiceDescriptor from google.protobuf.message import Message from google.protobuf.message_factory import MessageFactory class SymbolDatabase(MessageFactory): - def RegisterMessage(self, message: Union[type[Message], Message]) -> Union[type[Message], Message]: ... + def RegisterMessage(self, message: type[Message] | Message) -> type[Message] | Message: ... def RegisterMessageDescriptor(self, message_descriptor: Descriptor) -> None: ... def RegisterEnumDescriptor(self, enum_descriptor: EnumDescriptor) -> EnumDescriptor: ... def RegisterServiceDescriptor(self, service_descriptor: ServiceDescriptor) -> None: ... diff --git a/stubs/protobuf/google/protobuf/text_format.pyi b/stubs/protobuf/google/protobuf/text_format.pyi index f70959d02b47..1f9f21aece12 100644 --- a/stubs/protobuf/google/protobuf/text_format.pyi +++ b/stubs/protobuf/google/protobuf/text_format.pyi @@ -1,5 +1,5 @@ from _typeshed import SupportsWrite -from typing import Any, Callable, Iterable, Optional, Text, TypeVar, Union +from typing import Any, Callable, Iterable, Text, TypeVar from .descriptor import FieldDescriptor from .descriptor_pool import DescriptorPool @@ -10,9 +10,9 @@ _M = TypeVar("_M", bound=Message) # message type (of self) class Error(Exception): ... class ParseError(Error): - def __init__(self, message: Optional[str] = ..., line: Optional[int] = ..., column: Optional[int] = ...) -> None: ... - def GetLine(self) -> Optional[int]: ... - def GetColumn(self) -> Optional[int]: ... + def __init__(self, message: str | None = ..., line: int | None = ..., column: int | None = ...) -> None: ... + def GetLine(self) -> int | None: ... + def GetColumn(self) -> int | None: ... class TextWriter: def __init__(self, as_utf8: bool) -> None: ... @@ -20,7 +20,7 @@ class TextWriter: def getvalue(self) -> str: ... def close(self) -> None: ... -_MessageFormatter = Callable[[Message, int, bool], Optional[Text]] +_MessageFormatter = Callable[[Message, int, bool], Text | None] def MessageToString( message: Message, @@ -29,12 +29,12 @@ def MessageToString( use_short_repeated_primitives: bool = ..., pointy_brackets: bool = ..., use_index_order: bool = ..., - float_format: Optional[str] = ..., - double_format: Optional[str] = ..., + float_format: str | None = ..., + double_format: str | None = ..., use_field_number: bool = ..., - descriptor_pool: Optional[DescriptorPool] = ..., + descriptor_pool: DescriptorPool | None = ..., indent: int = ..., - message_formatter: Optional[_MessageFormatter] = ..., + message_formatter: _MessageFormatter | None = ..., print_unknown_fields: bool = ..., force_colon: bool = ..., ) -> str: ... @@ -45,10 +45,10 @@ def MessageToBytes( use_short_repeated_primitives: bool = ..., pointy_brackets: bool = ..., use_index_order: bool = ..., - float_format: Optional[str] = ..., - double_format: Optional[str] = ..., + float_format: str | None = ..., + double_format: str | None = ..., use_field_number: bool = ..., - descriptor_pool: Optional[DescriptorPool] = ..., + descriptor_pool: DescriptorPool | None = ..., indent: int = ..., message_formatter: _MessageFormatter = ..., print_unknown_fields: bool = ..., @@ -63,11 +63,11 @@ def PrintMessage( use_short_repeated_primitives: bool = ..., pointy_brackets: bool = ..., use_index_order: bool = ..., - float_format: Optional[str] = ..., - double_format: Optional[str] = ..., + float_format: str | None = ..., + double_format: str | None = ..., use_field_number: bool = ..., - descriptor_pool: Optional[DescriptorPool] = ..., - message_formatter: Optional[_MessageFormatter] = ..., + descriptor_pool: DescriptorPool | None = ..., + message_formatter: _MessageFormatter | None = ..., print_unknown_fields: bool = ..., force_colon: bool = ..., ) -> None: ... @@ -81,9 +81,9 @@ def PrintField( use_short_repeated_primitives: bool = ..., pointy_brackets: bool = ..., use_index_order: bool = ..., - float_format: Optional[str] = ..., - double_format: Optional[str] = ..., - message_formatter: Optional[_MessageFormatter] = ..., + float_format: str | None = ..., + double_format: str | None = ..., + message_formatter: _MessageFormatter | None = ..., print_unknown_fields: bool = ..., force_colon: bool = ..., ) -> None: ... @@ -97,9 +97,9 @@ def PrintFieldValue( use_short_repeated_primitives: bool = ..., pointy_brackets: bool = ..., use_index_order: bool = ..., - float_format: Optional[str] = ..., - double_format: Optional[str] = ..., - message_formatter: Optional[_MessageFormatter] = ..., + float_format: str | None = ..., + double_format: str | None = ..., + message_formatter: _MessageFormatter | None = ..., print_unknown_fields: bool = ..., force_colon: bool = ..., ) -> None: ... @@ -112,11 +112,11 @@ class _Printer: use_short_repeated_primitives: bool = ... pointy_brackets: bool = ... use_index_order: bool = ... - float_format: Optional[str] = ... - double_format: Optional[str] = ... + float_format: str | None = ... + double_format: str | None = ... use_field_number: bool = ... - descriptor_pool: Optional[DescriptorPool] = ... - message_formatter: Optional[_MessageFormatter] = ... + descriptor_pool: DescriptorPool | None = ... + message_formatter: _MessageFormatter | None = ... print_unknown_fields: bool = ... force_colon: bool = ... def __init__( @@ -128,11 +128,11 @@ class _Printer: use_short_repeated_primitives: bool = ..., pointy_brackets: bool = ..., use_index_order: bool = ..., - float_format: Optional[str] = ..., - double_format: Optional[str] = ..., + float_format: str | None = ..., + double_format: str | None = ..., use_field_number: bool = ..., - descriptor_pool: Optional[DescriptorPool] = ..., - message_formatter: Optional[_MessageFormatter] = ..., + descriptor_pool: DescriptorPool | None = ..., + message_formatter: _MessageFormatter | None = ..., print_unknown_fields: bool = ..., force_colon: bool = ..., ) -> None: ... @@ -141,44 +141,44 @@ class _Printer: def PrintFieldValue(self, field: FieldDescriptor, value: Any) -> None: ... def Parse( - text: Union[Text, bytes], + text: Text | bytes, message: _M, allow_unknown_extension: bool = ..., allow_field_number: bool = ..., - descriptor_pool: Optional[DescriptorPool] = ..., + descriptor_pool: DescriptorPool | None = ..., allow_unknown_field: bool = ..., ) -> _M: ... def Merge( - text: Union[Text, bytes], + text: Text | bytes, message: _M, allow_unknown_extension: bool = ..., allow_field_number: bool = ..., - descriptor_pool: Optional[DescriptorPool] = ..., + descriptor_pool: DescriptorPool | None = ..., allow_unknown_field: bool = ..., ) -> _M: ... def MergeLines( - lines: Iterable[Union[Text, bytes]], + lines: Iterable[Text | bytes], message: _M, allow_unknown_extension: bool = ..., allow_field_number: bool = ..., - descriptor_pool: Optional[DescriptorPool] = ..., + descriptor_pool: DescriptorPool | None = ..., allow_unknown_field: bool = ..., ) -> _M: ... class _Parser: allow_unknown_extension: bool = ... allow_field_number: bool = ... - descriptor_pool: Optional[DescriptorPool] = ... + descriptor_pool: DescriptorPool | None = ... allow_unknown_field: bool = ... def __init__( self, allow_unknown_extension: bool = ..., allow_field_number: bool = ..., - descriptor_pool: Optional[DescriptorPool] = ..., + descriptor_pool: DescriptorPool | None = ..., allow_unknown_field: bool = ..., ) -> None: ... - def ParseLines(self, lines: Iterable[Union[Text, bytes]], message: _M) -> _M: ... - def MergeLines(self, lines: Iterable[Union[Text, bytes]], message: _M) -> _M: ... + def ParseLines(self, lines: Iterable[Text | bytes], message: _M) -> _M: ... + def MergeLines(self, lines: Iterable[Text | bytes], message: _M) -> _M: ... _ParseError = ParseError diff --git a/stubs/pyOpenSSL/OpenSSL/crypto.pyi b/stubs/pyOpenSSL/OpenSSL/crypto.pyi index 9ffaa7412d4a..8516803219a7 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 6bce54a36e5f..a6994f9b5ae6 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 68bbb6c73a9d..ab0d4dddb358 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 7782cc0074b4..d62990449954 100644 --- a/stubs/python-dateutil/dateutil/parser/__init__.pyi +++ b/stubs/python-dateutil/dateutil/parser/__init__.pyi @@ -1,9 +1,9 @@ from datetime import datetime, tzinfo -from typing import IO, Any, Mapping, Text, Union +from typing import IO, Any, Mapping, Text from .isoparser import isoparse as isoparse, isoparser as isoparser -_FileOrStr = Union[bytes, Text, IO[str], IO[Any]] +_FileOrStr = bytes | Text | IO[str] | IO[Any] class parserinfo(object): JUMP: list[str] diff --git a/stubs/python-dateutil/dateutil/parser/isoparser.pyi b/stubs/python-dateutil/dateutil/parser/isoparser.pyi index ed24582d43c4..69d983ae71fb 100644 --- a/stubs/python-dateutil/dateutil/parser/isoparser.pyi +++ b/stubs/python-dateutil/dateutil/parser/isoparser.pyi @@ -1,9 +1,9 @@ from _typeshed import SupportsRead from datetime import date, datetime, time, tzinfo -from typing import Text, Union +from typing import Text -_Readable = SupportsRead[Union[Text, bytes]] -_TakesAscii = Union[Text, bytes, _Readable] +_Readable = SupportsRead[Text | bytes] +_TakesAscii = Text | bytes | _Readable class isoparser: def __init__(self, sep: Text | bytes | None = ...): ... diff --git a/stubs/python-dateutil/dateutil/tz/tz.pyi b/stubs/python-dateutil/dateutil/tz/tz.pyi index dad7fa15a0b3..296d4418e128 100644 --- a/stubs/python-dateutil/dateutil/tz/tz.pyi +++ b/stubs/python-dateutil/dateutil/tz/tz.pyi @@ -1,10 +1,10 @@ import datetime -from typing import IO, Any, Text, TypeVar, Union +from typing import IO, Any, Text, TypeVar from ..relativedelta import relativedelta from ._common import _tzinfo as _tzinfo, enfold as enfold, tzname_in_python2 as tzname_in_python2, tzrangebase as tzrangebase -_FileObj = Union[str, Text, IO[str], IO[Text]] +_FileObj = str | Text | IO[str] | IO[Text] _DT = TypeVar("_DT", bound=datetime.datetime) ZERO: datetime.timedelta diff --git a/stubs/redis/redis/client.pyi b/stubs/redis/redis/client.pyi index 554cb1abcf64..5660f6b78c2d 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 808227cdbee2..24e8cfb0a8b1 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 21693216eb5a..07c2872c583d 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 d4f65651a87b..a9c7f01a4f22 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 798a77062823..9e3401e78bb1 100644 --- a/stubs/simplejson/simplejson/__init__.pyi +++ b/stubs/simplejson/simplejson/__init__.pyi @@ -1,11 +1,11 @@ -from typing import IO, Any, Text, Union +from typing import IO, Any, Text from simplejson.decoder import JSONDecoder as JSONDecoder from simplejson.encoder import JSONEncoder as JSONEncoder, JSONEncoderForHTML as JSONEncoderForHTML from simplejson.raw_json import RawJSON as RawJSON from simplejson.scanner import JSONDecodeError as JSONDecodeError -_LoadsString = Union[Text, bytes, bytearray] +_LoadsString = Text | bytes | bytearray def dumps(obj: Any, *args: Any, **kwds: Any) -> str: ... def dump(obj: Any, fp: IO[str], *args: Any, **kwds: Any) -> None: ... diff --git a/stubs/tabulate/tabulate.pyi b/stubs/tabulate/tabulate.pyi index 1d0daa981c6c..e5208e0bef51 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 From b0cb5fa0de9081c44868390b3158dfd86f7f618f Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Tue, 15 Mar 2022 18:25:48 +0000 Subject: [PATCH 02/13] Avoid a `type[T]`-related mypy bug --- stdlib/_csv.pyi | 4 ++-- stdlib/inspect.pyi | 4 ++-- stubs/croniter/croniter.pyi | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/stdlib/_csv.pyi b/stdlib/_csv.pyi index d0bc6cc22819..d5ce462aed61 100644 --- a/stdlib/_csv.pyi +++ b/stdlib/_csv.pyi @@ -1,4 +1,4 @@ -from typing import Any, Iterable, Iterator, Protocol +from typing import Any, Iterable, Iterator, Protocol, Union from typing_extensions import Literal __version__: str @@ -21,7 +21,7 @@ class Dialect: strict: int def __init__(self) -> None: ... -_DialectLike = str | Dialect | type[Dialect] +_DialectLike = Union[str, Dialect, type[Dialect]] class _reader(Iterator[list[str]]): dialect: Dialect diff --git a/stdlib/inspect.pyi b/stdlib/inspect.pyi index 3c1f6de08d43..f87cd0e55acb 100644 --- a/stdlib/inspect.pyi +++ b/stdlib/inspect.pyi @@ -29,7 +29,7 @@ if sys.version_info >= (3, 7): MethodWrapperType, ) -from typing import Any, ClassVar, Coroutine, NamedTuple, Protocol, TypeVar +from typing import Any, ClassVar, Coroutine, NamedTuple, Protocol, TypeVar, Union from typing_extensions import Literal, ParamSpec, TypeGuard if sys.version_info >= (3, 11): @@ -242,7 +242,7 @@ def isdatadescriptor(object: object) -> TypeGuard[_SupportsSet[Any, Any] | _Supp # # Retrieving source code # -_SourceObjectType = ModuleType | type[Any] | MethodType | FunctionType | TracebackType | FrameType | CodeType | Callable[..., Any] +_SourceObjectType = Union[ModuleType, type[Any], MethodType, FunctionType, TracebackType, FrameType, CodeType, Callable[..., Any]] def findsource(object: _SourceObjectType) -> tuple[list[str], int]: ... def getabsfile(object: _SourceObjectType, _filename: str | None = ...) -> str: ... diff --git a/stubs/croniter/croniter.pyi b/stubs/croniter/croniter.pyi index 56ef5eacd916..891e76f7914e 100644 --- a/stubs/croniter/croniter.pyi +++ b/stubs/croniter/croniter.pyi @@ -3,7 +3,7 @@ from _typeshed import Self from typing import Any, Iterator, Text from typing_extensions import Literal -_RetType = type[float] | type[datetime.datetime] +_RetType = type[float | datetime.datetime] class CroniterError(ValueError): ... class CroniterBadCronError(CroniterError): ... From 5e9523f74172b1388027d4867c91b56d24a87782 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 15 Mar 2022 18:31:17 +0000 Subject: [PATCH 03/13] [pre-commit.ci] auto fixes from pre-commit.com hooks --- stdlib/_csv.pyi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/stdlib/_csv.pyi b/stdlib/_csv.pyi index d5ce462aed61..161a89778de8 100644 --- a/stdlib/_csv.pyi +++ b/stdlib/_csv.pyi @@ -21,7 +21,7 @@ class Dialect: strict: int def __init__(self) -> None: ... -_DialectLike = Union[str, Dialect, type[Dialect]] +_DialectLike = Union[str, Dialect, type[Dialect]] class _reader(Iterator[list[str]]): dialect: Dialect From c06ce4cbac65b698c162b275055c2dacc01efd22 Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Tue, 15 Mar 2022 19:03:52 +0000 Subject: [PATCH 04/13] Update signal.pyi --- stdlib/signal.pyi | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/stdlib/signal.pyi b/stdlib/signal.pyi index bac837bebfa6..632539bf7df1 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 +from typing import Any, Callable, Iterable, Union from typing_extensions import final NSIG: int @@ -61,7 +61,7 @@ SIG_DFL: Handlers SIG_IGN: Handlers _SIGNUM = int | Signals -_HANDLER = Callable[[int, FrameType | None], Any] | int | Handlers | None +_HANDLER = Union[Callable[[int, FrameType | None], Any], int, Handlers, None] def default_int_handler(__signalnum: int, __frame: FrameType | None) -> None: ... From 9fa1a0dcf7627ba849bd8ef737f010592aa86c4d Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Tue, 15 Mar 2022 19:05:41 +0000 Subject: [PATCH 05/13] Update __init__.pyi --- stdlib/tkinter/__init__.pyi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/stdlib/tkinter/__init__.pyi b/stdlib/tkinter/__init__.pyi index e2c9afba63e8..74844e94a5f4 100644 --- a/stdlib/tkinter/__init__.pyi +++ b/stdlib/tkinter/__init__.pyi @@ -193,7 +193,7 @@ _Padding = Union[ _Relief = Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] # manual page: Tk_GetRelief _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 = int | Literal[""] | Callable[[str], bool | None] # -takefocus in manual page named 'options' +_TakeFocusValue = Union[int, Literal[""], Callable[[str], bool | None]] # -takefocus in manual page named 'options' class EventType(str, Enum): Activate: str From dce2004b824333d6fdb08e6370584b82ff01c885 Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Tue, 15 Mar 2022 19:07:08 +0000 Subject: [PATCH 06/13] Update ssl.pyi --- stdlib/ssl.pyi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/stdlib/ssl.pyi b/stdlib/ssl.pyi index 4fe30e97ea1c..dbf3309c553f 100644 --- a/stdlib/ssl.pyi +++ b/stdlib/ssl.pyi @@ -10,7 +10,7 @@ _PCTRTTT = tuple[_PCTRTT, ...] _PeerCertRetDictType = dict[str, str | _PCTRTTT | _PCTRTT] _PeerCertRetType = _PeerCertRetDictType | bytes | None _EnumRetType = list[tuple[bytes, str, Union[set[str], bool]]] -_PasswordType = Callable[[], str | bytes] | str | bytes +_PasswordType = Union[Callable[[], str | bytes], str, bytes] _SrvnmeCbType = Callable[[SSLSocket | SSLObject, str | None, SSLSocket], int | None] From d9cfea77762f6aa0e53354dcc502c64bd9f79f4e Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Tue, 15 Mar 2022 19:10:13 +0000 Subject: [PATCH 07/13] Update inspect.pyi --- stdlib/@python2/inspect.pyi | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/stdlib/@python2/inspect.pyi b/stdlib/@python2/inspect.pyi index a6f2af2cd600..aa0450ce6785 100644 --- a/stdlib/@python2/inspect.pyi +++ b/stdlib/@python2/inspect.pyi @@ -1,5 +1,5 @@ from types import CodeType, FrameType, FunctionType, MethodType, ModuleType, TracebackType -from typing import Any, AnyStr, Callable, NamedTuple, Optional, Sequence +from typing import Any, AnyStr, Callable, NamedTuple, Optional, Sequence, Union # Types and members class EndOfBlock(Exception): ... @@ -50,7 +50,7 @@ def isgetsetdescriptor(object: object) -> bool: ... def ismemberdescriptor(object: object) -> bool: ... # Retrieving source code -_SourceObjectType = ModuleType | type[Any] | MethodType | FunctionType | TracebackType | FrameType | CodeType | Callable[..., Any] +_SourceObjectType = Union[ModuleType, type[Any], MethodType, FunctionType, TracebackType, FrameType, CodeType, Callable[..., Any]] def findsource(object: _SourceObjectType) -> tuple[list[str], int]: ... def getabsfile(object: _SourceObjectType) -> str: ... From 2ab349fc23533a6da0f166bc257dd654c190420e Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Tue, 15 Mar 2022 19:12:05 +0000 Subject: [PATCH 08/13] Update readline.pyi --- stdlib/@python2/readline.pyi | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/stdlib/@python2/readline.pyi b/stdlib/@python2/readline.pyi index 56db3a626db1..af642410b007 100644 --- a/stdlib/@python2/readline.pyi +++ b/stdlib/@python2/readline.pyi @@ -1,8 +1,8 @@ import sys -from typing import Callable, Sequence, Text +from typing import Callable, Optional, Sequence, Text if sys.platform != "win32": - _CompleterT = Callable[[str, int], str | None] | 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: ... From 03123d4e9c167db16bb3b24abd9c583e72570cef Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Tue, 15 Mar 2022 19:13:01 +0000 Subject: [PATCH 09/13] Update _csv.pyi --- stdlib/@python2/_csv.pyi | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/stdlib/@python2/_csv.pyi b/stdlib/@python2/_csv.pyi index 1033924f7e35..e01ccc19cb19 100644 --- a/stdlib/@python2/_csv.pyi +++ b/stdlib/@python2/_csv.pyi @@ -1,4 +1,4 @@ -from typing import Any, Iterable, Iterator, Protocol, Sequence, Text +from typing import Any, Iterable, Iterator, Protocol, Sequence, Text, Union QUOTE_ALL: int QUOTE_MINIMAL: int @@ -18,7 +18,7 @@ class Dialect: strict: int def __init__(self) -> None: ... -_DialectLike = str | Dialect | type[Dialect] +_DialectLike = Union[str, Dialect, type[Dialect]] class _reader(Iterator[list[str]]): dialect: Dialect From be11dcb79b4ec7354efc30ab42488280f397fc68 Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Tue, 15 Mar 2022 19:14:23 +0000 Subject: [PATCH 10/13] Update ssl.pyi --- stdlib/@python2/ssl.pyi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/stdlib/@python2/ssl.pyi b/stdlib/@python2/ssl.pyi index dafba0b1d62b..2c6b32567249 100644 --- a/stdlib/@python2/ssl.pyi +++ b/stdlib/@python2/ssl.pyi @@ -9,7 +9,7 @@ _PCTRTTT = tuple[_PCTRTT, ...] _PeerCertRetDictType = dict[str, str | _PCTRTTT | _PCTRTT] _PeerCertRetType = _PeerCertRetDictType | bytes | None _EnumRetType = list[tuple[bytes, str, Union[set[str], bool]]] -_PasswordType = Callable[[], str | bytes] | str | bytes +_PasswordType = Union[Callable[[], str | bytes], str, bytes] _SC1ArgT = SSLSocket _SrvnmeCbType = Callable[[_SC1ArgT, str | None, SSLSocket], int | None] From 2dfa58dff90b0c90f4939275db08c9a64e28258c Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Tue, 15 Mar 2022 22:03:36 +0000 Subject: [PATCH 11/13] Add a regression test --- tests/check_new_syntax.py | 48 ++++++++++++++++++++++++++++++--------- 1 file changed, 37 insertions(+), 11 deletions(-) diff --git a/tests/check_new_syntax.py b/tests/check_new_syntax.py index f6945a003261..9fbb2cf4da87 100755 --- a/tests/check_new_syntax.py +++ b/tests/check_new_syntax.py @@ -10,11 +10,12 @@ ) -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,47 @@ def visit_Subscript(self, node: ast.Subscript) -> None: 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: + 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_FunctionDef(self, node: ast.FunctionDef) -> None: + def _visit_function(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None: if node.returns is not None: - UnionFinder().visit(node.returns) + AnnotationUnionFinder().visit(node.returns) self.generic_visit(node) + def visit_FunctionDef(self, node: ast.FunctionDef) -> None: + self._visit_function(node) + def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None: - 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 +110,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)) From ac6b089403fbfe05f440e4c80f7fd422d6b280cc Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Tue, 15 Mar 2022 23:44:36 +0000 Subject: [PATCH 12/13] Revert changes to protobuf stubs --- .../google/protobuf/descriptor_pool.pyi | 6 +- .../google/protobuf/internal/containers.pyi | 18 ++--- .../protobuf/internal/extension_dict.pyi | 4 +- .../protobuf/internal/well_known_types.pyi | 6 +- .../protobuf/google/protobuf/json_format.pyi | 17 ++-- .../google/protobuf/message_factory.pyi | 4 +- stubs/protobuf/google/protobuf/service.pyi | 12 +-- .../google/protobuf/symbol_database.pyi | 4 +- .../protobuf/google/protobuf/text_format.pyi | 80 +++++++++---------- 9 files changed, 77 insertions(+), 74 deletions(-) diff --git a/stubs/protobuf/google/protobuf/descriptor_pool.pyi b/stubs/protobuf/google/protobuf/descriptor_pool.pyi index f1ecee77622a..aabe9d9dca0a 100644 --- a/stubs/protobuf/google/protobuf/descriptor_pool.pyi +++ b/stubs/protobuf/google/protobuf/descriptor_pool.pyi @@ -1,8 +1,8 @@ -from typing import Any +from typing import Any, Optional class DescriptorPool: - def __new__(cls, descriptor_db: Any | None = ...): ... - def __init__(self, descriptor_db: Any | None = ...) -> None: ... + def __new__(cls, descriptor_db: Optional[Any] = ...): ... + def __init__(self, descriptor_db: Optional[Any] = ...) -> None: ... def Add(self, file_desc_proto): ... def AddSerializedFile(self, serialized_file_desc_proto): ... def AddDescriptor(self, desc): ... diff --git a/stubs/protobuf/google/protobuf/internal/containers.pyi b/stubs/protobuf/google/protobuf/internal/containers.pyi index 0d7a97a4a65b..1a86d45a1393 100644 --- a/stubs/protobuf/google/protobuf/internal/containers.pyi +++ b/stubs/protobuf/google/protobuf/internal/containers.pyi @@ -1,5 +1,5 @@ from collections.abc import MutableMapping -from typing import Any, Callable, Iterable, Iterator, Sequence, Text, TypeVar, overload +from typing import Any, Callable, Iterable, Iterator, Optional, Sequence, Text, TypeVar, Union, overload from typing_extensions import SupportsIndex from google.protobuf.descriptor import Descriptor @@ -9,8 +9,8 @@ from google.protobuf.internal.type_checkers import _ValueChecker from google.protobuf.message import Message _T = TypeVar("_T") -_K = TypeVar("_K", bound=bool | int | Text) -_ScalarV = TypeVar("_ScalarV", bound=bool | int | float | Text | bytes) +_K = TypeVar("_K", bound=Union[bool, int, Text]) +_ScalarV = TypeVar("_ScalarV", bound=Union[bool, int, float, Text, bytes]) _MessageV = TypeVar("_MessageV", bound=Message) _M = TypeVar("_M") @@ -19,7 +19,7 @@ class BaseContainer(Sequence[_T]): def __len__(self) -> int: ... def __ne__(self, other: object) -> bool: ... def __hash__(self) -> int: ... - def sort(self, *, key: Callable[[_T], Any] | None = ..., reverse: bool = ...) -> None: ... + def sort(self, *, key: Optional[Callable[[_T], Any]] = ..., reverse: bool = ...) -> None: ... @overload def __getitem__(self, key: SupportsIndex) -> _T: ... @overload @@ -29,7 +29,7 @@ class RepeatedScalarFieldContainer(BaseContainer[_ScalarV]): def __init__(self, message_listener: MessageListener, type_checker: _ValueChecker[_ScalarV]) -> None: ... def append(self, value: _ScalarV) -> None: ... def insert(self, key: int, value: _ScalarV) -> None: ... - def extend(self, elem_seq: Iterable[_ScalarV] | None) -> None: ... + def extend(self, elem_seq: Optional[Iterable[_ScalarV]]) -> None: ... def MergeFrom(self: _M, other: _M) -> None: ... def remove(self, elem: _ScalarV) -> None: ... def pop(self, key: int = ...) -> _ScalarV: ... @@ -39,7 +39,7 @@ class RepeatedScalarFieldContainer(BaseContainer[_ScalarV]): def __setitem__(self, key: slice, value: Iterable[_ScalarV]) -> None: ... def __getslice__(self, start: int, stop: int) -> list[_ScalarV]: ... def __setslice__(self, start: int, stop: int, values: Iterable[_ScalarV]) -> None: ... - def __delitem__(self, key: int | slice) -> None: ... + def __delitem__(self, key: Union[int, slice]) -> None: ... def __delslice__(self, start: int, stop: int) -> None: ... def __eq__(self, other: object) -> bool: ... @@ -53,7 +53,7 @@ class RepeatedCompositeFieldContainer(BaseContainer[_MessageV]): def remove(self, elem: _MessageV) -> None: ... def pop(self, key: int = ...) -> _MessageV: ... def __getslice__(self, start: int, stop: int) -> list[_MessageV]: ... - def __delitem__(self, key: int | slice) -> None: ... + def __delitem__(self, key: Union[int, slice]) -> None: ... def __delslice__(self, start: int, stop: int) -> None: ... def __eq__(self, other: object) -> bool: ... @@ -74,7 +74,7 @@ class ScalarMap(MutableMapping[_K, _ScalarV]): @overload def get(self, key: _K, default: None = ...) -> _ScalarV: ... @overload - def get(self, key: _K, default: _ScalarV | _T) -> _ScalarV | _T: ... + def get(self, key: _K, default: Union[_ScalarV, _T]) -> Union[_ScalarV, _T]: ... def MergeFrom(self: _M, other: _M): ... def InvalidateIterators(self) -> None: ... def GetEntryClass(self) -> GeneratedProtocolMessageType: ... @@ -96,7 +96,7 @@ class MessageMap(MutableMapping[_K, _MessageV]): @overload def get(self, key: _K, default: None = ...) -> _MessageV: ... @overload - def get(self, key: _K, default: _MessageV | _T) -> _MessageV | _T: ... + def get(self, key: _K, default: Union[_MessageV, _T]) -> Union[_MessageV, _T]: ... def get_or_create(self, key: _K) -> _MessageV: ... def MergeFrom(self: _M, other: _M): ... def InvalidateIterators(self) -> None: ... diff --git a/stubs/protobuf/google/protobuf/internal/extension_dict.pyi b/stubs/protobuf/google/protobuf/internal/extension_dict.pyi index a8aead6fd3ad..486e367eaa15 100644 --- a/stubs/protobuf/google/protobuf/internal/extension_dict.pyi +++ b/stubs/protobuf/google/protobuf/internal/extension_dict.pyi @@ -1,4 +1,4 @@ -from typing import Any, Generic, Iterator, Text, TypeVar +from typing import Any, Generic, Iterator, Text, TypeVar, Union from google.protobuf.descriptor import FieldDescriptor from google.protobuf.internal.containers import RepeatedCompositeFieldContainer, RepeatedScalarFieldContainer @@ -7,7 +7,7 @@ from google.protobuf.message import Message _ContainerMessageT = TypeVar("_ContainerMessageT", bound=Message) _ExtenderMessageT = TypeVar( "_ExtenderMessageT", - bound=Message | RepeatedScalarFieldContainer[Any] | RepeatedCompositeFieldContainer[Any] | bool | int | float | Text | bytes, + bound=Union[Message, RepeatedScalarFieldContainer[Any], RepeatedCompositeFieldContainer[Any], bool, int, float, Text, bytes], ) class _ExtensionFieldDescriptor(FieldDescriptor, Generic[_ContainerMessageT, _ExtenderMessageT]): ... diff --git a/stubs/protobuf/google/protobuf/internal/well_known_types.pyi b/stubs/protobuf/google/protobuf/internal/well_known_types.pyi index 1f00ecf295d4..146907ce31bc 100644 --- a/stubs/protobuf/google/protobuf/internal/well_known_types.pyi +++ b/stubs/protobuf/google/protobuf/internal/well_known_types.pyi @@ -1,10 +1,10 @@ from datetime import datetime, timedelta -from typing import Any as tAny +from typing import Any as tAny, Optional class Any: type_url: tAny = ... value: tAny = ... - def Pack(self, msg: tAny, type_url_prefix: str = ..., deterministic: tAny | None = ...) -> None: ... + def Pack(self, msg: tAny, type_url_prefix: str = ..., deterministic: Optional[tAny] = ...) -> None: ... def Unpack(self, msg: tAny): ... def TypeName(self): ... def Is(self, descriptor: tAny): ... @@ -55,7 +55,7 @@ class FieldMask: ) -> None: ... class _FieldMaskTree: - def __init__(self, field_mask: tAny | None = ...) -> None: ... + def __init__(self, field_mask: Optional[tAny] = ...) -> None: ... def MergeFromFieldMask(self, field_mask: tAny) -> None: ... def AddPath(self, path: tAny): ... def ToFieldMask(self, field_mask: tAny) -> None: ... diff --git a/stubs/protobuf/google/protobuf/json_format.pyi b/stubs/protobuf/google/protobuf/json_format.pyi index f43d66e34012..6ecc10c520ca 100644 --- a/stubs/protobuf/google/protobuf/json_format.pyi +++ b/stubs/protobuf/google/protobuf/json_format.pyi @@ -1,4 +1,4 @@ -from typing import Any, Text, TypeVar +from typing import Any, Optional, Text, TypeVar, Union from google.protobuf.descriptor_pool import DescriptorPool from google.protobuf.message import Message @@ -16,20 +16,23 @@ def MessageToJson( indent: int = ..., sort_keys: bool = ..., use_integers_for_enums: bool = ..., - descriptor_pool: DescriptorPool | None = ..., - float_precision: int | None = ..., + descriptor_pool: Optional[DescriptorPool] = ..., + float_precision: Optional[int] = ..., ) -> str: ... def MessageToDict( message: Message, including_default_value_fields: bool = ..., preserving_proto_field_name: bool = ..., use_integers_for_enums: bool = ..., - descriptor_pool: DescriptorPool | None = ..., - float_precision: int | None = ..., + descriptor_pool: Optional[DescriptorPool] = ..., + float_precision: Optional[int] = ..., ) -> dict[Text, Any]: ... def Parse( - text: bytes | Text, message: _MessageT, ignore_unknown_fields: bool = ..., descriptor_pool: DescriptorPool | None = ... + text: Union[bytes, Text], + message: _MessageT, + ignore_unknown_fields: bool = ..., + descriptor_pool: Optional[DescriptorPool] = ..., ) -> _MessageT: ... def ParseDict( - js_dict: Any, message: _MessageT, ignore_unknown_fields: bool = ..., descriptor_pool: DescriptorPool | None = ... + js_dict: Any, message: _MessageT, ignore_unknown_fields: bool = ..., descriptor_pool: Optional[DescriptorPool] = ... ) -> _MessageT: ... diff --git a/stubs/protobuf/google/protobuf/message_factory.pyi b/stubs/protobuf/google/protobuf/message_factory.pyi index c8fb7983da25..ae299d8aeb69 100644 --- a/stubs/protobuf/google/protobuf/message_factory.pyi +++ b/stubs/protobuf/google/protobuf/message_factory.pyi @@ -1,4 +1,4 @@ -from typing import Any, Iterable +from typing import Any, Iterable, Optional from google.protobuf.descriptor import Descriptor from google.protobuf.descriptor_pb2 import FileDescriptorProto @@ -7,7 +7,7 @@ from google.protobuf.message import Message class MessageFactory: pool: Any - def __init__(self, pool: DescriptorPool | None = ...) -> None: ... + def __init__(self, pool: Optional[DescriptorPool] = ...) -> None: ... def GetPrototype(self, descriptor: Descriptor) -> type[Message]: ... def GetMessages(self, files: Iterable[str]) -> dict[str, type[Message]]: ... diff --git a/stubs/protobuf/google/protobuf/service.pyi b/stubs/protobuf/google/protobuf/service.pyi index 757c2449e63d..7f7a762ac9fa 100644 --- a/stubs/protobuf/google/protobuf/service.pyi +++ b/stubs/protobuf/google/protobuf/service.pyi @@ -1,5 +1,5 @@ from concurrent.futures import Future -from typing import Callable, Text +from typing import Callable, Optional, Text from google.protobuf.descriptor import MethodDescriptor, ServiceDescriptor from google.protobuf.message import Message @@ -14,15 +14,15 @@ class Service: method_descriptor: MethodDescriptor, rpc_controller: RpcController, request: Message, - done: Callable[[Message], None] | None, - ) -> Future[Message] | None: ... + done: Optional[Callable[[Message], None]], + ) -> Optional[Future[Message]]: ... def GetRequestClass(self, method_descriptor: MethodDescriptor) -> type[Message]: ... def GetResponseClass(self, method_descriptor: MethodDescriptor) -> type[Message]: ... class RpcController: def Reset(self) -> None: ... def Failed(self) -> bool: ... - def ErrorText(self) -> Text | None: ... + def ErrorText(self) -> Optional[Text]: ... def StartCancel(self) -> None: ... def SetFailed(self, reason: Text) -> None: ... def IsCanceled(self) -> bool: ... @@ -35,5 +35,5 @@ class RpcChannel: rpc_controller: RpcController, request: Message, response_class: type[Message], - done: Callable[[Message], None] | None, - ) -> Future[Message] | None: ... + done: Optional[Callable[[Message], None]], + ) -> Optional[Future[Message]]: ... diff --git a/stubs/protobuf/google/protobuf/symbol_database.pyi b/stubs/protobuf/google/protobuf/symbol_database.pyi index 73edfe2398fe..0644a9be82f3 100644 --- a/stubs/protobuf/google/protobuf/symbol_database.pyi +++ b/stubs/protobuf/google/protobuf/symbol_database.pyi @@ -1,11 +1,11 @@ -from typing import Iterable +from typing import Iterable, Union from google.protobuf.descriptor import Descriptor, EnumDescriptor, FileDescriptor, ServiceDescriptor from google.protobuf.message import Message from google.protobuf.message_factory import MessageFactory class SymbolDatabase(MessageFactory): - def RegisterMessage(self, message: type[Message] | Message) -> type[Message] | Message: ... + def RegisterMessage(self, message: Union[type[Message], Message]) -> Union[type[Message], Message]: ... def RegisterMessageDescriptor(self, message_descriptor: Descriptor) -> None: ... def RegisterEnumDescriptor(self, enum_descriptor: EnumDescriptor) -> EnumDescriptor: ... def RegisterServiceDescriptor(self, service_descriptor: ServiceDescriptor) -> None: ... diff --git a/stubs/protobuf/google/protobuf/text_format.pyi b/stubs/protobuf/google/protobuf/text_format.pyi index 1f9f21aece12..f70959d02b47 100644 --- a/stubs/protobuf/google/protobuf/text_format.pyi +++ b/stubs/protobuf/google/protobuf/text_format.pyi @@ -1,5 +1,5 @@ from _typeshed import SupportsWrite -from typing import Any, Callable, Iterable, Text, TypeVar +from typing import Any, Callable, Iterable, Optional, Text, TypeVar, Union from .descriptor import FieldDescriptor from .descriptor_pool import DescriptorPool @@ -10,9 +10,9 @@ _M = TypeVar("_M", bound=Message) # message type (of self) class Error(Exception): ... class ParseError(Error): - def __init__(self, message: str | None = ..., line: int | None = ..., column: int | None = ...) -> None: ... - def GetLine(self) -> int | None: ... - def GetColumn(self) -> int | None: ... + def __init__(self, message: Optional[str] = ..., line: Optional[int] = ..., column: Optional[int] = ...) -> None: ... + def GetLine(self) -> Optional[int]: ... + def GetColumn(self) -> Optional[int]: ... class TextWriter: def __init__(self, as_utf8: bool) -> None: ... @@ -20,7 +20,7 @@ class TextWriter: def getvalue(self) -> str: ... def close(self) -> None: ... -_MessageFormatter = Callable[[Message, int, bool], Text | None] +_MessageFormatter = Callable[[Message, int, bool], Optional[Text]] def MessageToString( message: Message, @@ -29,12 +29,12 @@ def MessageToString( use_short_repeated_primitives: bool = ..., pointy_brackets: bool = ..., use_index_order: bool = ..., - float_format: str | None = ..., - double_format: str | None = ..., + float_format: Optional[str] = ..., + double_format: Optional[str] = ..., use_field_number: bool = ..., - descriptor_pool: DescriptorPool | None = ..., + descriptor_pool: Optional[DescriptorPool] = ..., indent: int = ..., - message_formatter: _MessageFormatter | None = ..., + message_formatter: Optional[_MessageFormatter] = ..., print_unknown_fields: bool = ..., force_colon: bool = ..., ) -> str: ... @@ -45,10 +45,10 @@ def MessageToBytes( use_short_repeated_primitives: bool = ..., pointy_brackets: bool = ..., use_index_order: bool = ..., - float_format: str | None = ..., - double_format: str | None = ..., + float_format: Optional[str] = ..., + double_format: Optional[str] = ..., use_field_number: bool = ..., - descriptor_pool: DescriptorPool | None = ..., + descriptor_pool: Optional[DescriptorPool] = ..., indent: int = ..., message_formatter: _MessageFormatter = ..., print_unknown_fields: bool = ..., @@ -63,11 +63,11 @@ def PrintMessage( use_short_repeated_primitives: bool = ..., pointy_brackets: bool = ..., use_index_order: bool = ..., - float_format: str | None = ..., - double_format: str | None = ..., + float_format: Optional[str] = ..., + double_format: Optional[str] = ..., use_field_number: bool = ..., - descriptor_pool: DescriptorPool | None = ..., - message_formatter: _MessageFormatter | None = ..., + descriptor_pool: Optional[DescriptorPool] = ..., + message_formatter: Optional[_MessageFormatter] = ..., print_unknown_fields: bool = ..., force_colon: bool = ..., ) -> None: ... @@ -81,9 +81,9 @@ def PrintField( use_short_repeated_primitives: bool = ..., pointy_brackets: bool = ..., use_index_order: bool = ..., - float_format: str | None = ..., - double_format: str | None = ..., - message_formatter: _MessageFormatter | None = ..., + float_format: Optional[str] = ..., + double_format: Optional[str] = ..., + message_formatter: Optional[_MessageFormatter] = ..., print_unknown_fields: bool = ..., force_colon: bool = ..., ) -> None: ... @@ -97,9 +97,9 @@ def PrintFieldValue( use_short_repeated_primitives: bool = ..., pointy_brackets: bool = ..., use_index_order: bool = ..., - float_format: str | None = ..., - double_format: str | None = ..., - message_formatter: _MessageFormatter | None = ..., + float_format: Optional[str] = ..., + double_format: Optional[str] = ..., + message_formatter: Optional[_MessageFormatter] = ..., print_unknown_fields: bool = ..., force_colon: bool = ..., ) -> None: ... @@ -112,11 +112,11 @@ class _Printer: use_short_repeated_primitives: bool = ... pointy_brackets: bool = ... use_index_order: bool = ... - float_format: str | None = ... - double_format: str | None = ... + float_format: Optional[str] = ... + double_format: Optional[str] = ... use_field_number: bool = ... - descriptor_pool: DescriptorPool | None = ... - message_formatter: _MessageFormatter | None = ... + descriptor_pool: Optional[DescriptorPool] = ... + message_formatter: Optional[_MessageFormatter] = ... print_unknown_fields: bool = ... force_colon: bool = ... def __init__( @@ -128,11 +128,11 @@ class _Printer: use_short_repeated_primitives: bool = ..., pointy_brackets: bool = ..., use_index_order: bool = ..., - float_format: str | None = ..., - double_format: str | None = ..., + float_format: Optional[str] = ..., + double_format: Optional[str] = ..., use_field_number: bool = ..., - descriptor_pool: DescriptorPool | None = ..., - message_formatter: _MessageFormatter | None = ..., + descriptor_pool: Optional[DescriptorPool] = ..., + message_formatter: Optional[_MessageFormatter] = ..., print_unknown_fields: bool = ..., force_colon: bool = ..., ) -> None: ... @@ -141,44 +141,44 @@ class _Printer: def PrintFieldValue(self, field: FieldDescriptor, value: Any) -> None: ... def Parse( - text: Text | bytes, + text: Union[Text, bytes], message: _M, allow_unknown_extension: bool = ..., allow_field_number: bool = ..., - descriptor_pool: DescriptorPool | None = ..., + descriptor_pool: Optional[DescriptorPool] = ..., allow_unknown_field: bool = ..., ) -> _M: ... def Merge( - text: Text | bytes, + text: Union[Text, bytes], message: _M, allow_unknown_extension: bool = ..., allow_field_number: bool = ..., - descriptor_pool: DescriptorPool | None = ..., + descriptor_pool: Optional[DescriptorPool] = ..., allow_unknown_field: bool = ..., ) -> _M: ... def MergeLines( - lines: Iterable[Text | bytes], + lines: Iterable[Union[Text, bytes]], message: _M, allow_unknown_extension: bool = ..., allow_field_number: bool = ..., - descriptor_pool: DescriptorPool | None = ..., + descriptor_pool: Optional[DescriptorPool] = ..., allow_unknown_field: bool = ..., ) -> _M: ... class _Parser: allow_unknown_extension: bool = ... allow_field_number: bool = ... - descriptor_pool: DescriptorPool | None = ... + descriptor_pool: Optional[DescriptorPool] = ... allow_unknown_field: bool = ... def __init__( self, allow_unknown_extension: bool = ..., allow_field_number: bool = ..., - descriptor_pool: DescriptorPool | None = ..., + descriptor_pool: Optional[DescriptorPool] = ..., allow_unknown_field: bool = ..., ) -> None: ... - def ParseLines(self, lines: Iterable[Text | bytes], message: _M) -> _M: ... - def MergeLines(self, lines: Iterable[Text | bytes], message: _M) -> _M: ... + def ParseLines(self, lines: Iterable[Union[Text, bytes]], message: _M) -> _M: ... + def MergeLines(self, lines: Iterable[Union[Text, bytes]], message: _M) -> _M: ... _ParseError = ParseError From 577a7172aa2ca3c67d682f49918982afe61c480f Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Tue, 15 Mar 2022 23:45:59 +0000 Subject: [PATCH 13/13] Add comment to `check_new_syntax.py` --- tests/check_new_syntax.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/check_new_syntax.py b/tests/check_new_syntax.py index 9fbb2cf4da87..4a63e8e84e57 100755 --- a/tests/check_new_syntax.py +++ b/tests/check_new_syntax.py @@ -32,6 +32,7 @@ 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):