From 92c3aa0e69d55c19d53a6cb3f17975d4310101ff Mon Sep 17 00:00:00 2001 From: Jared Hance Date: Wed, 31 Jan 2024 12:25:58 -0800 Subject: [PATCH 1/7] Sync typeshed Source commit: https://github.com/python/typeshed/commit/284afde9cc9f0b68805a1e0fa987fec4bad3974e --- mypy/typeshed/stdlib/VERSIONS | 1 - mypy/typeshed/stdlib/_ast.pyi | 69 +- mypy/typeshed/stdlib/_codecs.pyi | 9 +- mypy/typeshed/stdlib/_collections_abc.pyi | 2 +- mypy/typeshed/stdlib/_csv.pyi | 4 +- mypy/typeshed/stdlib/_ctypes.pyi | 10 +- mypy/typeshed/stdlib/_curses.pyi | 18 +- mypy/typeshed/stdlib/_decimal.pyi | 4 +- mypy/typeshed/stdlib/_dummy_threading.pyi | 19 +- mypy/typeshed/stdlib/_heapq.pyi | 3 +- mypy/typeshed/stdlib/_json.pyi | 3 +- mypy/typeshed/stdlib/_operator.pyi | 4 +- mypy/typeshed/stdlib/_osx_support.pyi | 9 +- mypy/typeshed/stdlib/_posixsubprocess.pyi | 2 +- mypy/typeshed/stdlib/_sitebuiltins.pyi | 3 +- mypy/typeshed/stdlib/_socket.pyi | 677 ++++++++++-------- mypy/typeshed/stdlib/_stat.pyi | 4 +- mypy/typeshed/stdlib/_thread.pyi | 33 +- mypy/typeshed/stdlib/_tkinter.pyi | 37 +- mypy/typeshed/stdlib/_typeshed/__init__.pyi | 24 +- mypy/typeshed/stdlib/_weakref.pyi | 4 +- mypy/typeshed/stdlib/_winapi.pyi | 75 +- mypy/typeshed/stdlib/abc.pyi | 4 +- mypy/typeshed/stdlib/aifc.pyi | 4 +- mypy/typeshed/stdlib/argparse.pyi | 7 +- mypy/typeshed/stdlib/array.pyi | 4 +- mypy/typeshed/stdlib/ast.pyi | 222 +++--- mypy/typeshed/stdlib/asyncio/__init__.pyi | 4 +- mypy/typeshed/stdlib/asyncio/base_events.pyi | 52 +- mypy/typeshed/stdlib/asyncio/base_futures.pyi | 3 +- mypy/typeshed/stdlib/asyncio/constants.pyi | 2 +- mypy/typeshed/stdlib/asyncio/coroutines.pyi | 2 - mypy/typeshed/stdlib/asyncio/events.pyi | 105 +-- mypy/typeshed/stdlib/asyncio/futures.pyi | 19 +- mypy/typeshed/stdlib/asyncio/locks.pyi | 9 +- .../stdlib/asyncio/proactor_events.pyi | 3 +- mypy/typeshed/stdlib/asyncio/runners.pyi | 9 +- mypy/typeshed/stdlib/asyncio/sslproto.pyi | 4 +- mypy/typeshed/stdlib/asyncio/streams.pyi | 58 +- mypy/typeshed/stdlib/asyncio/subprocess.pyi | 20 +- mypy/typeshed/stdlib/asyncio/tasks.pyi | 21 +- mypy/typeshed/stdlib/asyncio/timeouts.pyi | 3 +- mypy/typeshed/stdlib/asyncio/unix_events.pyi | 46 +- .../stdlib/asyncio/windows_events.pyi | 3 +- .../typeshed/stdlib/asyncio/windows_utils.pyi | 4 +- mypy/typeshed/stdlib/bdb.pyi | 14 +- mypy/typeshed/stdlib/binascii.pyi | 12 +- mypy/typeshed/stdlib/binhex.pyi | 4 +- mypy/typeshed/stdlib/builtins.pyi | 447 ++++++------ mypy/typeshed/stdlib/bz2.pyi | 4 +- mypy/typeshed/stdlib/cProfile.pyi | 6 +- mypy/typeshed/stdlib/calendar.pyi | 4 +- mypy/typeshed/stdlib/cgi.pyi | 12 - mypy/typeshed/stdlib/cgitb.pyi | 3 +- mypy/typeshed/stdlib/cmath.pyi | 11 +- mypy/typeshed/stdlib/cmd.pyi | 3 +- mypy/typeshed/stdlib/codecs.pyi | 19 +- mypy/typeshed/stdlib/collections/__init__.pyi | 16 +- .../stdlib/concurrent/futures/__init__.pyi | 6 +- .../stdlib/concurrent/futures/_base.pyi | 26 +- mypy/typeshed/stdlib/configparser.pyi | 4 +- mypy/typeshed/stdlib/contextvars.pyi | 4 +- mypy/typeshed/stdlib/csv.pyi | 20 +- mypy/typeshed/stdlib/ctypes/__init__.pyi | 76 +- mypy/typeshed/stdlib/ctypes/_endian.pyi | 19 + mypy/typeshed/stdlib/ctypes/wintypes.pyi | 140 ++-- mypy/typeshed/stdlib/dataclasses.pyi | 21 +- mypy/typeshed/stdlib/datetime.pyi | 74 +- mypy/typeshed/stdlib/dbm/__init__.pyi | 3 +- mypy/typeshed/stdlib/distutils/ccompiler.pyi | 2 +- .../stdlib/distutils/cygwinccompiler.pyi | 2 +- mypy/typeshed/stdlib/distutils/filelist.pyi | 3 +- mypy/typeshed/stdlib/distutils/util.pyi | 8 +- .../stdlib/email/_header_value_parser.pyi | 38 +- mypy/typeshed/stdlib/email/headerregistry.pyi | 21 +- mypy/typeshed/stdlib/email/message.pyi | 4 +- mypy/typeshed/stdlib/enum.pyi | 4 +- mypy/typeshed/stdlib/fcntl.pyi | 17 +- mypy/typeshed/stdlib/filecmp.pyi | 3 +- mypy/typeshed/stdlib/fileinput.pyi | 115 +-- mypy/typeshed/stdlib/fractions.pyi | 34 +- mypy/typeshed/stdlib/ftplib.pyi | 4 +- mypy/typeshed/stdlib/functools.pyi | 120 ++-- mypy/typeshed/stdlib/gc.pyi | 12 +- mypy/typeshed/stdlib/genericpath.pyi | 4 +- mypy/typeshed/stdlib/gettext.pyi | 26 +- mypy/typeshed/stdlib/grp.pyi | 3 +- mypy/typeshed/stdlib/gzip.pyi | 19 +- mypy/typeshed/stdlib/hashlib.pyi | 15 +- mypy/typeshed/stdlib/heapq.pyi | 3 +- mypy/typeshed/stdlib/hmac.pyi | 25 +- mypy/typeshed/stdlib/http/__init__.pyi | 5 +- mypy/typeshed/stdlib/http/cookiejar.pyi | 58 +- mypy/typeshed/stdlib/http/server.pyi | 2 +- mypy/typeshed/stdlib/imaplib.pyi | 4 +- mypy/typeshed/stdlib/importlib/abc.pyi | 3 +- mypy/typeshed/stdlib/importlib/machinery.pyi | 10 +- mypy/typeshed/stdlib/importlib/readers.pyi | 4 +- .../stdlib/importlib/resources/simple.pyi | 4 +- mypy/typeshed/stdlib/inspect.pyi | 77 +- mypy/typeshed/stdlib/io.pyi | 11 +- mypy/typeshed/stdlib/ipaddress.pyi | 4 +- mypy/typeshed/stdlib/itertools.pyi | 16 +- mypy/typeshed/stdlib/keyword.pyi | 2 +- mypy/typeshed/stdlib/lib2to3/fixer_base.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_apply.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_asserts.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_basestring.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_buffer.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_dict.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_except.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_exec.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_execfile.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_exitfunc.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_filter.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_funcattrs.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_future.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_getcwdu.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_has_key.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_idioms.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_import.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_imports.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_input.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_intern.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_isinstance.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_itertools.pyi | 3 +- .../lib2to3/fixes/fix_itertools_imports.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_long.pyi | 3 +- .../typeshed/stdlib/lib2to3/fixes/fix_map.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_metaclass.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_methodattrs.pyi | 3 +- mypy/typeshed/stdlib/lib2to3/fixes/fix_ne.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_next.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_nonzero.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_numliterals.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_operator.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_paren.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_print.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_raise.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_raw_input.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_reduce.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_reload.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_renames.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_repr.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_set_literal.pyi | 3 +- .../lib2to3/fixes/fix_standarderror.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_sys_exc.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_throw.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_tuple_params.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_types.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_unicode.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_urllib.pyi | 2 +- .../stdlib/lib2to3/fixes/fix_ws_comma.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_xrange.pyi | 3 +- .../stdlib/lib2to3/fixes/fix_xreadlines.pyi | 3 +- .../typeshed/stdlib/lib2to3/fixes/fix_zip.pyi | 3 +- mypy/typeshed/stdlib/lib2to3/main.pyi | 3 +- mypy/typeshed/stdlib/lib2to3/pygram.pyi | 5 +- mypy/typeshed/stdlib/lib2to3/pytree.pyi | 3 +- mypy/typeshed/stdlib/lib2to3/refactor.pyi | 3 +- mypy/typeshed/stdlib/logging/__init__.pyi | 622 +++++----------- mypy/typeshed/stdlib/logging/config.pyi | 17 +- mypy/typeshed/stdlib/lzma.pyi | 4 +- mypy/typeshed/stdlib/macpath.pyi | 104 --- mypy/typeshed/stdlib/mailbox.pyi | 4 +- mypy/typeshed/stdlib/math.pyi | 52 +- mypy/typeshed/stdlib/mimetypes.pyi | 14 +- mypy/typeshed/stdlib/mmap.pyi | 52 +- mypy/typeshed/stdlib/modulefinder.pyi | 24 +- mypy/typeshed/stdlib/msilib/__init__.pyi | 3 +- mypy/typeshed/stdlib/msvcrt.pyi | 2 +- .../stdlib/multiprocessing/__init__.pyi | 14 +- .../stdlib/multiprocessing/connection.pyi | 4 +- .../stdlib/multiprocessing/context.pyi | 17 +- .../stdlib/multiprocessing/dummy/__init__.pyi | 3 +- .../stdlib/multiprocessing/managers.pyi | 27 +- mypy/typeshed/stdlib/multiprocessing/pool.pyi | 64 +- .../stdlib/multiprocessing/process.pyi | 10 +- .../stdlib/multiprocessing/reduction.pyi | 13 +- .../stdlib/multiprocessing/sharedctypes.pyi | 3 +- mypy/typeshed/stdlib/nntplib.pyi | 4 +- mypy/typeshed/stdlib/ntpath.pyi | 4 +- mypy/typeshed/stdlib/numbers.pyi | 81 +-- mypy/typeshed/stdlib/opcode.pyi | 8 +- mypy/typeshed/stdlib/os/__init__.pyi | 149 ++-- mypy/typeshed/stdlib/ossaudiodev.pyi | 3 +- mypy/typeshed/stdlib/parser.pyi | 3 +- mypy/typeshed/stdlib/pathlib.pyi | 20 +- mypy/typeshed/stdlib/pickle.pyi | 144 ++-- mypy/typeshed/stdlib/platform.pyi | 33 +- mypy/typeshed/stdlib/plistlib.pyi | 118 +-- mypy/typeshed/stdlib/poplib.pyi | 4 +- mypy/typeshed/stdlib/posix.pyi | 185 +++-- mypy/typeshed/stdlib/posixpath.pyi | 8 +- mypy/typeshed/stdlib/pprint.pyi | 37 +- mypy/typeshed/stdlib/pstats.pyi | 4 +- mypy/typeshed/stdlib/pty.pyi | 3 +- mypy/typeshed/stdlib/pwd.pyi | 3 +- mypy/typeshed/stdlib/py_compile.pyi | 30 +- mypy/typeshed/stdlib/pydoc.pyi | 4 +- mypy/typeshed/stdlib/pyexpat/__init__.pyi | 4 +- mypy/typeshed/stdlib/re.pyi | 4 +- mypy/typeshed/stdlib/resource.pyi | 2 +- mypy/typeshed/stdlib/select.pyi | 4 +- mypy/typeshed/stdlib/shlex.pyi | 11 +- mypy/typeshed/stdlib/shutil.pyi | 63 +- mypy/typeshed/stdlib/signal.pyi | 12 +- mypy/typeshed/stdlib/socket.pyi | 192 +++-- mypy/typeshed/stdlib/spwd.pyi | 3 +- mypy/typeshed/stdlib/sqlite3/dbapi2.pyi | 33 +- mypy/typeshed/stdlib/sre_parse.pyi | 50 +- mypy/typeshed/stdlib/ssl.pyi | 29 +- mypy/typeshed/stdlib/statistics.pyi | 105 ++- mypy/typeshed/stdlib/subprocess.pyi | 20 +- mypy/typeshed/stdlib/sunau.pyi | 4 +- mypy/typeshed/stdlib/symbol.pyi | 14 +- mypy/typeshed/stdlib/symtable.pyi | 15 +- mypy/typeshed/stdlib/sys/__init__.pyi | 41 +- mypy/typeshed/stdlib/sysconfig.pyi | 3 +- mypy/typeshed/stdlib/syslog.pyi | 3 +- mypy/typeshed/stdlib/tarfile.pyi | 120 ++-- mypy/typeshed/stdlib/tempfile.pyi | 450 ++++-------- mypy/typeshed/stdlib/threading.pyi | 27 +- mypy/typeshed/stdlib/time.pyi | 40 +- mypy/typeshed/stdlib/tkinter/__init__.pyi | 54 +- mypy/typeshed/stdlib/tkinter/constants.pyi | 2 +- mypy/typeshed/stdlib/tkinter/filedialog.pyi | 3 +- mypy/typeshed/stdlib/tkinter/font.pyi | 11 +- mypy/typeshed/stdlib/tkinter/tix.pyi | 3 +- mypy/typeshed/stdlib/tkinter/ttk.pyi | 11 +- mypy/typeshed/stdlib/token.pyi | 22 +- mypy/typeshed/stdlib/tokenize.pyi | 15 +- mypy/typeshed/stdlib/traceback.pyi | 7 +- mypy/typeshed/stdlib/tracemalloc.pyi | 4 +- mypy/typeshed/stdlib/types.pyi | 65 +- mypy/typeshed/stdlib/typing.pyi | 129 ++-- mypy/typeshed/stdlib/typing_extensions.pyi | 11 +- mypy/typeshed/stdlib/unicodedata.pyi | 13 +- mypy/typeshed/stdlib/unittest/__init__.pyi | 12 +- mypy/typeshed/stdlib/unittest/case.pyi | 19 +- mypy/typeshed/stdlib/unittest/mock.pyi | 173 ++--- mypy/typeshed/stdlib/urllib/parse.pyi | 4 +- mypy/typeshed/stdlib/urllib/robotparser.pyi | 4 +- mypy/typeshed/stdlib/warnings.pyi | 4 +- mypy/typeshed/stdlib/wave.pyi | 4 +- mypy/typeshed/stdlib/webbrowser.pyi | 2 +- mypy/typeshed/stdlib/winreg.pyi | 4 +- mypy/typeshed/stdlib/winsound.pyi | 3 +- mypy/typeshed/stdlib/xml/dom/minicompat.pyi | 3 +- mypy/typeshed/stdlib/xml/dom/minidom.pyi | 4 +- mypy/typeshed/stdlib/xml/dom/pulldom.pyi | 3 +- mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi | 4 +- .../typeshed/stdlib/xml/etree/ElementTree.pyi | 294 ++++---- mypy/typeshed/stdlib/xml/sax/__init__.pyi | 15 +- mypy/typeshed/stdlib/xmlrpc/client.pyi | 78 +- mypy/typeshed/stdlib/xxlimited.pyi | 3 +- mypy/typeshed/stdlib/zipfile/__init__.pyi | 35 +- mypy/typeshed/stdlib/zipfile/_path.pyi | 4 +- mypy/typeshed/stdlib/zipimport.pyi | 3 +- mypy/typeshed/stdlib/zlib.pyi | 2 +- 260 files changed, 2997 insertions(+), 4598 deletions(-) create mode 100644 mypy/typeshed/stdlib/ctypes/_endian.pyi delete mode 100644 mypy/typeshed/stdlib/macpath.pyi diff --git a/mypy/typeshed/stdlib/VERSIONS b/mypy/typeshed/stdlib/VERSIONS index 5099a94c93bc..da395f797881 100644 --- a/mypy/typeshed/stdlib/VERSIONS +++ b/mypy/typeshed/stdlib/VERSIONS @@ -170,7 +170,6 @@ linecache: 3.0- locale: 3.0- logging: 3.0- lzma: 3.3- -macpath: 3.0-3.7 mailbox: 3.0- mailcap: 3.0-3.12 marshal: 3.0- diff --git a/mypy/typeshed/stdlib/_ast.pyi b/mypy/typeshed/stdlib/_ast.pyi index 0fbf66f7feda..fc3f035cc779 100644 --- a/mypy/typeshed/stdlib/_ast.pyi +++ b/mypy/typeshed/stdlib/_ast.pyi @@ -1,12 +1,10 @@ import sys import typing_extensions -from typing import Any, ClassVar -from typing_extensions import Literal +from typing import Any, ClassVar, Literal PyCF_ONLY_AST: Literal[1024] -if sys.version_info >= (3, 8): - PyCF_TYPE_COMMENTS: Literal[4096] - PyCF_ALLOW_TOP_LEVEL_AWAIT: Literal[8192] +PyCF_TYPE_COMMENTS: Literal[4096] +PyCF_ALLOW_TOP_LEVEL_AWAIT: Literal[8192] _Identifier: typing_extensions.TypeAlias = str @@ -19,33 +17,29 @@ class AST: # TODO: Not all nodes have all of the following attributes lineno: int col_offset: int - if sys.version_info >= (3, 8): - end_lineno: int | None - end_col_offset: int | None - type_comment: str | None + end_lineno: int | None + end_col_offset: int | None + type_comment: str | None class mod(AST): ... +class type_ignore(AST): ... -if sys.version_info >= (3, 8): - class type_ignore(AST): ... - - class TypeIgnore(type_ignore): - if sys.version_info >= (3, 10): - __match_args__ = ("lineno", "tag") - tag: str +class TypeIgnore(type_ignore): + if sys.version_info >= (3, 10): + __match_args__ = ("lineno", "tag") + tag: str - class FunctionType(mod): - if sys.version_info >= (3, 10): - __match_args__ = ("argtypes", "returns") - argtypes: list[expr] - returns: expr +class FunctionType(mod): + if sys.version_info >= (3, 10): + __match_args__ = ("argtypes", "returns") + argtypes: list[expr] + returns: expr class Module(mod): if sys.version_info >= (3, 10): __match_args__ = ("body", "type_ignores") body: list[stmt] - if sys.version_info >= (3, 8): - type_ignores: list[TypeIgnore] + type_ignores: list[TypeIgnore] class Interactive(mod): if sys.version_info >= (3, 10): @@ -340,21 +334,6 @@ class JoinedStr(expr): __match_args__ = ("values",) values: list[expr] -if sys.version_info < (3, 8): - class Num(expr): # Deprecated in 3.8; use Constant - n: int | float | complex - - class Str(expr): # Deprecated in 3.8; use Constant - s: str - - class Bytes(expr): # Deprecated in 3.8; use Constant - s: bytes - - class NameConstant(expr): # Deprecated in 3.8; use Constant - value: Any - - class Ellipsis(expr): ... # Deprecated in 3.8; use Constant - class Constant(expr): if sys.version_info >= (3, 10): __match_args__ = ("value", "kind") @@ -364,12 +343,11 @@ class Constant(expr): s: Any n: int | float | complex -if sys.version_info >= (3, 8): - class NamedExpr(expr): - if sys.version_info >= (3, 10): - __match_args__ = ("target", "value") - target: Name - value: expr +class NamedExpr(expr): + if sys.version_info >= (3, 10): + __match_args__ = ("target", "value") + target: Name + value: expr class Attribute(expr): if sys.version_info >= (3, 10): @@ -498,8 +476,7 @@ class ExceptHandler(excepthandler): class arguments(AST): if sys.version_info >= (3, 10): __match_args__ = ("posonlyargs", "args", "vararg", "kwonlyargs", "kw_defaults", "kwarg", "defaults") - if sys.version_info >= (3, 8): - posonlyargs: list[arg] + posonlyargs: list[arg] args: list[arg] vararg: arg | None kwonlyargs: list[arg] diff --git a/mypy/typeshed/stdlib/_codecs.pyi b/mypy/typeshed/stdlib/_codecs.pyi index f8141d8bad4b..6de4666e0776 100644 --- a/mypy/typeshed/stdlib/_codecs.pyi +++ b/mypy/typeshed/stdlib/_codecs.pyi @@ -2,8 +2,8 @@ import codecs import sys from _typeshed import ReadableBuffer from collections.abc import Callable -from typing import overload -from typing_extensions import Literal, TypeAlias +from typing import Literal, overload +from typing_extensions import TypeAlias # This type is not exposed; it is defined in unicodeobject.c class _EncodingMap: @@ -99,11 +99,6 @@ else: def unicode_escape_decode(__data: str | ReadableBuffer, __errors: str | None = None) -> tuple[str, int]: ... def unicode_escape_encode(__str: str, __errors: str | None = None) -> tuple[bytes, int]: ... - -if sys.version_info < (3, 8): - def unicode_internal_decode(__obj: str | ReadableBuffer, __errors: str | None = None) -> tuple[str, int]: ... - def unicode_internal_encode(__obj: str | ReadableBuffer, __errors: str | None = None) -> tuple[bytes, int]: ... - def utf_16_be_decode(__data: ReadableBuffer, __errors: str | None = None, __final: bool = False) -> tuple[str, int]: ... def utf_16_be_encode(__str: str, __errors: str | None = None) -> tuple[bytes, int]: ... def utf_16_decode(__data: ReadableBuffer, __errors: str | None = None, __final: bool = False) -> tuple[str, int]: ... diff --git a/mypy/typeshed/stdlib/_collections_abc.pyi b/mypy/typeshed/stdlib/_collections_abc.pyi index 8520e9e4ed9b..0aa09967a895 100644 --- a/mypy/typeshed/stdlib/_collections_abc.pyi +++ b/mypy/typeshed/stdlib/_collections_abc.pyi @@ -30,9 +30,9 @@ from typing import ( # noqa: Y022,Y038,Y057 Sized as Sized, TypeVar, ValuesView as ValuesView, + final, runtime_checkable, ) -from typing_extensions import final __all__ = [ "Awaitable", diff --git a/mypy/typeshed/stdlib/_csv.pyi b/mypy/typeshed/stdlib/_csv.pyi index 19ea487e1530..19f2dc9664b1 100644 --- a/mypy/typeshed/stdlib/_csv.pyi +++ b/mypy/typeshed/stdlib/_csv.pyi @@ -1,8 +1,8 @@ import sys from _typeshed import SupportsWrite from collections.abc import Iterable, Iterator -from typing import Any -from typing_extensions import Final, Literal, TypeAlias +from typing import Any, Final, Literal +from typing_extensions import TypeAlias __version__: Final[str] diff --git a/mypy/typeshed/stdlib/_ctypes.pyi b/mypy/typeshed/stdlib/_ctypes.pyi index 0fa041844028..36540172ab95 100644 --- a/mypy/typeshed/stdlib/_ctypes.pyi +++ b/mypy/typeshed/stdlib/_ctypes.pyi @@ -2,7 +2,7 @@ import sys from _typeshed import ReadableBuffer, WriteableBuffer from abc import abstractmethod from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence -from ctypes import CDLL +from ctypes import CDLL, ArgumentError as ArgumentError from typing import Any, ClassVar, Generic, TypeVar, overload from typing_extensions import Self, TypeAlias @@ -167,7 +167,11 @@ class Array(_CData, Generic[_CT]): def _type_(self) -> type[_CT]: ... @_type_.setter def _type_(self, value: type[_CT]) -> None: ... - raw: bytes # Note: only available if _CT == c_char + # Note: only available if _CT == c_char + @property + def raw(self) -> bytes: ... + @raw.setter + def raw(self, value: ReadableBuffer) -> None: ... value: Any # Note: bytes if _CT == c_char, str if _CT == c_wchar, unavailable otherwise # TODO These methods cannot be annotated correctly at the moment. # All of these "Any"s stand for the array's element type, but it's not possible to use _CT @@ -197,8 +201,6 @@ class Array(_CData, Generic[_CT]): if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... -class ArgumentError(Exception): ... - def addressof(obj: _CData) -> int: ... def alignment(obj_or_type: _CData | type[_CData]) -> int: ... def get_errno() -> int: ... diff --git a/mypy/typeshed/stdlib/_curses.pyi b/mypy/typeshed/stdlib/_curses.pyi index 3604f7abedb5..adb09a50f47c 100644 --- a/mypy/typeshed/stdlib/_curses.pyi +++ b/mypy/typeshed/stdlib/_curses.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import ReadOnlyBuffer, SupportsRead -from typing import IO, Any, NamedTuple, overload -from typing_extensions import TypeAlias, final +from typing import IO, Any, NamedTuple, final, overload +from typing_extensions import TypeAlias if sys.platform != "win32": # Handled by PyCurses_ConvertToChtype in _cursesmodule.c. @@ -548,10 +548,10 @@ if sys.platform != "win32": def vline(self, ch: _ChType, n: int) -> None: ... @overload def vline(self, y: int, x: int, ch: _ChType, n: int) -> None: ... - if sys.version_info >= (3, 8): - class _ncurses_version(NamedTuple): - major: int - minor: int - patch: int - ncurses_version: _ncurses_version - window = _CursesWindow # undocumented + + class _ncurses_version(NamedTuple): + major: int + minor: int + patch: int + ncurses_version: _ncurses_version + window = _CursesWindow # undocumented diff --git a/mypy/typeshed/stdlib/_decimal.pyi b/mypy/typeshed/stdlib/_decimal.pyi index 9a90760bd2c2..369d04cd2d5d 100644 --- a/mypy/typeshed/stdlib/_decimal.pyi +++ b/mypy/typeshed/stdlib/_decimal.pyi @@ -2,8 +2,8 @@ import numbers import sys from collections.abc import Container, Sequence from types import TracebackType -from typing import Any, ClassVar, NamedTuple, overload -from typing_extensions import Final, Literal, Self, TypeAlias +from typing import Any, ClassVar, Final, Literal, NamedTuple, overload +from typing_extensions import Self, TypeAlias _Decimal: TypeAlias = Decimal | int _DecimalNew: TypeAlias = Decimal | float | str | tuple[int, Sequence[int], int] diff --git a/mypy/typeshed/stdlib/_dummy_threading.pyi b/mypy/typeshed/stdlib/_dummy_threading.pyi index abcf3a13a496..21d1d1921c0e 100644 --- a/mypy/typeshed/stdlib/_dummy_threading.pyi +++ b/mypy/typeshed/stdlib/_dummy_threading.pyi @@ -1,4 +1,5 @@ import sys +from _thread import _excepthook, _ExceptHookArgs from _typeshed import ProfileFunction, TraceFunction from collections.abc import Callable, Iterable, Mapping from types import TracebackType @@ -28,11 +29,10 @@ __all__ = [ "settrace", "local", "stack_size", + "ExceptHookArgs", + "excepthook", ] -if sys.version_info >= (3, 8): - __all__ += ["ExceptHookArgs", "excepthook"] - def active_count() -> int: ... def current_thread() -> Thread: ... def currentThread() -> Thread: ... @@ -72,10 +72,8 @@ class Thread: def join(self, timeout: float | None = None) -> None: ... def getName(self) -> str: ... def setName(self, name: str) -> None: ... - if sys.version_info >= (3, 8): - @property - def native_id(self) -> int | None: ... # only available on some platforms - + @property + def native_id(self) -> int | None: ... # only available on some platforms def is_alive(self) -> bool: ... if sys.version_info < (3, 9): def isAlive(self) -> bool: ... @@ -138,11 +136,8 @@ class Event: def clear(self) -> None: ... def wait(self, timeout: float | None = None) -> bool: ... -if sys.version_info >= (3, 8): - from _thread import _excepthook, _ExceptHookArgs - - excepthook = _excepthook - ExceptHookArgs = _ExceptHookArgs +excepthook = _excepthook +ExceptHookArgs = _ExceptHookArgs class Timer(Thread): def __init__( diff --git a/mypy/typeshed/stdlib/_heapq.pyi b/mypy/typeshed/stdlib/_heapq.pyi index 8d6c3e88103e..28b03a75d4c7 100644 --- a/mypy/typeshed/stdlib/_heapq.pyi +++ b/mypy/typeshed/stdlib/_heapq.pyi @@ -1,5 +1,4 @@ -from typing import Any, TypeVar -from typing_extensions import Final +from typing import Any, Final, TypeVar _T = TypeVar("_T") diff --git a/mypy/typeshed/stdlib/_json.pyi b/mypy/typeshed/stdlib/_json.pyi index 130f7ab92e97..a6a62be184d8 100644 --- a/mypy/typeshed/stdlib/_json.pyi +++ b/mypy/typeshed/stdlib/_json.pyi @@ -1,6 +1,5 @@ from collections.abc import Callable -from typing import Any -from typing_extensions import final +from typing import Any, final @final class make_encoder: diff --git a/mypy/typeshed/stdlib/_operator.pyi b/mypy/typeshed/stdlib/_operator.pyi index 26e69f130728..acc4a6fb59ca 100644 --- a/mypy/typeshed/stdlib/_operator.pyi +++ b/mypy/typeshed/stdlib/_operator.pyi @@ -1,8 +1,8 @@ import sys from _typeshed import SupportsGetItem from collections.abc import Callable, Container, Iterable, MutableMapping, MutableSequence, Sequence -from typing import Any, AnyStr, Generic, Protocol, SupportsAbs, TypeVar, overload -from typing_extensions import ParamSpec, SupportsIndex, TypeAlias, TypeVarTuple, Unpack, final +from typing import Any, AnyStr, Generic, Protocol, SupportsAbs, SupportsIndex, TypeVar, final, overload +from typing_extensions import ParamSpec, TypeAlias, TypeVarTuple, Unpack _R = TypeVar("_R") _T = TypeVar("_T") diff --git a/mypy/typeshed/stdlib/_osx_support.pyi b/mypy/typeshed/stdlib/_osx_support.pyi index 3eb6f4ddc67c..64dbdd24fd40 100644 --- a/mypy/typeshed/stdlib/_osx_support.pyi +++ b/mypy/typeshed/stdlib/_osx_support.pyi @@ -1,4 +1,3 @@ -import sys from collections.abc import Iterable, Sequence from typing import TypeVar @@ -13,13 +12,7 @@ _COMPILER_CONFIG_VARS: tuple[str, ...] # undocumented _INITPRE: str # undocumented def _find_executable(executable: str, path: str | None = None) -> str | None: ... # undocumented - -if sys.version_info >= (3, 8): - def _read_output(commandstring: str, capture_stderr: bool = False) -> str | None: ... # undocumented - -else: - def _read_output(commandstring: str) -> str | None: ... # undocumented - +def _read_output(commandstring: str, capture_stderr: bool = False) -> str | None: ... # undocumented def _find_build_tool(toolname: str) -> str: ... # undocumented _SYSTEM_VERSION: str | None # undocumented diff --git a/mypy/typeshed/stdlib/_posixsubprocess.pyi b/mypy/typeshed/stdlib/_posixsubprocess.pyi index 1708063720ba..6c1782433e45 100644 --- a/mypy/typeshed/stdlib/_posixsubprocess.pyi +++ b/mypy/typeshed/stdlib/_posixsubprocess.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import StrOrBytesPath from collections.abc import Callable, Sequence -from typing_extensions import SupportsIndex +from typing import SupportsIndex if sys.platform != "win32": def cloexec_pipe() -> tuple[int, int]: ... diff --git a/mypy/typeshed/stdlib/_sitebuiltins.pyi b/mypy/typeshed/stdlib/_sitebuiltins.pyi index 94ad701d4a73..49e88a196825 100644 --- a/mypy/typeshed/stdlib/_sitebuiltins.pyi +++ b/mypy/typeshed/stdlib/_sitebuiltins.pyi @@ -1,6 +1,5 @@ from collections.abc import Iterable -from typing import ClassVar, NoReturn -from typing_extensions import Literal +from typing import ClassVar, Literal, NoReturn class Quitter: name: str diff --git a/mypy/typeshed/stdlib/_socket.pyi b/mypy/typeshed/stdlib/_socket.pyi index 7a0ede62838c..6471cae2e72d 100644 --- a/mypy/typeshed/stdlib/_socket.pyi +++ b/mypy/typeshed/stdlib/_socket.pyi @@ -1,16 +1,9 @@ import sys from _typeshed import ReadableBuffer, WriteableBuffer from collections.abc import Iterable -from typing import Any, SupportsInt, overload +from typing import Any, SupportsIndex, overload from typing_extensions import TypeAlias -if sys.version_info >= (3, 8): - from typing import SupportsIndex - - _FD: TypeAlias = SupportsIndex -else: - _FD: TypeAlias = SupportsInt - _CMSG: TypeAlias = tuple[int, int, bytes] _CMSGArg: TypeAlias = tuple[int, int, ReadableBuffer] @@ -20,19 +13,18 @@ _CMSGArg: TypeAlias = tuple[int, int, ReadableBuffer] _Address: TypeAlias = tuple[Any, ...] | str | ReadableBuffer _RetAddress: TypeAlias = Any -# ----- Constants ----- -# Some socket families are listed in the "Socket families" section of the docs, -# but not the "Constants" section. These are listed at the end of the list of -# constants. -# -# Besides those and the first few constants listed, the constants are listed in -# documentation order. +# ===== Constants ===== +# This matches the order in the CPython documentation +# https://docs.python.org/3/library/socket.html#constants -has_ipv6: bool +if sys.platform != "win32": + AF_UNIX: int AF_INET: int AF_INET6: int +AF_UNSPEC: int + SOCK_STREAM: int SOCK_DGRAM: int SOCK_RAW: int @@ -40,162 +32,29 @@ SOCK_RDM: int SOCK_SEQPACKET: int if sys.platform == "linux": + # Availability: Linux >= 2.6.27 SOCK_CLOEXEC: int SOCK_NONBLOCK: int -# Address families not mentioned in the docs -AF_APPLETALK: int -AF_DECnet: int -AF_IPX: int -AF_SNA: int -AF_UNSPEC: int - -if sys.platform != "win32": - AF_ROUTE: int - AF_SYSTEM: int - AF_UNIX: int - -if sys.platform != "darwin": - AF_IRDA: int - -if sys.platform != "darwin" and sys.platform != "win32": - AF_AAL5: int - AF_ASH: int - AF_ATMPVC: int - AF_ATMSVC: int - AF_AX25: int - AF_BRIDGE: int - AF_ECONET: int - AF_KEY: int - AF_LLC: int - AF_NETBEUI: int - AF_NETROM: int - AF_PPPOX: int - AF_ROSE: int - AF_SECURITY: int - AF_WANPIPE: int - AF_X25: int +# -------------------- +# Many constants of these forms, documented in the Unix documentation on +# sockets and/or the IP protocol, are also defined in the socket module. +# SO_* +# socket.SOMAXCONN +# MSG_* +# SOL_* +# SCM_* +# IPPROTO_* +# IPPORT_* +# INADDR_* +# IP_* +# IPV6_* +# EAI_* +# AI_* +# NI_* +# TCP_* +# -------------------- -# The "many constants" referenced by the docs -SOMAXCONN: int -AI_ADDRCONFIG: int -AI_ALL: int -AI_CANONNAME: int -AI_NUMERICHOST: int -AI_NUMERICSERV: int -AI_PASSIVE: int -AI_V4MAPPED: int -EAI_AGAIN: int -EAI_BADFLAGS: int -EAI_FAIL: int -EAI_FAMILY: int -EAI_MEMORY: int -EAI_NODATA: int -EAI_NONAME: int -EAI_SERVICE: int -EAI_SOCKTYPE: int -INADDR_ALLHOSTS_GROUP: int -INADDR_ANY: int -INADDR_BROADCAST: int -INADDR_LOOPBACK: int -INADDR_MAX_LOCAL_GROUP: int -INADDR_NONE: int -INADDR_UNSPEC_GROUP: int -IPPORT_RESERVED: int -IPPORT_USERRESERVED: int - -if sys.platform != "win32" or sys.version_info >= (3, 8): - IPPROTO_AH: int - IPPROTO_DSTOPTS: int - IPPROTO_EGP: int - IPPROTO_ESP: int - IPPROTO_FRAGMENT: int - IPPROTO_GGP: int - IPPROTO_HOPOPTS: int - IPPROTO_ICMPV6: int - IPPROTO_IDP: int - IPPROTO_IGMP: int - IPPROTO_IPV4: int - IPPROTO_IPV6: int - IPPROTO_MAX: int - IPPROTO_ND: int - IPPROTO_NONE: int - IPPROTO_PIM: int - IPPROTO_PUP: int - IPPROTO_ROUTING: int - IPPROTO_SCTP: int - - if sys.platform != "darwin": - IPPROTO_CBT: int - IPPROTO_ICLFXBM: int - IPPROTO_IGP: int - IPPROTO_L2TP: int - IPPROTO_PGM: int - IPPROTO_RDP: int - IPPROTO_ST: int - -IPPROTO_ICMP: int -IPPROTO_IP: int -IPPROTO_RAW: int -IPPROTO_TCP: int -IPPROTO_UDP: int -IPV6_CHECKSUM: int -IPV6_JOIN_GROUP: int -IPV6_LEAVE_GROUP: int -IPV6_MULTICAST_HOPS: int -IPV6_MULTICAST_IF: int -IPV6_MULTICAST_LOOP: int -IPV6_RECVTCLASS: int -IPV6_TCLASS: int -IPV6_UNICAST_HOPS: int -IPV6_V6ONLY: int - -if sys.platform != "darwin" or sys.version_info >= (3, 9): - IPV6_DONTFRAG: int - IPV6_HOPLIMIT: int - IPV6_HOPOPTS: int - IPV6_PKTINFO: int - IPV6_RECVRTHDR: int - IPV6_RTHDR: int - -IP_ADD_MEMBERSHIP: int -IP_DROP_MEMBERSHIP: int -IP_HDRINCL: int -IP_MULTICAST_IF: int -IP_MULTICAST_LOOP: int -IP_MULTICAST_TTL: int -IP_OPTIONS: int -IP_RECVDSTADDR: int -if sys.version_info >= (3, 10): - IP_RECVTOS: int -elif sys.platform != "win32" and sys.platform != "darwin": - IP_RECVTOS: int -IP_TOS: int -IP_TTL: int -MSG_CTRUNC: int -MSG_DONTROUTE: int - -if sys.platform != "darwin": - MSG_ERRQUEUE: int - -MSG_OOB: int -MSG_PEEK: int -MSG_TRUNC: int -MSG_WAITALL: int -NI_DGRAM: int -NI_MAXHOST: int -NI_MAXSERV: int -NI_NAMEREQD: int -NI_NOFQDN: int -NI_NUMERICHOST: int -NI_NUMERICSERV: int -SHUT_RD: int -SHUT_RDWR: int -SHUT_WR: int -SOL_IP: int -SOL_SOCKET: int -SOL_TCP: int -SOL_UDP: int SO_ACCEPTCONN: int SO_BROADCAST: int SO_DEBUG: int @@ -213,39 +72,99 @@ SO_SNDLOWAT: int SO_SNDTIMEO: int SO_TYPE: int SO_USELOOPBACK: int -if sys.platform == "linux" and sys.version_info >= (3, 11): - SO_INCOMING_CPU: int -TCP_FASTOPEN: int -TCP_KEEPCNT: int -TCP_KEEPINTVL: int +if sys.platform == "win32": + SO_EXCLUSIVEADDRUSE: int +if sys.platform != "win32": + SO_REUSEPORT: int +if sys.platform != "win32" and sys.platform != "darwin": + SO_BINDTODEVICE: int + SO_DOMAIN: int + SO_MARK: int + SO_PASSCRED: int + SO_PASSSEC: int + SO_PEERCRED: int + SO_PEERSEC: int + SO_PRIORITY: int + SO_PROTOCOL: int + SO_SETFIB: int -if sys.platform != "darwin": - TCP_KEEPIDLE: int +SOMAXCONN: int -TCP_MAXSEG: int -TCP_NODELAY: int +MSG_CTRUNC: int +MSG_DONTROUTE: int +MSG_OOB: int +MSG_PEEK: int +MSG_TRUNC: int +MSG_WAITALL: int if sys.platform != "win32": - TCP_NOTSENT_LOWAT: int -if sys.version_info >= (3, 10) and sys.platform == "darwin": - TCP_KEEPALIVE: int -if sys.version_info >= (3, 11) and sys.platform == "darwin": - TCP_CONNECTION_INFO: int - + MSG_DONTWAIT: int + MSG_EOF: int + MSG_EOR: int + MSG_NOSIGNAL: int # Sometimes this exists on darwin, sometimes not if sys.platform != "darwin": MSG_BCAST: int + MSG_ERRQUEUE: int MSG_MCAST: int - SO_EXCLUSIVEADDRUSE: int +if sys.platform != "win32" and sys.platform != "darwin": + MSG_BTAG: int + MSG_CMSG_CLOEXEC: int + MSG_CONFIRM: int + MSG_ETAG: int + MSG_FASTOPEN: int + MSG_MORE: int + MSG_NOTIFICATION: int + +SOL_IP: int +SOL_SOCKET: int +SOL_TCP: int +SOL_UDP: int +if sys.platform != "win32" and sys.platform != "darwin": + SOL_ATALK: int + SOL_AX25: int + SOL_HCI: int + SOL_IPX: int + SOL_NETROM: int + SOL_ROSE: int if sys.platform != "win32": - AI_DEFAULT: int - AI_MASK: int - AI_V4MAPPED_CFG: int - EAI_ADDRFAMILY: int - EAI_BADHINTS: int - EAI_MAX: int - EAI_OVERFLOW: int - EAI_PROTOCOL: int - EAI_SYSTEM: int + SCM_CREDS: int + SCM_RIGHTS: int +if sys.platform != "win32" and sys.platform != "darwin": + SCM_CREDENTIALS: int + +IPPROTO_ICMP: int +IPPROTO_IP: int +IPPROTO_RAW: int +IPPROTO_TCP: int +IPPROTO_UDP: int +IPPROTO_AH: int +IPPROTO_DSTOPTS: int +IPPROTO_EGP: int +IPPROTO_ESP: int +IPPROTO_FRAGMENT: int +IPPROTO_GGP: int +IPPROTO_HOPOPTS: int +IPPROTO_ICMPV6: int +IPPROTO_IDP: int +IPPROTO_IGMP: int +IPPROTO_IPV4: int +IPPROTO_IPV6: int +IPPROTO_MAX: int +IPPROTO_ND: int +IPPROTO_NONE: int +IPPROTO_PIM: int +IPPROTO_PUP: int +IPPROTO_ROUTING: int +IPPROTO_SCTP: int +if sys.platform != "darwin": + IPPROTO_CBT: int + IPPROTO_ICLFXBM: int + IPPROTO_IGP: int + IPPROTO_L2TP: int + IPPROTO_PGM: int + IPPROTO_RDP: int + IPPROTO_ST: int +if sys.platform != "win32": IPPROTO_EON: int IPPROTO_GRE: int IPPROTO_HELLO: int @@ -254,24 +173,78 @@ if sys.platform != "win32": IPPROTO_RSVP: int IPPROTO_TP: int IPPROTO_XTP: int - IPV6_RTHDR_TYPE_0: int +if sys.platform != "win32" and sys.platform != "darwin": + IPPROTO_BIP: int + IPPROTO_MOBILE: int + IPPROTO_VRRP: int +if sys.version_info >= (3, 9) and sys.platform == "linux": + # Availability: Linux >= 2.6.20, FreeBSD >= 10.1 + IPPROTO_UDPLITE: int +if sys.version_info >= (3, 10) and sys.platform == "linux": + IPPROTO_MPTCP: int + +IPPORT_RESERVED: int +IPPORT_USERRESERVED: int + +INADDR_ALLHOSTS_GROUP: int +INADDR_ANY: int +INADDR_BROADCAST: int +INADDR_LOOPBACK: int +INADDR_MAX_LOCAL_GROUP: int +INADDR_NONE: int +INADDR_UNSPEC_GROUP: int + +IP_ADD_MEMBERSHIP: int +IP_DROP_MEMBERSHIP: int +IP_HDRINCL: int +IP_MULTICAST_IF: int +IP_MULTICAST_LOOP: int +IP_MULTICAST_TTL: int +IP_OPTIONS: int +IP_RECVDSTADDR: int +if sys.version_info >= (3, 10): + IP_RECVTOS: int +elif sys.platform != "win32" and sys.platform != "darwin": + IP_RECVTOS: int +IP_TOS: int +IP_TTL: int +if sys.platform != "win32": IP_DEFAULT_MULTICAST_LOOP: int IP_DEFAULT_MULTICAST_TTL: int IP_MAX_MEMBERSHIPS: int IP_RECVOPTS: int IP_RECVRETOPTS: int IP_RETOPTS: int - LOCAL_PEERCRED: int - MSG_DONTWAIT: int - MSG_EOF: int - MSG_EOR: int - MSG_NOSIGNAL: int # Sometimes this exists on darwin, sometimes not - SCM_CREDS: int - SCM_RIGHTS: int - SO_REUSEPORT: int +if sys.platform != "win32" and sys.platform != "darwin": + IP_TRANSPARENT: int + IP_BIND_ADDRESS_NO_PORT: int +if sys.version_info >= (3, 12): + IP_ADD_SOURCE_MEMBERSHIP: int + IP_BLOCK_SOURCE: int + IP_DROP_SOURCE_MEMBERSHIP: int + IP_PKTINFO: int + IP_UNBLOCK_SOURCE: int +IPV6_CHECKSUM: int +IPV6_JOIN_GROUP: int +IPV6_LEAVE_GROUP: int +IPV6_MULTICAST_HOPS: int +IPV6_MULTICAST_IF: int +IPV6_MULTICAST_LOOP: int +IPV6_RECVTCLASS: int +IPV6_TCLASS: int +IPV6_UNICAST_HOPS: int +IPV6_V6ONLY: int +if sys.version_info >= (3, 9) or sys.platform != "darwin": + IPV6_DONTFRAG: int + IPV6_HOPLIMIT: int + IPV6_HOPOPTS: int + IPV6_PKTINFO: int + IPV6_RECVRTHDR: int + IPV6_RTHDR: int if sys.platform != "win32": - if sys.platform != "darwin" or sys.version_info >= (3, 9): + IPV6_RTHDR_TYPE_0: int + if sys.version_info >= (3, 9) or sys.platform != "darwin": IPV6_DSTOPTS: int IPV6_NEXTHOP: int IPV6_PATHMTU: int @@ -283,43 +256,74 @@ if sys.platform != "win32": IPV6_RTHDRDSTOPTS: int IPV6_USE_MIN_MTU: int +EAI_AGAIN: int +EAI_BADFLAGS: int +EAI_FAIL: int +EAI_FAMILY: int +EAI_MEMORY: int +EAI_NODATA: int +EAI_NONAME: int +EAI_SERVICE: int +EAI_SOCKTYPE: int +if sys.platform != "win32": + EAI_ADDRFAMILY: int + EAI_BADHINTS: int + EAI_MAX: int + EAI_OVERFLOW: int + EAI_PROTOCOL: int + EAI_SYSTEM: int + +AI_ADDRCONFIG: int +AI_ALL: int +AI_CANONNAME: int +AI_NUMERICHOST: int +AI_NUMERICSERV: int +AI_PASSIVE: int +AI_V4MAPPED: int +if sys.platform != "win32": + AI_DEFAULT: int + AI_MASK: int + AI_V4MAPPED_CFG: int + +NI_DGRAM: int +NI_MAXHOST: int +NI_MAXSERV: int +NI_NAMEREQD: int +NI_NOFQDN: int +NI_NUMERICHOST: int +NI_NUMERICSERV: int + +TCP_FASTOPEN: int +TCP_KEEPCNT: int +TCP_KEEPINTVL: int +TCP_MAXSEG: int +TCP_NODELAY: int +if sys.platform != "win32": + TCP_NOTSENT_LOWAT: int +if sys.platform != "darwin": + TCP_KEEPIDLE: int +if sys.version_info >= (3, 10) and sys.platform == "darwin": + TCP_KEEPALIVE: int +if sys.version_info >= (3, 11) and sys.platform == "darwin": + TCP_CONNECTION_INFO: int + if sys.platform != "win32" and sys.platform != "darwin": - IPPROTO_BIP: int - IPPROTO_MOBILE: int - IPPROTO_VRRP: int - IPX_TYPE: int - IP_TRANSPARENT: int - MSG_BTAG: int - MSG_CMSG_CLOEXEC: int - MSG_CONFIRM: int - MSG_ETAG: int - MSG_FASTOPEN: int - MSG_MORE: int - MSG_NOTIFICATION: int - SCM_CREDENTIALS: int - SOL_ATALK: int - SOL_AX25: int - SOL_HCI: int - SOL_IPX: int - SOL_NETROM: int - SOL_ROSE: int - SO_BINDTODEVICE: int - SO_MARK: int - SO_PASSCRED: int - SO_PEERCRED: int - SO_PRIORITY: int - SO_SETFIB: int + TCP_CONGESTION: int TCP_CORK: int TCP_DEFER_ACCEPT: int TCP_INFO: int TCP_LINGER2: int TCP_QUICKACK: int TCP_SYNCNT: int + TCP_USER_TIMEOUT: int TCP_WINDOW_CLAMP: int -# Specifically-documented constants +# -------------------- +# Specifically documented constants +# -------------------- if sys.platform == "linux": + # Availability: Linux >= 2.6.25, NetBSD >= 8 AF_CAN: int PF_CAN: int SOL_CAN_BASE: int @@ -336,6 +340,8 @@ if sys.platform == "linux": CAN_RTR_FLAG: int CAN_SFF_MASK: int +if sys.platform == "linux": + # Availability: Linux >= 2.6.25 CAN_BCM: int CAN_BCM_TX_SETUP: int CAN_BCM_TX_DELETE: int @@ -349,10 +355,6 @@ if sys.platform == "linux": CAN_BCM_RX_STATUS: int CAN_BCM_RX_TIMEOUT: int CAN_BCM_RX_CHANGED: int - - CAN_RAW_FD_FRAMES: int - -if sys.platform == "linux" and sys.version_info >= (3, 8): CAN_BCM_SETTIMER: int CAN_BCM_STARTTIMER: int CAN_BCM_TX_COUNTEVT: int @@ -367,11 +369,20 @@ if sys.platform == "linux" and sys.version_info >= (3, 8): CAN_BCM_CAN_FD_FRAME: int if sys.platform == "linux": + # Availability: Linux >= 3.6 + CAN_RAW_FD_FRAMES: int + +if sys.platform == "linux" and sys.version_info >= (3, 9): + # Availability: Linux >= 4.1 + CAN_RAW_JOIN_FILTERS: int + +if sys.platform == "linux": + # Availability: Linux >= 2.6.25 CAN_ISOTP: int if sys.platform == "linux" and sys.version_info >= (3, 9): + # Availability: Linux >= 5.4 CAN_J1939: int - CAN_RAW_JOIN_FILTERS: int J1939_MAX_UNICAST_ADDR: int J1939_IDLE_ADDR: int @@ -396,16 +407,17 @@ if sys.platform == "linux" and sys.version_info >= (3, 9): J1939_NLA_PAD: int J1939_NLA_BYTES_ACKED: int - J1939_EE_INFO_NONE: int J1939_EE_INFO_TX_ABORT: int - J1939_FILTER_MAX: int -if sys.platform == "linux" and sys.version_info >= (3, 10): - IPPROTO_MPTCP: int +if sys.version_info >= (3, 12) and sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darwin": + # Availability: FreeBSD >= 14.0 + AF_DIVERT: int + PF_DIVERT: int if sys.platform == "linux": + # Availability: Linux >= 2.2 AF_PACKET: int PF_PACKET: int PACKET_BROADCAST: int @@ -416,7 +428,11 @@ if sys.platform == "linux": PACKET_OTHERHOST: int PACKET_OUTGOING: int +if sys.version_info >= (3, 12) and sys.platform == "linux": + ETH_P_ALL: int + if sys.platform == "linux": + # Availability: Linux >= 2.6.30 AF_RDS: int PF_RDS: int SOL_RDS: int @@ -476,6 +492,7 @@ if sys.platform == "linux": TIPC_ZONE_SCOPE: int if sys.platform == "linux": + # Availability: Linux >= 2.6.38 AF_ALG: int SOL_ALG: int ALG_OP_DECRYPT: int @@ -490,6 +507,7 @@ if sys.platform == "linux": ALG_SET_PUBKEY: int if sys.platform == "linux": + # Availability: Linux >= 4.8 (or maybe 3.9, CPython docs are confusing) AF_VSOCK: int IOCTL_VM_SOCKETS_GET_LOCAL_CID: int VMADDR_CID_ANY: int @@ -498,26 +516,65 @@ if sys.platform == "linux": SO_VM_SOCKETS_BUFFER_MAX_SIZE: int SO_VM_SOCKETS_BUFFER_SIZE: int SO_VM_SOCKETS_BUFFER_MIN_SIZE: int - VM_SOCKETS_INVALID_VERSION: int + VM_SOCKETS_INVALID_VERSION: int # undocumented if sys.platform != "win32" or sys.version_info >= (3, 9): + # Documented as only available on BSD, macOS, but empirically sometimes + # available on Windows AF_LINK: int -# BDADDR_* and HCI_* listed with other bluetooth constants below +has_ipv6: bool + +if sys.platform != "darwin": + if sys.platform != "win32" or sys.version_info >= (3, 9): + BDADDR_ANY: str + BDADDR_LOCAL: str if sys.platform != "win32" and sys.platform != "darwin": - SO_DOMAIN: int - SO_PASSSEC: int - SO_PEERSEC: int - SO_PROTOCOL: int - TCP_CONGESTION: int - TCP_USER_TIMEOUT: int + HCI_FILTER: int # not in NetBSD or DragonFlyBSD + HCI_TIME_STAMP: int # not in FreeBSD, NetBSD, or DragonFlyBSD + HCI_DATA_DIR: int # not in FreeBSD, NetBSD, or DragonFlyBSD + +if sys.platform == "linux": + AF_QIPCRTR: int # Availability: Linux >= 4.7 + +if sys.version_info >= (3, 11) and sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darwin": + # FreeBSD + SCM_CREDS2: int + LOCAL_CREDS: int + LOCAL_CREDS_PERSISTENT: int + +if sys.version_info >= (3, 11) and sys.platform == "linux": + SO_INCOMING_CPU: int # Availability: Linux >= 3.9 + +if sys.version_info >= (3, 12) and sys.platform == "win32": + # Availability: Windows + AF_HYPERV: int + HV_PROTOCOL_RAW: int + HVSOCKET_CONNECT_TIMEOUT: int + HVSOCKET_CONNECT_TIMEOUT_MAX: int + HVSOCKET_CONNECTED_SUSPEND: int + HVSOCKET_ADDRESS_FLAG_PASSTHRU: int + HV_GUID_ZERO: str + HV_GUID_WILDCARD: str + HV_GUID_BROADCAST: str + HV_GUID_CHILDREN: str + HV_GUID_LOOPBACK: str + HV_GUID_PARENT: str -if sys.platform == "linux" and sys.version_info >= (3, 8): - AF_QIPCRTR: int +if sys.version_info >= (3, 12): + if sys.platform != "win32": + # Availability: Linux, FreeBSD, macOS + ETHERTYPE_ARP: int + ETHERTYPE_IP: int + ETHERTYPE_IPV6: int + ETHERTYPE_VLAN: int +# -------------------- # Semi-documented constants -# (Listed under "Socket families" in the docs, but not "Constants") +# These are alluded to under the "Socket families" section in the docs +# https://docs.python.org/3/library/socket.html#socket-families +# -------------------- if sys.platform == "linux": # Netlink is defined by Linux @@ -537,12 +594,13 @@ if sys.platform == "linux": NETLINK_W1: int NETLINK_XFRM: int +if sys.platform == "darwin": + PF_SYSTEM: int + SYSPROTO_CONTROL: int + if sys.platform != "darwin": - if sys.platform != "win32" or sys.version_info >= (3, 9): + if sys.version_info >= (3, 9) or sys.platform != "win32": AF_BLUETOOTH: int - BDADDR_ANY: str - BDADDR_LOCAL: str - BTPROTO_RFCOMM: int if sys.platform != "win32" and sys.platform != "darwin": # Linux and some BSD support is explicit in the docs @@ -550,17 +608,65 @@ if sys.platform != "win32" and sys.platform != "darwin": BTPROTO_HCI: int BTPROTO_L2CAP: int BTPROTO_SCO: int # not in FreeBSD - HCI_FILTER: int # not in NetBSD or DragonFlyBSD - # not in FreeBSD, NetBSD, or DragonFlyBSD - HCI_TIME_STAMP: int - HCI_DATA_DIR: int +if sys.platform != "darwin": + if sys.version_info >= (3, 9) or sys.platform != "win32": + BTPROTO_RFCOMM: int -if sys.platform == "darwin": - # PF_SYSTEM is defined by macOS - PF_SYSTEM: int - SYSPROTO_CONTROL: int +if sys.version_info >= (3, 9) and sys.platform == "linux": + UDPLITE_RECV_CSCOV: int + UDPLITE_SEND_CSCOV: int + +# -------------------- +# Documented under socket.shutdown +# -------------------- +SHUT_RD: int +SHUT_RDWR: int +SHUT_WR: int -# ----- Exceptions ----- +# -------------------- +# Undocumented constants +# -------------------- + +# Undocumented address families +AF_APPLETALK: int +AF_DECnet: int +AF_IPX: int +AF_SNA: int + +if sys.platform != "win32": + AF_ROUTE: int + AF_SYSTEM: int + +if sys.platform != "darwin": + AF_IRDA: int + +if sys.platform != "win32" and sys.platform != "darwin": + AF_AAL5: int + AF_ASH: int + AF_ATMPVC: int + AF_ATMSVC: int + AF_AX25: int + AF_BRIDGE: int + AF_ECONET: int + AF_KEY: int + AF_LLC: int + AF_NETBEUI: int + AF_NETROM: int + AF_PPPOX: int + AF_ROSE: int + AF_SECURITY: int + AF_WANPIPE: int + AF_X25: int + +# Miscellaneous undocumented + +if sys.platform != "win32": + LOCAL_PEERCRED: int + +if sys.platform != "win32" and sys.platform != "darwin": + IPX_TYPE: int + +# ===== Exceptions ===== error = OSError @@ -572,7 +678,7 @@ if sys.version_info >= (3, 10): else: class timeout(error): ... -# ----- Classes ----- +# ===== Classes ===== class socket: @property @@ -584,9 +690,11 @@ class socket: @property def timeout(self) -> float | None: ... if sys.platform == "win32": - def __init__(self, family: int = ..., type: int = ..., proto: int = ..., fileno: _FD | bytes | None = ...) -> None: ... + def __init__( + self, family: int = ..., type: int = ..., proto: int = ..., fileno: SupportsIndex | bytes | None = ... + ) -> None: ... else: - def __init__(self, family: int = ..., type: int = ..., proto: int = ..., fileno: _FD | None = ...) -> None: ... + def __init__(self, family: int = ..., type: int = ..., proto: int = ..., fileno: SupportsIndex | None = ...) -> None: ... def bind(self, __address: _Address) -> None: ... def close(self) -> None: ... @@ -648,10 +756,10 @@ class socket: SocketType = socket -# ----- Functions ----- +# ===== Functions ===== -def close(__fd: _FD) -> None: ... -def dup(__fd: _FD) -> int: ... +def close(__fd: SupportsIndex) -> None: ... +def dup(__fd: SupportsIndex) -> int: ... # the 5th tuple item is an address def getaddrinfo( @@ -687,33 +795,8 @@ if sys.platform != "win32": def CMSG_SPACE(__length: int) -> int: ... def socketpair(__family: int = ..., __type: int = ..., __proto: int = ...) -> tuple[socket, socket]: ... -# Windows added these in 3.8, but didn't have them before -if sys.platform != "win32" or sys.version_info >= (3, 8): - def if_nameindex() -> list[tuple[int, str]]: ... - def if_nametoindex(__name: str) -> int: ... - def if_indextoname(__index: int) -> str: ... +def if_nameindex() -> list[tuple[int, str]]: ... +def if_nametoindex(__name: str) -> int: ... +def if_indextoname(__index: int) -> str: ... -if sys.version_info >= (3, 12): - IP_PKTINFO: int - IP_UNBLOCK_SOURCE: int - IP_BLOCK_SOURCE: int - IP_ADD_SOURCE_MEMBERSHIP: int - IP_DROP_SOURCE_MEMBERSHIP: int - if sys.platform == "win32": - AF_HYPERV: int - HV_PROTOCOL_RAW: int - HVSOCKET_CONNECT_TIMEOUT: int - HVSOCKET_CONNECT_TIMEOUT_MAX: int - HVSOCKET_CONNECTED_SUSPEND: int - HVSOCKET_ADDRESS_FLAG_PASSTHRU: int - HV_GUID_ZERO: str - HV_GUID_WILDCARD: str - HV_GUID_BROADCAST: str - HV_GUID_CHILDREN: str - HV_GUID_LOOPBACK: str - HV_GUID_PARENT: str - else: - ETHERTYPE_ARP: int - ETHERTYPE_IP: int - ETHERTYPE_IPV6: int - ETHERTYPE_VLAN: int +CAPI: object diff --git a/mypy/typeshed/stdlib/_stat.pyi b/mypy/typeshed/stdlib/_stat.pyi index 83d832e4dd8e..347897404edc 100644 --- a/mypy/typeshed/stdlib/_stat.pyi +++ b/mypy/typeshed/stdlib/_stat.pyi @@ -1,5 +1,5 @@ import sys -from typing_extensions import Literal +from typing import Literal SF_APPEND: Literal[0x00040000] SF_ARCHIVED: Literal[0x00010000] @@ -78,7 +78,7 @@ def S_ISSOCK(mode: int) -> bool: ... def S_ISWHT(mode: int) -> bool: ... def filemode(mode: int) -> str: ... -if sys.platform == "win32" and sys.version_info >= (3, 8): +if sys.platform == "win32": IO_REPARSE_TAG_SYMLINK: int IO_REPARSE_TAG_MOUNT_POINT: int IO_REPARSE_TAG_APPEXECLINK: int diff --git a/mypy/typeshed/stdlib/_thread.pyi b/mypy/typeshed/stdlib/_thread.pyi index 8bd0b179607b..8b43a81cac8a 100644 --- a/mypy/typeshed/stdlib/_thread.pyi +++ b/mypy/typeshed/stdlib/_thread.pyi @@ -3,8 +3,7 @@ from _typeshed import structseq from collections.abc import Callable from threading import Thread from types import TracebackType -from typing import Any, NoReturn -from typing_extensions import Final, final +from typing import Any, Final, NoReturn, final error = RuntimeError @@ -28,21 +27,21 @@ def stack_size(size: int = ...) -> int: ... TIMEOUT_MAX: float -if sys.version_info >= (3, 8): - def get_native_id() -> int: ... # only available on some platforms - @final - class _ExceptHookArgs(structseq[Any], tuple[type[BaseException], BaseException | None, TracebackType | None, Thread | None]): - if sys.version_info >= (3, 10): - __match_args__: Final = ("exc_type", "exc_value", "exc_traceback", "thread") - @property - def exc_type(self) -> type[BaseException]: ... - @property - def exc_value(self) -> BaseException | None: ... - @property - def exc_traceback(self) -> TracebackType | None: ... - @property - def thread(self) -> Thread | None: ... - _excepthook: Callable[[_ExceptHookArgs], Any] +def get_native_id() -> int: ... # only available on some platforms +@final +class _ExceptHookArgs(structseq[Any], tuple[type[BaseException], BaseException | None, TracebackType | None, Thread | None]): + if sys.version_info >= (3, 10): + __match_args__: Final = ("exc_type", "exc_value", "exc_traceback", "thread") + @property + def exc_type(self) -> type[BaseException]: ... + @property + def exc_value(self) -> BaseException | None: ... + @property + def exc_traceback(self) -> TracebackType | None: ... + @property + def thread(self) -> Thread | None: ... + +_excepthook: Callable[[_ExceptHookArgs], Any] if sys.version_info >= (3, 12): def daemon_threads_allowed() -> bool: ... diff --git a/mypy/typeshed/stdlib/_tkinter.pyi b/mypy/typeshed/stdlib/_tkinter.pyi index 89610e21d9e7..67e7e3f696e2 100644 --- a/mypy/typeshed/stdlib/_tkinter.pyi +++ b/mypy/typeshed/stdlib/_tkinter.pyi @@ -1,6 +1,5 @@ import sys -from typing import Any, ClassVar -from typing_extensions import Literal, final +from typing import Any, ClassVar, Literal, final # _tkinter is meant to be only used internally by tkinter, but some tkinter # functions e.g. return _tkinter.Tcl_Obj objects. Tcl_Obj represents a Tcl @@ -107,29 +106,15 @@ TK_VERSION: str class TkttType: def deletetimerhandler(self): ... -if sys.version_info >= (3, 8): - def create( - __screenName: str | None = None, - __baseName: str = "", - __className: str = "Tk", - __interactive: bool = False, - __wantobjects: bool = False, - __wantTk: bool = True, - __sync: bool = False, - __use: str | None = None, - ): ... - -else: - def create( - __screenName: str | None = None, - __baseName: str | None = None, - __className: str = "Tk", - __interactive: bool = False, - __wantobjects: bool = False, - __wantTk: bool = True, - __sync: bool = False, - __use: str | None = None, - ): ... - +def create( + __screenName: str | None = None, + __baseName: str = "", + __className: str = "Tk", + __interactive: bool = False, + __wantobjects: bool = False, + __wantTk: bool = True, + __sync: bool = False, + __use: str | None = None, +): ... def getbusywaitinterval(): ... def setbusywaitinterval(__new_val): ... diff --git a/mypy/typeshed/stdlib/_typeshed/__init__.pyi b/mypy/typeshed/stdlib/_typeshed/__init__.pyi index 05892c8aab11..e9a24bab28a9 100644 --- a/mypy/typeshed/stdlib/_typeshed/__init__.pyi +++ b/mypy/typeshed/stdlib/_typeshed/__init__.pyi @@ -7,8 +7,22 @@ from collections.abc import Awaitable, Callable, Iterable, Sequence, Set as Abst from dataclasses import Field from os import PathLike from types import FrameType, TracebackType -from typing import Any, AnyStr, ClassVar, Generic, Protocol, SupportsFloat, SupportsInt, TypeVar, overload -from typing_extensions import Buffer, Final, Literal, LiteralString, SupportsIndex, TypeAlias, final +from typing import ( + Any, + AnyStr, + ClassVar, + Final, + Generic, + Literal, + Protocol, + SupportsFloat, + SupportsIndex, + SupportsInt, + TypeVar, + final, + overload, +) +from typing_extensions import Buffer, LiteralString, TypeAlias _KT = TypeVar("_KT") _KT_co = TypeVar("_KT_co", covariant=True) @@ -19,8 +33,10 @@ _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) _T_contra = TypeVar("_T_contra", contravariant=True) -# Use for "self" annotations: -# def __enter__(self: Self) -> Self: ... +# Alternative to `typing_extensions.Self`, exclusively for use with `__new__` +# in metaclasses: +# def __new__(cls: type[Self], ...) -> Self: ... +# In other cases, use `typing_extensions.Self`. Self = TypeVar("Self") # noqa: Y001 # covariant version of typing.AnyStr, useful for protocols diff --git a/mypy/typeshed/stdlib/_weakref.pyi b/mypy/typeshed/stdlib/_weakref.pyi index ce0f681248ab..f939aa815bd2 100644 --- a/mypy/typeshed/stdlib/_weakref.pyi +++ b/mypy/typeshed/stdlib/_weakref.pyi @@ -1,7 +1,7 @@ import sys from collections.abc import Callable -from typing import Any, Generic, TypeVar, overload -from typing_extensions import Self, final +from typing import Any, Generic, TypeVar, final, overload +from typing_extensions import Self if sys.version_info >= (3, 9): from types import GenericAlias diff --git a/mypy/typeshed/stdlib/_winapi.pyi b/mypy/typeshed/stdlib/_winapi.pyi index 1aec6ce50443..21ae149e186e 100644 --- a/mypy/typeshed/stdlib/_winapi.pyi +++ b/mypy/typeshed/stdlib/_winapi.pyi @@ -1,8 +1,7 @@ import sys from _typeshed import ReadableBuffer from collections.abc import Sequence -from typing import Any, NoReturn, overload -from typing_extensions import Literal, final +from typing import Any, Literal, NoReturn, final, overload if sys.platform == "win32": ABOVE_NORMAL_PRIORITY_CLASS: Literal[0x8000] @@ -36,12 +35,11 @@ if sys.platform == "win32": FILE_GENERIC_READ: Literal[1179785] FILE_GENERIC_WRITE: Literal[1179926] - if sys.version_info >= (3, 8): - FILE_MAP_ALL_ACCESS: Literal[983071] - FILE_MAP_COPY: Literal[1] - FILE_MAP_EXECUTE: Literal[32] - FILE_MAP_READ: Literal[4] - FILE_MAP_WRITE: Literal[2] + FILE_MAP_ALL_ACCESS: Literal[983071] + FILE_MAP_COPY: Literal[1] + FILE_MAP_EXECUTE: Literal[32] + FILE_MAP_READ: Literal[4] + FILE_MAP_WRITE: Literal[2] FILE_TYPE_CHAR: Literal[2] FILE_TYPE_DISK: Literal[1] @@ -53,23 +51,21 @@ if sys.platform == "win32": GENERIC_WRITE: Literal[0x40000000] HIGH_PRIORITY_CLASS: Literal[0x80] INFINITE: Literal[0xFFFFFFFF] - if sys.version_info >= (3, 8): - # Ignore the Flake8 error -- flake8-pyi assumes - # most numbers this long will be implementation details, - # but here we can see that it's a power of 2 - INVALID_HANDLE_VALUE: Literal[0xFFFFFFFFFFFFFFFF] # noqa: Y054 + # Ignore the Flake8 error -- flake8-pyi assumes + # most numbers this long will be implementation details, + # but here we can see that it's a power of 2 + INVALID_HANDLE_VALUE: Literal[0xFFFFFFFFFFFFFFFF] # noqa: Y054 IDLE_PRIORITY_CLASS: Literal[0x40] NORMAL_PRIORITY_CLASS: Literal[0x20] REALTIME_PRIORITY_CLASS: Literal[0x100] NMPWAIT_WAIT_FOREVER: Literal[0xFFFFFFFF] - if sys.version_info >= (3, 8): - MEM_COMMIT: Literal[0x1000] - MEM_FREE: Literal[0x10000] - MEM_IMAGE: Literal[0x1000000] - MEM_MAPPED: Literal[0x40000] - MEM_PRIVATE: Literal[0x20000] - MEM_RESERVE: Literal[0x2000] + MEM_COMMIT: Literal[0x1000] + MEM_FREE: Literal[0x10000] + MEM_IMAGE: Literal[0x1000000] + MEM_MAPPED: Literal[0x40000] + MEM_PRIVATE: Literal[0x20000] + MEM_RESERVE: Literal[0x2000] NULL: Literal[0] OPEN_EXISTING: Literal[3] @@ -81,29 +77,27 @@ if sys.platform == "win32": PIPE_UNLIMITED_INSTANCES: Literal[255] PIPE_WAIT: Literal[0] - if sys.version_info >= (3, 8): - PAGE_EXECUTE: Literal[0x10] - PAGE_EXECUTE_READ: Literal[0x20] - PAGE_EXECUTE_READWRITE: Literal[0x40] - PAGE_EXECUTE_WRITECOPY: Literal[0x80] - PAGE_GUARD: Literal[0x100] - PAGE_NOACCESS: Literal[0x1] - PAGE_NOCACHE: Literal[0x200] - PAGE_READONLY: Literal[0x2] - PAGE_READWRITE: Literal[0x4] - PAGE_WRITECOMBINE: Literal[0x400] - PAGE_WRITECOPY: Literal[0x8] + PAGE_EXECUTE: Literal[0x10] + PAGE_EXECUTE_READ: Literal[0x20] + PAGE_EXECUTE_READWRITE: Literal[0x40] + PAGE_EXECUTE_WRITECOPY: Literal[0x80] + PAGE_GUARD: Literal[0x100] + PAGE_NOACCESS: Literal[0x1] + PAGE_NOCACHE: Literal[0x200] + PAGE_READONLY: Literal[0x2] + PAGE_READWRITE: Literal[0x4] + PAGE_WRITECOMBINE: Literal[0x400] + PAGE_WRITECOPY: Literal[0x8] PROCESS_ALL_ACCESS: Literal[0x1FFFFF] PROCESS_DUP_HANDLE: Literal[0x40] - if sys.version_info >= (3, 8): - SEC_COMMIT: Literal[0x8000000] - SEC_IMAGE: Literal[0x1000000] - SEC_LARGE_PAGES: Literal[0x80000000] - SEC_NOCACHE: Literal[0x10000000] - SEC_RESERVE: Literal[0x4000000] - SEC_WRITECOMBINE: Literal[0x40000000] + SEC_COMMIT: Literal[0x8000000] + SEC_IMAGE: Literal[0x1000000] + SEC_LARGE_PAGES: Literal[0x80000000] + SEC_NOCACHE: Literal[0x10000000] + SEC_RESERVE: Literal[0x4000000] + SEC_WRITECOMBINE: Literal[0x40000000] STARTF_USESHOWWINDOW: Literal[0x1] STARTF_USESTDHANDLES: Literal[0x100] @@ -114,8 +108,7 @@ if sys.platform == "win32": STILL_ACTIVE: Literal[259] SW_HIDE: Literal[0] - if sys.version_info >= (3, 8): - SYNCHRONIZE: Literal[0x100000] + SYNCHRONIZE: Literal[0x100000] WAIT_ABANDONED_0: Literal[128] WAIT_OBJECT_0: Literal[0] WAIT_TIMEOUT: Literal[258] diff --git a/mypy/typeshed/stdlib/abc.pyi b/mypy/typeshed/stdlib/abc.pyi index 7fe1d09f7589..c642f8b9f123 100644 --- a/mypy/typeshed/stdlib/abc.pyi +++ b/mypy/typeshed/stdlib/abc.pyi @@ -2,8 +2,8 @@ import _typeshed import sys from _typeshed import SupportsWrite from collections.abc import Callable -from typing import Any, TypeVar -from typing_extensions import Concatenate, Literal, ParamSpec +from typing import Any, Literal, TypeVar +from typing_extensions import Concatenate, ParamSpec _T = TypeVar("_T") _R_co = TypeVar("_R_co", covariant=True) diff --git a/mypy/typeshed/stdlib/aifc.pyi b/mypy/typeshed/stdlib/aifc.pyi index ab0c18ed6623..05bf53986b29 100644 --- a/mypy/typeshed/stdlib/aifc.pyi +++ b/mypy/typeshed/stdlib/aifc.pyi @@ -1,7 +1,7 @@ import sys from types import TracebackType -from typing import IO, Any, NamedTuple, overload -from typing_extensions import Literal, Self, TypeAlias +from typing import IO, Any, Literal, NamedTuple, overload +from typing_extensions import Self, TypeAlias if sys.version_info >= (3, 9): __all__ = ["Error", "open"] diff --git a/mypy/typeshed/stdlib/argparse.pyi b/mypy/typeshed/stdlib/argparse.pyi index 0cbbcd242195..489cc6b16634 100644 --- a/mypy/typeshed/stdlib/argparse.pyi +++ b/mypy/typeshed/stdlib/argparse.pyi @@ -2,8 +2,8 @@ import sys from _typeshed import sentinel from collections.abc import Callable, Generator, Iterable, Sequence from re import Pattern -from typing import IO, Any, Generic, NewType, NoReturn, Protocol, TypeVar, overload -from typing_extensions import Literal, Self, TypeAlias +from typing import IO, Any, Generic, Literal, NewType, NoReturn, Protocol, TypeVar, overload +from typing_extensions import Self, TypeAlias __all__ = [ "ArgumentParser", @@ -446,8 +446,7 @@ class _StoreFalseAction(_StoreConstAction): class _AppendAction(Action): ... # undocumented -if sys.version_info >= (3, 8): - class _ExtendAction(_AppendAction): ... +class _ExtendAction(_AppendAction): ... # undocumented class _AppendConstAction(Action): diff --git a/mypy/typeshed/stdlib/array.pyi b/mypy/typeshed/stdlib/array.pyi index 2ef821fcf87a..4b5675d2a76e 100644 --- a/mypy/typeshed/stdlib/array.pyi +++ b/mypy/typeshed/stdlib/array.pyi @@ -3,8 +3,8 @@ from _typeshed import ReadableBuffer, SupportsRead, SupportsWrite from collections.abc import Iterable # pytype crashes if array inherits from collections.abc.MutableSequence instead of typing.MutableSequence -from typing import Any, MutableSequence, TypeVar, overload # noqa: Y022 -from typing_extensions import Literal, Self, SupportsIndex, TypeAlias +from typing import Any, Literal, MutableSequence, SupportsIndex, TypeVar, overload # noqa: Y022 +from typing_extensions import Self, TypeAlias if sys.version_info >= (3, 12): from types import GenericAlias diff --git a/mypy/typeshed/stdlib/ast.pyi b/mypy/typeshed/stdlib/ast.pyi index 5c9cafc189be..4ab325b5baa7 100644 --- a/mypy/typeshed/stdlib/ast.pyi +++ b/mypy/typeshed/stdlib/ast.pyi @@ -3,32 +3,34 @@ import sys from _ast import * from _typeshed import ReadableBuffer, Unused from collections.abc import Iterator -from typing import Any, TypeVar as _TypeVar, overload -from typing_extensions import Literal, deprecated +from typing import Any, Literal, TypeVar as _TypeVar, overload +from typing_extensions import deprecated -if sys.version_info >= (3, 8): - class _ABC(type): - if sys.version_info >= (3, 9): - def __init__(cls, *args: Unused) -> None: ... +class _ABC(type): + if sys.version_info >= (3, 9): + def __init__(cls, *args: Unused) -> None: ... - @deprecated("Replaced by ast.Constant; removal scheduled for Python 3.14") - class Num(Constant, metaclass=_ABC): - value: int | float | complex - @deprecated("Replaced by ast.Constant; removal scheduled for Python 3.14") - class Str(Constant, metaclass=_ABC): - value: str - # Aliases for value, for backwards compatibility - s: str - @deprecated("Replaced by ast.Constant; removal scheduled for Python 3.14") - class Bytes(Constant, metaclass=_ABC): - value: bytes - # Aliases for value, for backwards compatibility - s: bytes - @deprecated("Replaced by ast.Constant; removal scheduled for Python 3.14") - class NameConstant(Constant, metaclass=_ABC): ... +@deprecated("Replaced by ast.Constant; removal scheduled for Python 3.14") +class Num(Constant, metaclass=_ABC): + value: int | float | complex - @deprecated("Replaced by ast.Constant; removal scheduled for Python 3.14") - class Ellipsis(Constant, metaclass=_ABC): ... +@deprecated("Replaced by ast.Constant; removal scheduled for Python 3.14") +class Str(Constant, metaclass=_ABC): + value: str + # Aliases for value, for backwards compatibility + s: str + +@deprecated("Replaced by ast.Constant; removal scheduled for Python 3.14") +class Bytes(Constant, metaclass=_ABC): + value: bytes + # Aliases for value, for backwards compatibility + s: bytes + +@deprecated("Replaced by ast.Constant; removal scheduled for Python 3.14") +class NameConstant(Constant, metaclass=_ABC): ... + +@deprecated("Replaced by ast.Constant; removal scheduled for Python 3.14") +class Ellipsis(Constant, metaclass=_ABC): ... if sys.version_info >= (3, 9): class slice(AST): ... @@ -90,10 +92,8 @@ class NodeVisitor: def visit_FormattedValue(self, node: FormattedValue) -> Any: ... def visit_JoinedStr(self, node: JoinedStr) -> Any: ... def visit_Constant(self, node: Constant) -> Any: ... - if sys.version_info >= (3, 8): - def visit_NamedExpr(self, node: NamedExpr) -> Any: ... - def visit_TypeIgnore(self, node: TypeIgnore) -> Any: ... - + def visit_NamedExpr(self, node: NamedExpr) -> Any: ... + def visit_TypeIgnore(self, node: TypeIgnore) -> Any: ... def visit_Attribute(self, node: Attribute) -> Any: ... def visit_Subscript(self, node: Subscript) -> Any: ... def visit_Starred(self, node: Starred) -> Any: ... @@ -181,100 +181,75 @@ class NodeTransformer(NodeVisitor): _T = _TypeVar("_T", bound=AST) -if sys.version_info >= (3, 8): - @overload - def parse( - source: str | ReadableBuffer, - filename: str | ReadableBuffer | os.PathLike[Any] = "", - mode: Literal["exec"] = "exec", - *, - type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, - ) -> Module: ... - @overload - def parse( - source: str | ReadableBuffer, - filename: str | ReadableBuffer | os.PathLike[Any], - mode: Literal["eval"], - *, - type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, - ) -> Expression: ... - @overload - def parse( - source: str | ReadableBuffer, - filename: str | ReadableBuffer | os.PathLike[Any], - mode: Literal["func_type"], - *, - type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, - ) -> FunctionType: ... - @overload - def parse( - source: str | ReadableBuffer, - filename: str | ReadableBuffer | os.PathLike[Any], - mode: Literal["single"], - *, - type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, - ) -> Interactive: ... - @overload - def parse( - source: str | ReadableBuffer, - *, - mode: Literal["eval"], - type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, - ) -> Expression: ... - @overload - def parse( - source: str | ReadableBuffer, - *, - mode: Literal["func_type"], - type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, - ) -> FunctionType: ... - @overload - def parse( - source: str | ReadableBuffer, - *, - mode: Literal["single"], - type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, - ) -> Interactive: ... - @overload - def parse( - source: str | ReadableBuffer, - filename: str | ReadableBuffer | os.PathLike[Any] = "", - mode: str = "exec", - *, - type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, - ) -> AST: ... - -else: - @overload - def parse( - source: str | ReadableBuffer, - filename: str | ReadableBuffer | os.PathLike[Any] = "", - mode: Literal["exec"] = "exec", - ) -> Module: ... - @overload - def parse( - source: str | ReadableBuffer, filename: str | ReadableBuffer | os.PathLike[Any], mode: Literal["eval"] - ) -> Expression: ... - @overload - def parse( - source: str | ReadableBuffer, filename: str | ReadableBuffer | os.PathLike[Any], mode: Literal["single"] - ) -> Interactive: ... - @overload - def parse(source: str | ReadableBuffer, *, mode: Literal["eval"]) -> Expression: ... - @overload - def parse(source: str | ReadableBuffer, *, mode: Literal["single"]) -> Interactive: ... - @overload - def parse( - source: str | ReadableBuffer, filename: str | ReadableBuffer | os.PathLike[Any] = "", mode: str = "exec" - ) -> AST: ... +@overload +def parse( + source: str | ReadableBuffer, + filename: str | ReadableBuffer | os.PathLike[Any] = "", + mode: Literal["exec"] = "exec", + *, + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, +) -> Module: ... +@overload +def parse( + source: str | ReadableBuffer, + filename: str | ReadableBuffer | os.PathLike[Any], + mode: Literal["eval"], + *, + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, +) -> Expression: ... +@overload +def parse( + source: str | ReadableBuffer, + filename: str | ReadableBuffer | os.PathLike[Any], + mode: Literal["func_type"], + *, + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, +) -> FunctionType: ... +@overload +def parse( + source: str | ReadableBuffer, + filename: str | ReadableBuffer | os.PathLike[Any], + mode: Literal["single"], + *, + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, +) -> Interactive: ... +@overload +def parse( + source: str | ReadableBuffer, + *, + mode: Literal["eval"], + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, +) -> Expression: ... +@overload +def parse( + source: str | ReadableBuffer, + *, + mode: Literal["func_type"], + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, +) -> FunctionType: ... +@overload +def parse( + source: str | ReadableBuffer, + *, + mode: Literal["single"], + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, +) -> Interactive: ... +@overload +def parse( + source: str | ReadableBuffer, + filename: str | ReadableBuffer | os.PathLike[Any] = "", + mode: str = "exec", + *, + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, +) -> AST: ... if sys.version_info >= (3, 9): def unparse(ast_obj: AST) -> str: ... @@ -295,10 +270,7 @@ def increment_lineno(node: _T, n: int = 1) -> _T: ... def iter_child_nodes(node: AST) -> Iterator[AST]: ... def iter_fields(node: AST) -> Iterator[tuple[str, Any]]: ... def literal_eval(node_or_string: str | AST) -> Any: ... - -if sys.version_info >= (3, 8): - def get_source_segment(source: str, node: AST, *, padded: bool = False) -> str | None: ... - +def get_source_segment(source: str, node: AST, *, padded: bool = False) -> str | None: ... def walk(node: AST) -> Iterator[AST]: ... if sys.version_info >= (3, 9): diff --git a/mypy/typeshed/stdlib/asyncio/__init__.pyi b/mypy/typeshed/stdlib/asyncio/__init__.pyi index c11465184389..d5bbe8cb0642 100644 --- a/mypy/typeshed/stdlib/asyncio/__init__.pyi +++ b/mypy/typeshed/stdlib/asyncio/__init__.pyi @@ -7,6 +7,7 @@ from typing_extensions import TypeAlias from .base_events import * from .coroutines import * from .events import * +from .exceptions import * from .futures import * from .locks import * from .protocols import * @@ -17,9 +18,6 @@ from .subprocess import * from .tasks import * from .transports import * -if sys.version_info >= (3, 8): - from .exceptions import * - if sys.version_info >= (3, 9): from .threads import * diff --git a/mypy/typeshed/stdlib/asyncio/base_events.pyi b/mypy/typeshed/stdlib/asyncio/base_events.pyi index ff6c42c3645a..112cfeefa8f2 100644 --- a/mypy/typeshed/stdlib/asyncio/base_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/base_events.pyi @@ -10,8 +10,8 @@ from asyncio.transports import BaseTransport, DatagramTransport, ReadTransport, from collections.abc import Callable, Iterable, Sequence from contextvars import Context from socket import AddressFamily, SocketKind, _Address, _RetAddress, socket -from typing import IO, Any, TypeVar, overload -from typing_extensions import Literal, TypeAlias, TypeVarTuple, Unpack +from typing import IO, Any, Literal, TypeVar, overload +from typing_extensions import TypeAlias, TypeVarTuple, Unpack if sys.version_info >= (3, 9): __all__ = ("BaseEventLoop", "Server") @@ -53,13 +53,8 @@ class Server(AbstractServer): def is_serving(self) -> bool: ... async def start_serving(self) -> None: ... async def serve_forever(self) -> None: ... - if sys.version_info >= (3, 8): - @property - def sockets(self) -> tuple[socket, ...]: ... - else: - @property - def sockets(self) -> list[socket]: ... - + @property + def sockets(self) -> tuple[socket, ...]: ... def close(self) -> None: ... async def wait_closed(self) -> None: ... @@ -87,10 +82,8 @@ class BaseEventLoop(AbstractEventLoop): # Tasks methods if sys.version_info >= (3, 11): def create_task(self, coro: _CoroutineLike[_T], *, name: object = None, context: Context | None = None) -> Task[_T]: ... - elif sys.version_info >= (3, 8): - def create_task(self, coro: _CoroutineLike[_T], *, name: object = None) -> Task[_T]: ... else: - def create_task(self, coro: _CoroutineLike[_T]) -> Task[_T]: ... + def create_task(self, coro: _CoroutineLike[_T], *, name: object = None) -> Task[_T]: ... def set_task_factory(self, factory: _TaskFactory | None) -> None: ... def get_task_factory(self) -> _TaskFactory | None: ... @@ -192,7 +185,7 @@ class BaseEventLoop(AbstractEventLoop): happy_eyeballs_delay: float | None = None, interleave: int | None = None, ) -> tuple[Transport, _ProtocolT]: ... - elif sys.version_info >= (3, 8): + else: @overload async def create_connection( self, @@ -229,39 +222,6 @@ class BaseEventLoop(AbstractEventLoop): happy_eyeballs_delay: float | None = None, interleave: int | None = None, ) -> tuple[Transport, _ProtocolT]: ... - else: - @overload - async def create_connection( - self, - protocol_factory: Callable[[], _ProtocolT], - host: str = ..., - port: int = ..., - *, - ssl: _SSLContext = None, - family: int = 0, - proto: int = 0, - flags: int = 0, - sock: None = None, - local_addr: tuple[str, int] | None = None, - server_hostname: str | None = None, - ssl_handshake_timeout: float | None = None, - ) -> tuple[Transport, _ProtocolT]: ... - @overload - async def create_connection( - self, - protocol_factory: Callable[[], _ProtocolT], - host: None = None, - port: None = None, - *, - ssl: _SSLContext = None, - family: int = 0, - proto: int = 0, - flags: int = 0, - sock: socket, - local_addr: None = None, - server_hostname: str | None = None, - ssl_handshake_timeout: float | None = None, - ) -> tuple[Transport, _ProtocolT]: ... if sys.version_info >= (3, 11): @overload async def create_server( diff --git a/mypy/typeshed/stdlib/asyncio/base_futures.pyi b/mypy/typeshed/stdlib/asyncio/base_futures.pyi index c51174ef23cd..231766200934 100644 --- a/mypy/typeshed/stdlib/asyncio/base_futures.pyi +++ b/mypy/typeshed/stdlib/asyncio/base_futures.pyi @@ -1,7 +1,6 @@ from collections.abc import Callable, Sequence from contextvars import Context -from typing import Any -from typing_extensions import Literal +from typing import Any, Literal from . import futures diff --git a/mypy/typeshed/stdlib/asyncio/constants.pyi b/mypy/typeshed/stdlib/asyncio/constants.pyi index 60d8529209c2..559cc02a0faa 100644 --- a/mypy/typeshed/stdlib/asyncio/constants.pyi +++ b/mypy/typeshed/stdlib/asyncio/constants.pyi @@ -1,6 +1,6 @@ import enum import sys -from typing_extensions import Literal +from typing import Literal LOG_THRESHOLD_FOR_CONNLOST_WRITES: Literal[5] ACCEPT_RETRY_DELAY: Literal[1] diff --git a/mypy/typeshed/stdlib/asyncio/coroutines.pyi b/mypy/typeshed/stdlib/asyncio/coroutines.pyi index 14fb627ae6fe..e92b150875f6 100644 --- a/mypy/typeshed/stdlib/asyncio/coroutines.pyi +++ b/mypy/typeshed/stdlib/asyncio/coroutines.pyi @@ -23,6 +23,4 @@ def iscoroutinefunction(func: Callable[_P, Awaitable[_T]]) -> TypeGuard[Callable def iscoroutinefunction(func: Callable[_P, object]) -> TypeGuard[Callable[_P, Coroutine[Any, Any, Any]]]: ... @overload def iscoroutinefunction(func: object) -> TypeGuard[Callable[..., Coroutine[Any, Any, Any]]]: ... - -# Can actually be a generator-style coroutine on Python 3.7 def iscoroutine(obj: object) -> TypeGuard[Coroutine[Any, Any, Any]]: ... diff --git a/mypy/typeshed/stdlib/asyncio/events.pyi b/mypy/typeshed/stdlib/asyncio/events.pyi index 0f51c457fc24..649771df8bf1 100644 --- a/mypy/typeshed/stdlib/asyncio/events.pyi +++ b/mypy/typeshed/stdlib/asyncio/events.pyi @@ -5,8 +5,8 @@ from abc import ABCMeta, abstractmethod from collections.abc import Callable, Coroutine, Generator, Sequence from contextvars import Context from socket import AddressFamily, SocketKind, _Address, _RetAddress, socket -from typing import IO, Any, Protocol, TypeVar, overload -from typing_extensions import Literal, Self, TypeAlias, TypeVarTuple, Unpack, deprecated +from typing import IO, Any, Literal, Protocol, TypeVar, overload +from typing_extensions import Self, TypeAlias, TypeVarTuple, Unpack, deprecated from . import _AwaitableLike, _CoroutineLike from .base_events import Server @@ -16,44 +16,23 @@ from .tasks import Task from .transports import BaseTransport, DatagramTransport, ReadTransport, SubprocessTransport, Transport, WriteTransport from .unix_events import AbstractChildWatcher -if sys.version_info >= (3, 8): - __all__ = ( - "AbstractEventLoopPolicy", - "AbstractEventLoop", - "AbstractServer", - "Handle", - "TimerHandle", - "get_event_loop_policy", - "set_event_loop_policy", - "get_event_loop", - "set_event_loop", - "new_event_loop", - "get_child_watcher", - "set_child_watcher", - "_set_running_loop", - "get_running_loop", - "_get_running_loop", - ) - -else: - __all__ = ( - "AbstractEventLoopPolicy", - "AbstractEventLoop", - "AbstractServer", - "Handle", - "TimerHandle", - "SendfileNotAvailableError", - "get_event_loop_policy", - "set_event_loop_policy", - "get_event_loop", - "set_event_loop", - "new_event_loop", - "get_child_watcher", - "set_child_watcher", - "_set_running_loop", - "get_running_loop", - "_get_running_loop", - ) +__all__ = ( + "AbstractEventLoopPolicy", + "AbstractEventLoop", + "AbstractServer", + "Handle", + "TimerHandle", + "get_event_loop_policy", + "set_event_loop_policy", + "get_event_loop", + "set_event_loop", + "new_event_loop", + "get_child_watcher", + "set_child_watcher", + "_set_running_loop", + "get_running_loop", + "_get_running_loop", +) _T = TypeVar("_T") _Ts = TypeVarTuple("_Ts") @@ -162,12 +141,9 @@ class AbstractEventLoop: def create_task( self, coro: _CoroutineLike[_T], *, name: str | None = None, context: Context | None = None ) -> Task[_T]: ... - elif sys.version_info >= (3, 8): - @abstractmethod - def create_task(self, coro: _CoroutineLike[_T], *, name: str | None = None) -> Task[_T]: ... else: @abstractmethod - def create_task(self, coro: _CoroutineLike[_T]) -> Task[_T]: ... + def create_task(self, coro: _CoroutineLike[_T], *, name: str | None = None) -> Task[_T]: ... @abstractmethod def set_task_factory(self, factory: _TaskFactory | None) -> None: ... @@ -242,7 +218,7 @@ class AbstractEventLoop: happy_eyeballs_delay: float | None = None, interleave: int | None = None, ) -> tuple[Transport, _ProtocolT]: ... - elif sys.version_info >= (3, 8): + else: @overload @abstractmethod async def create_connection( @@ -281,41 +257,6 @@ class AbstractEventLoop: happy_eyeballs_delay: float | None = None, interleave: int | None = None, ) -> tuple[Transport, _ProtocolT]: ... - else: - @overload - @abstractmethod - async def create_connection( - self, - protocol_factory: Callable[[], _ProtocolT], - host: str = ..., - port: int = ..., - *, - ssl: _SSLContext = None, - family: int = 0, - proto: int = 0, - flags: int = 0, - sock: None = None, - local_addr: tuple[str, int] | None = None, - server_hostname: str | None = None, - ssl_handshake_timeout: float | None = None, - ) -> tuple[Transport, _ProtocolT]: ... - @overload - @abstractmethod - async def create_connection( - self, - protocol_factory: Callable[[], _ProtocolT], - host: None = None, - port: None = None, - *, - ssl: _SSLContext = None, - family: int = 0, - proto: int = 0, - flags: int = 0, - sock: socket, - local_addr: None = None, - server_hostname: str | None = None, - ssl_handshake_timeout: float | None = None, - ) -> tuple[Transport, _ProtocolT]: ... if sys.version_info >= (3, 11): @overload @abstractmethod @@ -554,7 +495,6 @@ class AbstractEventLoop: def add_writer(self, fd: FileDescriptorLike, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> None: ... @abstractmethod def remove_writer(self, fd: FileDescriptorLike) -> bool: ... - # Completion based I/O methods returning Futures prior to 3.7 @abstractmethod async def sock_recv(self, sock: socket, nbytes: int) -> bytes: ... @abstractmethod @@ -632,6 +572,3 @@ else: def _set_running_loop(__loop: AbstractEventLoop | None) -> None: ... def _get_running_loop() -> AbstractEventLoop: ... def get_running_loop() -> AbstractEventLoop: ... - -if sys.version_info < (3, 8): - class SendfileNotAvailableError(RuntimeError): ... diff --git a/mypy/typeshed/stdlib/asyncio/futures.pyi b/mypy/typeshed/stdlib/asyncio/futures.pyi index af05425d02a2..44b9528705a5 100644 --- a/mypy/typeshed/stdlib/asyncio/futures.pyi +++ b/mypy/typeshed/stdlib/asyncio/futures.pyi @@ -1,25 +1,16 @@ import sys from collections.abc import Awaitable, Callable, Generator, Iterable -from concurrent.futures._base import Error, Future as _ConcurrentFuture -from typing import Any, TypeVar -from typing_extensions import Literal, Self, TypeGuard +from concurrent.futures._base import Future as _ConcurrentFuture +from contextvars import Context +from typing import Any, Literal, TypeVar +from typing_extensions import Self, TypeGuard from .events import AbstractEventLoop -if sys.version_info < (3, 8): - from concurrent.futures import CancelledError as CancelledError, TimeoutError as TimeoutError - - class InvalidStateError(Error): ... - -from contextvars import Context - if sys.version_info >= (3, 9): from types import GenericAlias -if sys.version_info >= (3, 8): - __all__ = ("Future", "wrap_future", "isfuture") -else: - __all__ = ("CancelledError", "TimeoutError", "InvalidStateError", "Future", "wrap_future", "isfuture") +__all__ = ("Future", "wrap_future", "isfuture") _T = TypeVar("_T") diff --git a/mypy/typeshed/stdlib/asyncio/locks.pyi b/mypy/typeshed/stdlib/asyncio/locks.pyi index 394b82a5b3d9..3aac34b6934f 100644 --- a/mypy/typeshed/stdlib/asyncio/locks.pyi +++ b/mypy/typeshed/stdlib/asyncio/locks.pyi @@ -4,8 +4,8 @@ from _typeshed import Unused from collections import deque from collections.abc import Callable, Generator from types import TracebackType -from typing import Any, TypeVar -from typing_extensions import Literal, Self +from typing import Any, Literal, TypeVar +from typing_extensions import Self from .events import AbstractEventLoop from .futures import Future @@ -47,6 +47,7 @@ else: ) -> None: ... class Lock(_ContextManagerMixin, _LoopBoundMixin): + _waiters: deque[Future[Any]] | None if sys.version_info >= (3, 10): def __init__(self) -> None: ... else: @@ -57,6 +58,7 @@ class Lock(_ContextManagerMixin, _LoopBoundMixin): def release(self) -> None: ... class Event(_LoopBoundMixin): + _waiters: deque[Future[Any]] if sys.version_info >= (3, 10): def __init__(self) -> None: ... else: @@ -68,6 +70,7 @@ class Event(_LoopBoundMixin): async def wait(self) -> Literal[True]: ... class Condition(_ContextManagerMixin, _LoopBoundMixin): + _waiters: deque[Future[Any]] if sys.version_info >= (3, 10): def __init__(self, lock: Lock | None = None) -> None: ... else: @@ -83,7 +86,7 @@ class Condition(_ContextManagerMixin, _LoopBoundMixin): class Semaphore(_ContextManagerMixin, _LoopBoundMixin): _value: int - _waiters: deque[Future[Any]] + _waiters: deque[Future[Any]] | None if sys.version_info >= (3, 10): def __init__(self, value: int = 1) -> None: ... else: diff --git a/mypy/typeshed/stdlib/asyncio/proactor_events.pyi b/mypy/typeshed/stdlib/asyncio/proactor_events.pyi index 4634bbb2b37c..957fdd6ce255 100644 --- a/mypy/typeshed/stdlib/asyncio/proactor_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/proactor_events.pyi @@ -1,8 +1,7 @@ import sys from collections.abc import Mapping from socket import socket -from typing import Any, ClassVar -from typing_extensions import Literal +from typing import Any, ClassVar, Literal from . import base_events, constants, events, futures, streams, transports diff --git a/mypy/typeshed/stdlib/asyncio/runners.pyi b/mypy/typeshed/stdlib/asyncio/runners.pyi index 847072b633ac..37a85b709cdc 100644 --- a/mypy/typeshed/stdlib/asyncio/runners.pyi +++ b/mypy/typeshed/stdlib/asyncio/runners.pyi @@ -2,8 +2,8 @@ import sys from _typeshed import Unused from collections.abc import Callable, Coroutine from contextvars import Context -from typing import Any, TypeVar -from typing_extensions import Self, final +from typing import Any, TypeVar, final +from typing_extensions import Self from .events import AbstractEventLoop @@ -28,8 +28,5 @@ if sys.version_info >= (3, 12): main: Coroutine[Any, Any, _T], *, debug: bool | None = ..., loop_factory: Callable[[], AbstractEventLoop] | None = ... ) -> _T: ... -elif sys.version_info >= (3, 8): - def run(main: Coroutine[Any, Any, _T], *, debug: bool | None = None) -> _T: ... - else: - def run(main: Coroutine[Any, Any, _T], *, debug: bool = False) -> _T: ... + def run(main: Coroutine[Any, Any, _T], *, debug: bool | None = None) -> _T: ... diff --git a/mypy/typeshed/stdlib/asyncio/sslproto.pyi b/mypy/typeshed/stdlib/asyncio/sslproto.pyi index 393a1fbdc468..5dcca950e819 100644 --- a/mypy/typeshed/stdlib/asyncio/sslproto.pyi +++ b/mypy/typeshed/stdlib/asyncio/sslproto.pyi @@ -3,8 +3,8 @@ import sys from collections import deque from collections.abc import Callable from enum import Enum -from typing import Any, ClassVar -from typing_extensions import Literal, TypeAlias +from typing import Any, ClassVar, Literal +from typing_extensions import TypeAlias from . import constants, events, futures, protocols, transports diff --git a/mypy/typeshed/stdlib/asyncio/streams.pyi b/mypy/typeshed/stdlib/asyncio/streams.pyi index 81a94425f8de..4dff8d28b616 100644 --- a/mypy/typeshed/stdlib/asyncio/streams.pyi +++ b/mypy/typeshed/stdlib/asyncio/streams.pyi @@ -2,61 +2,27 @@ import ssl import sys from _typeshed import StrPath from collections.abc import AsyncIterator, Awaitable, Callable, Iterable, Sequence -from typing import Any -from typing_extensions import Self, SupportsIndex, TypeAlias +from typing import Any, SupportsIndex +from typing_extensions import Self, TypeAlias from . import events, protocols, transports from .base_events import Server if sys.platform == "win32": - if sys.version_info >= (3, 8): - __all__ = ("StreamReader", "StreamWriter", "StreamReaderProtocol", "open_connection", "start_server") - else: - __all__ = ( - "StreamReader", - "StreamWriter", - "StreamReaderProtocol", - "open_connection", - "start_server", - "IncompleteReadError", - "LimitOverrunError", - ) + __all__ = ("StreamReader", "StreamWriter", "StreamReaderProtocol", "open_connection", "start_server") else: - if sys.version_info >= (3, 8): - __all__ = ( - "StreamReader", - "StreamWriter", - "StreamReaderProtocol", - "open_connection", - "start_server", - "open_unix_connection", - "start_unix_server", - ) - else: - __all__ = ( - "StreamReader", - "StreamWriter", - "StreamReaderProtocol", - "open_connection", - "start_server", - "IncompleteReadError", - "LimitOverrunError", - "open_unix_connection", - "start_unix_server", - ) + __all__ = ( + "StreamReader", + "StreamWriter", + "StreamReaderProtocol", + "open_connection", + "start_server", + "open_unix_connection", + "start_unix_server", + ) _ClientConnectedCallback: TypeAlias = Callable[[StreamReader, StreamWriter], Awaitable[None] | None] -if sys.version_info < (3, 8): - class IncompleteReadError(EOFError): - expected: int | None - partial: bytes - def __init__(self, partial: bytes, expected: int | None) -> None: ... - - class LimitOverrunError(Exception): - consumed: int - def __init__(self, message: str, consumed: int) -> None: ... - if sys.version_info >= (3, 10): async def open_connection( host: str | None = None, diff --git a/mypy/typeshed/stdlib/asyncio/subprocess.pyi b/mypy/typeshed/stdlib/asyncio/subprocess.pyi index 03aea65f6d54..19452d4eb469 100644 --- a/mypy/typeshed/stdlib/asyncio/subprocess.pyi +++ b/mypy/typeshed/stdlib/asyncio/subprocess.pyi @@ -3,16 +3,10 @@ import sys from _typeshed import StrOrBytesPath from asyncio import events, protocols, streams, transports from collections.abc import Callable, Collection -from typing import IO, Any -from typing_extensions import Literal, TypeAlias +from typing import IO, Any, Literal __all__ = ("create_subprocess_exec", "create_subprocess_shell") -if sys.version_info >= (3, 8): - _ExecArg: TypeAlias = StrOrBytesPath -else: - _ExecArg: TypeAlias = str | bytes - PIPE: int STDOUT: int DEVNULL: int @@ -74,8 +68,8 @@ if sys.version_info >= (3, 11): pipesize: int = -1, ) -> Process: ... async def create_subprocess_exec( - program: _ExecArg, - *args: _ExecArg, + program: StrOrBytesPath, + *args: StrOrBytesPath, stdin: int | IO[Any] | None = None, stdout: int | IO[Any] | None = None, stderr: int | IO[Any] | None = None, @@ -139,8 +133,8 @@ elif sys.version_info >= (3, 10): pipesize: int = -1, ) -> Process: ... async def create_subprocess_exec( - program: _ExecArg, - *args: _ExecArg, + program: StrOrBytesPath, + *args: StrOrBytesPath, stdin: int | IO[Any] | None = None, stdout: int | IO[Any] | None = None, stderr: int | IO[Any] | None = None, @@ -203,8 +197,8 @@ else: # >= 3.9 umask: int = -1, ) -> Process: ... async def create_subprocess_exec( - program: _ExecArg, - *args: _ExecArg, + program: StrOrBytesPath, + *args: StrOrBytesPath, stdin: int | IO[Any] | None = None, stdout: int | IO[Any] | None = None, stderr: int | IO[Any] | None = None, diff --git a/mypy/typeshed/stdlib/asyncio/tasks.pyi b/mypy/typeshed/stdlib/asyncio/tasks.pyi index 7c76abaf1dca..23447ba27aa5 100644 --- a/mypy/typeshed/stdlib/asyncio/tasks.pyi +++ b/mypy/typeshed/stdlib/asyncio/tasks.pyi @@ -2,8 +2,8 @@ import concurrent.futures import sys from collections.abc import Awaitable, Coroutine, Generator, Iterable, Iterator from types import FrameType -from typing import Any, Protocol, TextIO, TypeVar, overload -from typing_extensions import Literal, TypeAlias +from typing import Any, Literal, Protocol, TextIO, TypeVar, overload +from typing_extensions import TypeAlias from . import _CoroutineLike from .events import AbstractEventLoop @@ -402,16 +402,14 @@ class Task(Future[_T_co]): # type: ignore[type-var] # pyright: ignore[reportGe name: str | None = ..., context: Context | None = None, ) -> None: ... - elif sys.version_info >= (3, 8): + else: def __init__( self, coro: _TaskCompatibleCoro[_T_co], *, loop: AbstractEventLoop = ..., name: str | None = ... ) -> None: ... - else: - def __init__(self, coro: _TaskCompatibleCoro[_T_co], *, loop: AbstractEventLoop = ...) -> None: ... - if sys.version_info >= (3, 8): - def get_coro(self) -> _TaskCompatibleCoro[_T_co]: ... - def get_name(self) -> str: ... - def set_name(self, __value: object) -> None: ... + + def get_coro(self) -> _TaskCompatibleCoro[_T_co]: ... + def get_name(self) -> str: ... + def set_name(self, __value: object) -> None: ... if sys.version_info >= (3, 12): def get_context(self) -> Context: ... @@ -433,11 +431,8 @@ def all_tasks(loop: AbstractEventLoop | None = None) -> set[Task[Any]]: ... if sys.version_info >= (3, 11): def create_task(coro: _CoroutineLike[_T], *, name: str | None = None, context: Context | None = None) -> Task[_T]: ... -elif sys.version_info >= (3, 8): - def create_task(coro: _CoroutineLike[_T], *, name: str | None = None) -> Task[_T]: ... - else: - def create_task(coro: _CoroutineLike[_T]) -> Task[_T]: ... + def create_task(coro: _CoroutineLike[_T], *, name: str | None = None) -> Task[_T]: ... def current_task(loop: AbstractEventLoop | None = None) -> Task[Any] | None: ... def _enter_task(loop: AbstractEventLoop, task: Task[Any]) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/timeouts.pyi b/mypy/typeshed/stdlib/asyncio/timeouts.pyi index 2d31b777b77d..2f0e40e25680 100644 --- a/mypy/typeshed/stdlib/asyncio/timeouts.pyi +++ b/mypy/typeshed/stdlib/asyncio/timeouts.pyi @@ -1,5 +1,6 @@ from types import TracebackType -from typing_extensions import Self, final +from typing import final +from typing_extensions import Self __all__ = ("Timeout", "timeout", "timeout_at") diff --git a/mypy/typeshed/stdlib/asyncio/unix_events.pyi b/mypy/typeshed/stdlib/asyncio/unix_events.pyi index ee16035f86a8..d2a2fef5c33b 100644 --- a/mypy/typeshed/stdlib/asyncio/unix_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/unix_events.pyi @@ -2,7 +2,8 @@ import sys import types from abc import ABCMeta, abstractmethod from collections.abc import Callable -from typing_extensions import Literal, Self, TypeVarTuple, Unpack, deprecated +from typing import Literal +from typing_extensions import Self, TypeVarTuple, Unpack, deprecated from .events import AbstractEventLoop, BaseDefaultEventLoopPolicy from .selector_events import BaseSelectorEventLoop @@ -29,9 +30,8 @@ if sys.version_info >= (3, 12): def __exit__( self, typ: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None ) -> None: ... - if sys.version_info >= (3, 8): - @abstractmethod - def is_active(self) -> bool: ... + @abstractmethod + def is_active(self) -> bool: ... else: class AbstractChildWatcher: @@ -49,9 +49,8 @@ else: def __exit__( self, typ: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None ) -> None: ... - if sys.version_info >= (3, 8): - @abstractmethod - def is_active(self) -> bool: ... + @abstractmethod + def is_active(self) -> bool: ... if sys.platform != "win32": if sys.version_info >= (3, 9): @@ -65,7 +64,7 @@ if sys.platform != "win32": "ThreadedChildWatcher", "DefaultEventLoopPolicy", ) - elif sys.version_info >= (3, 8): + else: __all__ = ( "SelectorEventLoop", "AbstractChildWatcher", @@ -75,16 +74,12 @@ if sys.platform != "win32": "ThreadedChildWatcher", "DefaultEventLoopPolicy", ) - else: - __all__ = ("SelectorEventLoop", "AbstractChildWatcher", "SafeChildWatcher", "FastChildWatcher", "DefaultEventLoopPolicy") # Doesn't actually have ABCMeta metaclass at runtime, but mypy complains if we don't have it in the stub. # See discussion in #7412 class BaseChildWatcher(AbstractChildWatcher, metaclass=ABCMeta): def close(self) -> None: ... - if sys.version_info >= (3, 8): - def is_active(self) -> bool: ... - + def is_active(self) -> bool: ... def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... if sys.version_info >= (3, 12): @@ -141,7 +136,7 @@ if sys.platform != "win32": def add_child_handler(self, pid: int, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> None: ... def remove_child_handler(self, pid: int) -> bool: ... def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... - elif sys.version_info >= (3, 8): + else: class MultiLoopChildWatcher(AbstractChildWatcher): def is_active(self) -> bool: ... def close(self) -> None: ... @@ -153,18 +148,17 @@ if sys.platform != "win32": def remove_child_handler(self, pid: int) -> bool: ... def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... - if sys.version_info >= (3, 8): - class ThreadedChildWatcher(AbstractChildWatcher): - def is_active(self) -> Literal[True]: ... - def close(self) -> None: ... - def __enter__(self) -> Self: ... - def __exit__( - self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None - ) -> None: ... - def __del__(self) -> None: ... - def add_child_handler(self, pid: int, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> None: ... - def remove_child_handler(self, pid: int) -> bool: ... - def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... + class ThreadedChildWatcher(AbstractChildWatcher): + def is_active(self) -> Literal[True]: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None + ) -> None: ... + def __del__(self) -> None: ... + def add_child_handler(self, pid: int, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... + def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... if sys.version_info >= (3, 9): class PidfdChildWatcher(AbstractChildWatcher): diff --git a/mypy/typeshed/stdlib/asyncio/windows_events.pyi b/mypy/typeshed/stdlib/asyncio/windows_events.pyi index 8e643dd4a3f2..fdf43d3ea91c 100644 --- a/mypy/typeshed/stdlib/asyncio/windows_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/windows_events.pyi @@ -2,8 +2,7 @@ import socket import sys from _typeshed import Incomplete, ReadableBuffer, WriteableBuffer from collections.abc import Callable -from typing import IO, Any, ClassVar, NoReturn -from typing_extensions import Literal +from typing import IO, Any, ClassVar, Literal, NoReturn from . import events, futures, proactor_events, selector_events, streams, windows_utils diff --git a/mypy/typeshed/stdlib/asyncio/windows_utils.pyi b/mypy/typeshed/stdlib/asyncio/windows_utils.pyi index ed5d8da275c5..6b3589adc3cb 100644 --- a/mypy/typeshed/stdlib/asyncio/windows_utils.pyi +++ b/mypy/typeshed/stdlib/asyncio/windows_utils.pyi @@ -2,8 +2,8 @@ import subprocess import sys from collections.abc import Callable from types import TracebackType -from typing import Any, AnyStr -from typing_extensions import Literal, Self +from typing import Any, AnyStr, Literal +from typing_extensions import Self if sys.platform == "win32": __all__ = ("pipe", "Popen", "PIPE", "PipeHandle") diff --git a/mypy/typeshed/stdlib/bdb.pyi b/mypy/typeshed/stdlib/bdb.pyi index 2a1fdddff7e9..43012a253164 100644 --- a/mypy/typeshed/stdlib/bdb.pyi +++ b/mypy/typeshed/stdlib/bdb.pyi @@ -2,8 +2,8 @@ import sys from _typeshed import ExcInfo, TraceFunction from collections.abc import Callable, Iterable, Mapping from types import CodeType, FrameType, TracebackType -from typing import IO, Any, SupportsInt, TypeVar -from typing_extensions import Literal, ParamSpec +from typing import IO, Any, Literal, SupportsInt, TypeVar +from typing_extensions import ParamSpec __all__ = ["BdbQuit", "Bdb", "Breakpoint"] @@ -50,11 +50,11 @@ class Bdb: def set_quit(self) -> None: ... def set_break( self, filename: str, lineno: int, temporary: bool = False, cond: str | None = None, funcname: str | None = None - ) -> None: ... - def clear_break(self, filename: str, lineno: int) -> None: ... - def clear_bpbynumber(self, arg: SupportsInt) -> None: ... - def clear_all_file_breaks(self, filename: str) -> None: ... - def clear_all_breaks(self) -> None: ... + ) -> str | None: ... + def clear_break(self, filename: str, lineno: int) -> str | None: ... + def clear_bpbynumber(self, arg: SupportsInt) -> str | None: ... + def clear_all_file_breaks(self, filename: str) -> str | None: ... + def clear_all_breaks(self) -> str | None: ... def get_bpbynumber(self, arg: SupportsInt) -> Breakpoint: ... def get_break(self, filename: str, lineno: int) -> bool: ... def get_breaks(self, filename: str, lineno: int) -> list[Breakpoint]: ... diff --git a/mypy/typeshed/stdlib/binascii.pyi b/mypy/typeshed/stdlib/binascii.pyi index 759b6c39399a..d48507b90694 100644 --- a/mypy/typeshed/stdlib/binascii.pyi +++ b/mypy/typeshed/stdlib/binascii.pyi @@ -27,16 +27,8 @@ if sys.version_info < (3, 11): def crc_hqx(__data: ReadableBuffer, __crc: int) -> int: ... def crc32(__data: ReadableBuffer, __crc: int = 0) -> int: ... - -if sys.version_info >= (3, 8): - # sep must be str or bytes, not bytearray or any other buffer - def b2a_hex(data: ReadableBuffer, sep: str | bytes = ..., bytes_per_sep: int = ...) -> bytes: ... - def hexlify(data: ReadableBuffer, sep: str | bytes = ..., bytes_per_sep: int = ...) -> bytes: ... - -else: - def b2a_hex(__data: ReadableBuffer) -> bytes: ... - def hexlify(__data: ReadableBuffer) -> bytes: ... - +def b2a_hex(data: ReadableBuffer, sep: str | bytes = ..., bytes_per_sep: int = ...) -> bytes: ... +def hexlify(data: ReadableBuffer, sep: str | bytes = ..., bytes_per_sep: int = ...) -> bytes: ... def a2b_hex(__hexstr: _AsciiBuffer) -> bytes: ... def unhexlify(__hexstr: _AsciiBuffer) -> bytes: ... diff --git a/mypy/typeshed/stdlib/binhex.pyi b/mypy/typeshed/stdlib/binhex.pyi index 64ba9f6150b4..d514be3b9b26 100644 --- a/mypy/typeshed/stdlib/binhex.pyi +++ b/mypy/typeshed/stdlib/binhex.pyi @@ -1,6 +1,6 @@ from _typeshed import SizedBuffer -from typing import IO, Any -from typing_extensions import Literal, TypeAlias +from typing import IO, Any, Literal +from typing_extensions import TypeAlias __all__ = ["binhex", "hexbin", "Error"] diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index dca3c2160b5a..b8c807dd388d 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -50,21 +50,24 @@ from typing import ( # noqa: Y022 SupportsBytes, SupportsComplex, SupportsFloat, + SupportsIndex, TypeVar, + final, overload, type_check_only, ) -from typing_extensions import ( + +# we can't import `Literal` from typing or mypy crashes: see #11247 +from typing_extensions import ( # noqa: Y023 Concatenate, Literal, + LiteralString, ParamSpec, Self, - SupportsIndex, TypeAlias, TypeGuard, TypeVarTuple, deprecated, - final, ) if sys.version_info >= (3, 9): @@ -115,10 +118,7 @@ class object: # return type of pickle methods is rather hard to express in the current type system # see #6661 and https://docs.python.org/3/library/pickle.html#object.__reduce__ def __reduce__(self) -> str | tuple[Any, ...]: ... - if sys.version_info >= (3, 8): - def __reduce_ex__(self, __protocol: SupportsIndex) -> str | tuple[Any, ...]: ... - else: - def __reduce_ex__(self, __protocol: int) -> str | tuple[Any, ...]: ... + def __reduce_ex__(self, __protocol: SupportsIndex) -> str | tuple[Any, ...]: ... if sys.version_info >= (3, 11): def __getstate__(self) -> object: ... @@ -226,9 +226,7 @@ class int: def __new__(cls, __x: ConvertibleToInt = ...) -> Self: ... @overload def __new__(cls, __x: str | bytes | bytearray, base: SupportsIndex) -> Self: ... - if sys.version_info >= (3, 8): - def as_integer_ratio(self) -> tuple[int, Literal[1]]: ... - + def as_integer_ratio(self) -> tuple[int, Literal[1]]: ... @property def real(self) -> int: ... @property @@ -392,22 +390,15 @@ class float: def __bool__(self) -> bool: ... class complex: - if sys.version_info >= (3, 8): - # Python doesn't currently accept SupportsComplex for the second argument - @overload - def __new__( - cls, - real: complex | SupportsComplex | SupportsFloat | SupportsIndex = ..., - imag: complex | SupportsFloat | SupportsIndex = ..., - ) -> Self: ... - @overload - def __new__(cls, real: str | SupportsComplex | SupportsFloat | SupportsIndex | complex) -> Self: ... - else: - @overload - def __new__(cls, real: complex | SupportsComplex | SupportsFloat = ..., imag: complex | SupportsFloat = ...) -> Self: ... - @overload - def __new__(cls, real: str | SupportsComplex | SupportsFloat | complex) -> Self: ... - + # Python doesn't currently accept SupportsComplex for the second argument + @overload + def __new__( + cls, + real: complex | SupportsComplex | SupportsFloat | SupportsIndex = ..., + imag: complex | SupportsFloat | SupportsIndex = ..., + ) -> Self: ... + @overload + def __new__(cls, real: str | SupportsComplex | SupportsFloat | SupportsIndex | complex) -> Self: ... @property def real(self) -> float: ... @property @@ -444,20 +435,31 @@ class str(Sequence[str]): def __new__(cls, object: object = ...) -> Self: ... @overload def __new__(cls, object: ReadableBuffer, encoding: str = ..., errors: str = ...) -> Self: ... + @overload + def capitalize(self: LiteralString) -> LiteralString: ... + @overload def capitalize(self) -> str: ... # type: ignore[misc] + @overload + def casefold(self: LiteralString) -> LiteralString: ... + @overload def casefold(self) -> str: ... # type: ignore[misc] + @overload + def center(self: LiteralString, __width: SupportsIndex, __fillchar: LiteralString = " ") -> LiteralString: ... + @overload def center(self, __width: SupportsIndex, __fillchar: str = " ") -> str: ... # type: ignore[misc] def count(self, x: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... def encode(self, encoding: str = "utf-8", errors: str = "strict") -> bytes: ... def endswith( self, __suffix: str | tuple[str, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> bool: ... - if sys.version_info >= (3, 8): - def expandtabs(self, tabsize: SupportsIndex = 8) -> str: ... # type: ignore[misc] - else: - def expandtabs(self, tabsize: int = 8) -> str: ... # type: ignore[misc] - + @overload + def expandtabs(self: LiteralString, tabsize: SupportsIndex = 8) -> LiteralString: ... + @overload + def expandtabs(self, tabsize: SupportsIndex = 8) -> str: ... # type: ignore[misc] def find(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... + @overload + def format(self: LiteralString, *args: LiteralString, **kwargs: LiteralString) -> LiteralString: ... + @overload def format(self, *args: object, **kwargs: object) -> str: ... def format_map(self, map: _FormatMapMapping) -> str: ... def index(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... @@ -473,32 +475,91 @@ class str(Sequence[str]): def isspace(self) -> bool: ... def istitle(self) -> bool: ... def isupper(self) -> bool: ... + @overload + def join(self: LiteralString, __iterable: Iterable[LiteralString]) -> LiteralString: ... + @overload def join(self, __iterable: Iterable[str]) -> str: ... # type: ignore[misc] + @overload + def ljust(self: LiteralString, __width: SupportsIndex, __fillchar: LiteralString = " ") -> LiteralString: ... + @overload def ljust(self, __width: SupportsIndex, __fillchar: str = " ") -> str: ... # type: ignore[misc] + @overload + def lower(self: LiteralString) -> LiteralString: ... + @overload def lower(self) -> str: ... # type: ignore[misc] + @overload + def lstrip(self: LiteralString, __chars: LiteralString | None = None) -> LiteralString: ... + @overload def lstrip(self, __chars: str | None = None) -> str: ... # type: ignore[misc] + @overload + def partition(self: LiteralString, __sep: LiteralString) -> tuple[LiteralString, LiteralString, LiteralString]: ... + @overload def partition(self, __sep: str) -> tuple[str, str, str]: ... # type: ignore[misc] + @overload + def replace( + self: LiteralString, __old: LiteralString, __new: LiteralString, __count: SupportsIndex = -1 + ) -> LiteralString: ... + @overload def replace(self, __old: str, __new: str, __count: SupportsIndex = -1) -> str: ... # type: ignore[misc] if sys.version_info >= (3, 9): + @overload + def removeprefix(self: LiteralString, __prefix: LiteralString) -> LiteralString: ... + @overload def removeprefix(self, __prefix: str) -> str: ... # type: ignore[misc] + @overload + def removesuffix(self: LiteralString, __suffix: LiteralString) -> LiteralString: ... + @overload def removesuffix(self, __suffix: str) -> str: ... # type: ignore[misc] def rfind(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... def rindex(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... + @overload + def rjust(self: LiteralString, __width: SupportsIndex, __fillchar: LiteralString = " ") -> LiteralString: ... + @overload def rjust(self, __width: SupportsIndex, __fillchar: str = " ") -> str: ... # type: ignore[misc] + @overload + def rpartition(self: LiteralString, __sep: LiteralString) -> tuple[LiteralString, LiteralString, LiteralString]: ... + @overload def rpartition(self, __sep: str) -> tuple[str, str, str]: ... # type: ignore[misc] + @overload + def rsplit(self: LiteralString, sep: LiteralString | None = None, maxsplit: SupportsIndex = -1) -> list[LiteralString]: ... + @overload def rsplit(self, sep: str | None = None, maxsplit: SupportsIndex = -1) -> list[str]: ... # type: ignore[misc] + @overload + def rstrip(self: LiteralString, __chars: LiteralString | None = None) -> LiteralString: ... + @overload def rstrip(self, __chars: str | None = None) -> str: ... # type: ignore[misc] + @overload + def split(self: LiteralString, sep: LiteralString | None = None, maxsplit: SupportsIndex = -1) -> list[LiteralString]: ... + @overload def split(self, sep: str | None = None, maxsplit: SupportsIndex = -1) -> list[str]: ... # type: ignore[misc] + @overload + def splitlines(self: LiteralString, keepends: bool = False) -> list[LiteralString]: ... + @overload def splitlines(self, keepends: bool = False) -> list[str]: ... # type: ignore[misc] def startswith( self, __prefix: str | tuple[str, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> bool: ... + @overload + def strip(self: LiteralString, __chars: LiteralString | None = None) -> LiteralString: ... + @overload def strip(self, __chars: str | None = None) -> str: ... # type: ignore[misc] + @overload + def swapcase(self: LiteralString) -> LiteralString: ... + @overload def swapcase(self) -> str: ... # type: ignore[misc] + @overload + def title(self: LiteralString) -> LiteralString: ... + @overload def title(self) -> str: ... # type: ignore[misc] def translate(self, __table: _TranslateTable) -> str: ... + @overload + def upper(self: LiteralString) -> LiteralString: ... + @overload def upper(self) -> str: ... # type: ignore[misc] + @overload + def zfill(self: LiteralString, __width: SupportsIndex) -> LiteralString: ... + @overload def zfill(self, __width: SupportsIndex) -> str: ... # type: ignore[misc] @staticmethod @overload @@ -509,6 +570,9 @@ class str(Sequence[str]): @staticmethod @overload def maketrans(__x: str, __y: str, __z: str) -> dict[int, int | None]: ... + @overload + def __add__(self: LiteralString, __value: LiteralString) -> LiteralString: ... + @overload def __add__(self, __value: str) -> str: ... # type: ignore[misc] # Incompatible with Sequence.__contains__ def __contains__(self, __key: str) -> bool: ... # type: ignore[override] @@ -517,13 +581,25 @@ class str(Sequence[str]): def __getitem__(self, __key: SupportsIndex | slice) -> str: ... def __gt__(self, __value: str) -> bool: ... def __hash__(self) -> int: ... + @overload + def __iter__(self: LiteralString) -> Iterator[LiteralString]: ... + @overload def __iter__(self) -> Iterator[str]: ... # type: ignore[misc] def __le__(self, __value: str) -> bool: ... def __len__(self) -> int: ... def __lt__(self, __value: str) -> bool: ... + @overload + def __mod__(self: LiteralString, __value: LiteralString | tuple[LiteralString, ...]) -> LiteralString: ... + @overload def __mod__(self, __value: Any) -> str: ... + @overload + def __mul__(self: LiteralString, __value: SupportsIndex) -> LiteralString: ... + @overload def __mul__(self, __value: SupportsIndex) -> str: ... # type: ignore[misc] def __ne__(self, __value: object) -> bool: ... + @overload + def __rmul__(self: LiteralString, __value: SupportsIndex) -> LiteralString: ... + @overload def __rmul__(self, __value: SupportsIndex) -> str: ... # type: ignore[misc] def __getnewargs__(self) -> tuple[str]: ... @@ -546,19 +622,11 @@ class bytes(Sequence[int]): __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ..., ) -> bool: ... - if sys.version_info >= (3, 8): - def expandtabs(self, tabsize: SupportsIndex = 8) -> bytes: ... - else: - def expandtabs(self, tabsize: int = ...) -> bytes: ... - + def expandtabs(self, tabsize: SupportsIndex = 8) -> bytes: ... def find( self, __sub: ReadableBuffer | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> int: ... - if sys.version_info >= (3, 8): - def hex(self, sep: str | bytes = ..., bytes_per_sep: SupportsIndex = ...) -> str: ... - else: - def hex(self) -> str: ... - + def hex(self, sep: str | bytes = ..., bytes_per_sep: SupportsIndex = ...) -> str: ... def index( self, __sub: ReadableBuffer | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> int: ... @@ -654,20 +722,12 @@ class bytearray(MutableSequence[int]): __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ..., ) -> bool: ... - if sys.version_info >= (3, 8): - def expandtabs(self, tabsize: SupportsIndex = 8) -> bytearray: ... - else: - def expandtabs(self, tabsize: int = ...) -> bytearray: ... - + def expandtabs(self, tabsize: SupportsIndex = 8) -> bytearray: ... def extend(self, __iterable_of_ints: Iterable[SupportsIndex]) -> None: ... def find( self, __sub: ReadableBuffer | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> int: ... - if sys.version_info >= (3, 8): - def hex(self, sep: str | bytes = ..., bytes_per_sep: SupportsIndex = ...) -> str: ... - else: - def hex(self) -> str: ... - + def hex(self, sep: str | bytes = ..., bytes_per_sep: SupportsIndex = ...) -> str: ... def index( self, __sub: ReadableBuffer | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> int: ... @@ -784,7 +844,7 @@ class memoryview(Sequence[int]): ) -> None: ... def cast(self, format: str, shape: list[int] | tuple[int, ...] = ...) -> memoryview: ... @overload - def __getitem__(self, __key: SupportsIndex) -> int: ... + def __getitem__(self, __key: SupportsIndex | tuple[SupportsIndex, ...]) -> int: ... @overload def __getitem__(self, __key: slice) -> memoryview: ... def __contains__(self, __x: object) -> bool: ... @@ -795,24 +855,16 @@ class memoryview(Sequence[int]): @overload def __setitem__(self, __key: slice, __value: ReadableBuffer) -> None: ... @overload - def __setitem__(self, __key: SupportsIndex, __value: SupportsIndex) -> None: ... + def __setitem__(self, __key: SupportsIndex | tuple[SupportsIndex, ...], __value: SupportsIndex) -> None: ... if sys.version_info >= (3, 10): def tobytes(self, order: Literal["C", "F", "A"] | None = "C") -> bytes: ... - elif sys.version_info >= (3, 8): - def tobytes(self, order: Literal["C", "F", "A"] | None = None) -> bytes: ... else: - def tobytes(self) -> bytes: ... + def tobytes(self, order: Literal["C", "F", "A"] | None = None) -> bytes: ... def tolist(self) -> list[int]: ... - if sys.version_info >= (3, 8): - def toreadonly(self) -> memoryview: ... - + def toreadonly(self) -> memoryview: ... def release(self) -> None: ... - if sys.version_info >= (3, 8): - def hex(self, sep: str | bytes = ..., bytes_per_sep: SupportsIndex = ...) -> str: ... - else: - def hex(self) -> str: ... - + def hex(self, sep: str | bytes = ..., bytes_per_sep: SupportsIndex = ...) -> str: ... def __buffer__(self, __flags: int) -> memoryview: ... def __release_buffer__(self, __buffer: memoryview) -> None: ... @@ -1026,8 +1078,7 @@ class dict(MutableMapping[_KT, _VT]): def __delitem__(self, __key: _KT) -> None: ... def __iter__(self) -> Iterator[_KT]: ... def __eq__(self, __value: object) -> bool: ... - if sys.version_info >= (3, 8): - def __reversed__(self) -> Iterator[_KT]: ... + def __reversed__(self) -> Iterator[_KT]: ... __hash__: ClassVar[None] # type: ignore[assignment] if sys.version_info >= (3, 9): def __class_getitem__(cls, __item: Any) -> GenericAlias: ... @@ -1204,89 +1255,49 @@ if sys.version_info >= (3, 10): # compile() returns a CodeType, unless the flags argument includes PyCF_ONLY_AST (=1024), # in which case it returns ast.AST. We have overloads for flag 0 (the default) and for # explicitly passing PyCF_ONLY_AST. We fall back to Any for other values of flags. -if sys.version_info >= (3, 8): - @overload - def compile( - source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, - filename: str | ReadableBuffer | _PathLike[Any], - mode: str, - flags: Literal[0], - dont_inherit: bool = False, - optimize: int = -1, - *, - _feature_version: int = -1, - ) -> CodeType: ... - @overload - def compile( - source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, - filename: str | ReadableBuffer | _PathLike[Any], - mode: str, - *, - dont_inherit: bool = False, - optimize: int = -1, - _feature_version: int = -1, - ) -> CodeType: ... - @overload - def compile( - source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, - filename: str | ReadableBuffer | _PathLike[Any], - mode: str, - flags: Literal[1024], - dont_inherit: bool = False, - optimize: int = -1, - *, - _feature_version: int = -1, - ) -> _ast.AST: ... - @overload - def compile( - source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, - filename: str | ReadableBuffer | _PathLike[Any], - mode: str, - flags: int, - dont_inherit: bool = False, - optimize: int = -1, - *, - _feature_version: int = -1, - ) -> Any: ... - -else: - @overload - def compile( - source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, - filename: str | ReadableBuffer | _PathLike[Any], - mode: str, - flags: Literal[0], - dont_inherit: bool = False, - optimize: int = -1, - ) -> CodeType: ... - @overload - def compile( - source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, - filename: str | ReadableBuffer | _PathLike[Any], - mode: str, - *, - dont_inherit: bool = False, - optimize: int = -1, - ) -> CodeType: ... - @overload - def compile( - source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, - filename: str | ReadableBuffer | _PathLike[Any], - mode: str, - flags: Literal[1024], - dont_inherit: bool = False, - optimize: int = -1, - ) -> _ast.AST: ... - @overload - def compile( - source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, - filename: str | ReadableBuffer | _PathLike[Any], - mode: str, - flags: int, - dont_inherit: bool = False, - optimize: int = -1, - ) -> Any: ... - +@overload +def compile( + source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, + filename: str | ReadableBuffer | _PathLike[Any], + mode: str, + flags: Literal[0], + dont_inherit: bool = False, + optimize: int = -1, + *, + _feature_version: int = -1, +) -> CodeType: ... +@overload +def compile( + source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, + filename: str | ReadableBuffer | _PathLike[Any], + mode: str, + *, + dont_inherit: bool = False, + optimize: int = -1, + _feature_version: int = -1, +) -> CodeType: ... +@overload +def compile( + source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, + filename: str | ReadableBuffer | _PathLike[Any], + mode: str, + flags: Literal[1024], + dont_inherit: bool = False, + optimize: int = -1, + *, + _feature_version: int = -1, +) -> _ast.AST: ... +@overload +def compile( + source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, + filename: str | ReadableBuffer | _PathLike[Any], + mode: str, + flags: int, + dont_inherit: bool = False, + optimize: int = -1, + *, + _feature_version: int = -1, +) -> Any: ... def copyright() -> None: ... def credits() -> None: ... def delattr(__obj: object, __name: str) -> None: ... @@ -1580,77 +1591,45 @@ _SupportsSomeKindOfPow = ( # noqa: Y026 # TODO: Use TypeAlias once mypy bugs a _SupportsPow2[Any, Any] | _SupportsPow3NoneOnly[Any, Any] | _SupportsPow3[Any, Any, Any] ) -if sys.version_info >= (3, 8): - # TODO: `pow(int, int, Literal[0])` fails at runtime, - # but adding a `NoReturn` overload isn't a good solution for expressing that (see #8566). - @overload - def pow(base: int, exp: int, mod: int) -> int: ... - @overload - def pow(base: int, exp: Literal[0], mod: None = None) -> Literal[1]: ... - @overload - def pow(base: int, exp: _PositiveInteger, mod: None = None) -> int: ... - @overload - def pow(base: int, exp: _NegativeInteger, mod: None = None) -> float: ... - # int base & positive-int exp -> int; int base & negative-int exp -> float - # return type must be Any as `int | float` causes too many false-positive errors - @overload - def pow(base: int, exp: int, mod: None = None) -> Any: ... - @overload - def pow(base: _PositiveInteger, exp: float, mod: None = None) -> float: ... - @overload - def pow(base: _NegativeInteger, exp: float, mod: None = None) -> complex: ... - @overload - def pow(base: float, exp: int, mod: None = None) -> float: ... - # float base & float exp could return float or complex - # return type must be Any (same as complex base, complex exp), - # as `float | complex` causes too many false-positive errors - @overload - def pow(base: float, exp: complex | _SupportsSomeKindOfPow, mod: None = None) -> Any: ... - @overload - def pow(base: complex, exp: complex | _SupportsSomeKindOfPow, mod: None = None) -> complex: ... - @overload - def pow(base: _SupportsPow2[_E, _T_co], exp: _E, mod: None = None) -> _T_co: ... - @overload - def pow(base: _SupportsPow3NoneOnly[_E, _T_co], exp: _E, mod: None = None) -> _T_co: ... - @overload - def pow(base: _SupportsPow3[_E, _M, _T_co], exp: _E, mod: _M) -> _T_co: ... - @overload - def pow(base: _SupportsSomeKindOfPow, exp: float, mod: None = None) -> Any: ... - @overload - def pow(base: _SupportsSomeKindOfPow, exp: complex, mod: None = None) -> complex: ... +# TODO: `pow(int, int, Literal[0])` fails at runtime, +# but adding a `NoReturn` overload isn't a good solution for expressing that (see #8566). +@overload +def pow(base: int, exp: int, mod: int) -> int: ... +@overload +def pow(base: int, exp: Literal[0], mod: None = None) -> Literal[1]: ... +@overload +def pow(base: int, exp: _PositiveInteger, mod: None = None) -> int: ... +@overload +def pow(base: int, exp: _NegativeInteger, mod: None = None) -> float: ... -else: - @overload - def pow(__x: int, __y: int, __z: int) -> int: ... - @overload - def pow(__x: int, __y: Literal[0], __z: None = None) -> Literal[1]: ... - @overload - def pow(__x: int, __y: _PositiveInteger, __z: None = None) -> int: ... - @overload - def pow(__x: int, __y: _NegativeInteger, __z: None = None) -> float: ... - @overload - def pow(__x: int, __y: int, __z: None = None) -> Any: ... - @overload - def pow(__x: _PositiveInteger, __y: float, __z: None = None) -> float: ... - @overload - def pow(__x: _NegativeInteger, __y: float, __z: None = None) -> complex: ... - @overload - def pow(__x: float, __y: int, __z: None = None) -> float: ... - @overload - def pow(__x: float, __y: complex | _SupportsSomeKindOfPow, __z: None = None) -> Any: ... - @overload - def pow(__x: complex, __y: complex | _SupportsSomeKindOfPow, __z: None = None) -> complex: ... - @overload - def pow(__x: _SupportsPow2[_E, _T_co], __y: _E, __z: None = None) -> _T_co: ... - @overload - def pow(__x: _SupportsPow3NoneOnly[_E, _T_co], __y: _E, __z: None = None) -> _T_co: ... - @overload - def pow(__x: _SupportsPow3[_E, _M, _T_co], __y: _E, __z: _M) -> _T_co: ... - @overload - def pow(__x: _SupportsSomeKindOfPow, __y: float, __z: None = None) -> Any: ... - @overload - def pow(__x: _SupportsSomeKindOfPow, __y: complex, __z: None = None) -> complex: ... +# int base & positive-int exp -> int; int base & negative-int exp -> float +# return type must be Any as `int | float` causes too many false-positive errors +@overload +def pow(base: int, exp: int, mod: None = None) -> Any: ... +@overload +def pow(base: _PositiveInteger, exp: float, mod: None = None) -> float: ... +@overload +def pow(base: _NegativeInteger, exp: float, mod: None = None) -> complex: ... +@overload +def pow(base: float, exp: int, mod: None = None) -> float: ... +# float base & float exp could return float or complex +# return type must be Any (same as complex base, complex exp), +# as `float | complex` causes too many false-positive errors +@overload +def pow(base: float, exp: complex | _SupportsSomeKindOfPow, mod: None = None) -> Any: ... +@overload +def pow(base: complex, exp: complex | _SupportsSomeKindOfPow, mod: None = None) -> complex: ... +@overload +def pow(base: _SupportsPow2[_E, _T_co], exp: _E, mod: None = None) -> _T_co: ... +@overload +def pow(base: _SupportsPow3NoneOnly[_E, _T_co], exp: _E, mod: None = None) -> _T_co: ... +@overload +def pow(base: _SupportsPow3[_E, _M, _T_co], exp: _E, mod: _M) -> _T_co: ... +@overload +def pow(base: _SupportsSomeKindOfPow, exp: float, mod: None = None) -> Any: ... +@overload +def pow(base: _SupportsSomeKindOfPow, exp: complex, mod: None = None) -> complex: ... def quit(code: sys._ExitCode = None) -> NoReturn: ... class reversed(Iterator[_T]): @@ -1700,24 +1679,12 @@ _SupportsSumNoDefaultT = TypeVar("_SupportsSumNoDefaultT", bound=_SupportsSumWit # However, we can't express that in the stub for `sum()` # without creating many false-positive errors (see #7578). # Instead, we special-case the most common examples of this: bool and literal integers. -if sys.version_info >= (3, 8): - @overload - def sum(__iterable: Iterable[bool], start: int = 0) -> int: ... # type: ignore[overload-overlap] - -else: - @overload - def sum(__iterable: Iterable[bool], __start: int = 0) -> int: ... # type: ignore[overload-overlap] - +@overload +def sum(__iterable: Iterable[bool | _LiteralInteger], start: int = 0) -> int: ... # type: ignore[overload-overlap] @overload def sum(__iterable: Iterable[_SupportsSumNoDefaultT]) -> _SupportsSumNoDefaultT | Literal[0]: ... - -if sys.version_info >= (3, 8): - @overload - def sum(__iterable: Iterable[_AddableT1], start: _AddableT2) -> _AddableT1 | _AddableT2: ... - -else: - @overload - def sum(__iterable: Iterable[_AddableT1], __start: _AddableT2) -> _AddableT1 | _AddableT2: ... +@overload +def sum(__iterable: Iterable[_AddableT1], start: _AddableT2) -> _AddableT1 | _AddableT2: ... # The argument to `vars()` has to have a `__dict__` attribute, so the second overload can't be annotated with `object` # (A "SupportsDunderDict" protocol doesn't work) @@ -1821,9 +1788,13 @@ def __import__( def __build_class__(__func: Callable[[], _Cell | Any], __name: str, *bases: Any, metaclass: Any = ..., **kwds: Any) -> Any: ... if sys.version_info >= (3, 10): - # In Python 3.10, EllipsisType is exposed publicly in the types module. - @final - class ellipsis: ... + from types import EllipsisType + + # Backwards compatibility hack for folks who relied on the ellipsis type + # existing in typeshed in Python 3.9 and earlier. + ellipsis = EllipsisType + + Ellipsis: EllipsisType else: # Actually the type of Ellipsis is , but since it's @@ -1832,7 +1803,7 @@ else: @type_check_only class ellipsis: ... -Ellipsis: ellipsis + Ellipsis: ellipsis class BaseException: args: tuple[Any, ...] diff --git a/mypy/typeshed/stdlib/bz2.pyi b/mypy/typeshed/stdlib/bz2.pyi index 9ad80ee6f731..620d59a6010c 100644 --- a/mypy/typeshed/stdlib/bz2.pyi +++ b/mypy/typeshed/stdlib/bz2.pyi @@ -3,8 +3,8 @@ import sys from _compression import BaseStream from _typeshed import ReadableBuffer, StrOrBytesPath, WriteableBuffer from collections.abc import Iterable -from typing import IO, Any, Protocol, TextIO, overload -from typing_extensions import Literal, Self, SupportsIndex, TypeAlias, final +from typing import IO, Any, Literal, Protocol, SupportsIndex, TextIO, final, overload +from typing_extensions import Self, TypeAlias __all__ = ["BZ2File", "BZ2Compressor", "BZ2Decompressor", "open", "compress", "decompress"] diff --git a/mypy/typeshed/stdlib/cProfile.pyi b/mypy/typeshed/stdlib/cProfile.pyi index 8945b21427ab..7d97fa22c394 100644 --- a/mypy/typeshed/stdlib/cProfile.pyi +++ b/mypy/typeshed/stdlib/cProfile.pyi @@ -1,4 +1,3 @@ -import sys from _typeshed import StrOrBytesPath, Unused from collections.abc import Callable from types import CodeType @@ -30,8 +29,7 @@ class Profile: def run(self, cmd: str) -> Self: ... def runctx(self, cmd: str, globals: dict[str, Any], locals: dict[str, Any]) -> Self: ... def runcall(self, __func: Callable[_P, _T], *args: _P.args, **kw: _P.kwargs) -> _T: ... - if sys.version_info >= (3, 8): - def __enter__(self) -> Self: ... - def __exit__(self, *exc_info: Unused) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *exc_info: Unused) -> None: ... def label(code: str | CodeType) -> _Label: ... # undocumented diff --git a/mypy/typeshed/stdlib/calendar.pyi b/mypy/typeshed/stdlib/calendar.pyi index 3f881393e99f..cac39a498ac9 100644 --- a/mypy/typeshed/stdlib/calendar.pyi +++ b/mypy/typeshed/stdlib/calendar.pyi @@ -4,8 +4,8 @@ import sys from _typeshed import Unused from collections.abc import Iterable, Sequence from time import struct_time -from typing import ClassVar -from typing_extensions import Literal, TypeAlias +from typing import ClassVar, Literal +from typing_extensions import TypeAlias __all__ = [ "IllegalMonthError", diff --git a/mypy/typeshed/stdlib/cgi.pyi b/mypy/typeshed/stdlib/cgi.pyi index 21bf8ca25394..91179c2ed8d5 100644 --- a/mypy/typeshed/stdlib/cgi.pyi +++ b/mypy/typeshed/stdlib/cgi.pyi @@ -1,4 +1,3 @@ -import sys from _typeshed import SupportsGetItem, SupportsItemAccess, Unused from builtins import list as _list, type as _type from collections.abc import Iterable, Iterator, Mapping @@ -22,9 +21,6 @@ __all__ = [ "print_environ_usage", ] -if sys.version_info < (3, 8): - __all__ += ["parse_qs", "parse_qsl", "escape"] - def parse( fp: IO[Any] | None = None, environ: SupportsItemAccess[str, str] = ..., @@ -32,11 +28,6 @@ def parse( strict_parsing: bool = ..., separator: str = "&", ) -> dict[str, list[str]]: ... - -if sys.version_info < (3, 8): - def parse_qs(qs: str, keep_blank_values: bool = ..., strict_parsing: bool = ...) -> dict[str, list[str]]: ... - def parse_qsl(qs: str, keep_blank_values: bool = ..., strict_parsing: bool = ...) -> list[tuple[str, str]]: ... - def parse_multipart( fp: IO[Any], pdict: SupportsGetItem[str, bytes], encoding: str = "utf-8", errors: str = "replace", separator: str = "&" ) -> dict[str, list[Any]]: ... @@ -52,9 +43,6 @@ def print_form(form: dict[str, Any]) -> None: ... def print_directory() -> None: ... def print_environ_usage() -> None: ... -if sys.version_info < (3, 8): - def escape(s: str, quote: bool | None = None) -> str: ... - class MiniFieldStorage: # The first five "Any" attributes here are always None, but mypy doesn't support that filename: Any diff --git a/mypy/typeshed/stdlib/cgitb.pyi b/mypy/typeshed/stdlib/cgitb.pyi index 4c315bf6ca39..565725801159 100644 --- a/mypy/typeshed/stdlib/cgitb.pyi +++ b/mypy/typeshed/stdlib/cgitb.pyi @@ -1,8 +1,7 @@ from _typeshed import OptExcInfo, StrOrBytesPath from collections.abc import Callable from types import FrameType, TracebackType -from typing import IO, Any -from typing_extensions import Final +from typing import IO, Any, Final __UNDEF__: Final[object] # undocumented sentinel diff --git a/mypy/typeshed/stdlib/cmath.pyi b/mypy/typeshed/stdlib/cmath.pyi index 658cfb2d40ed..8aad19dafcfb 100644 --- a/mypy/typeshed/stdlib/cmath.pyi +++ b/mypy/typeshed/stdlib/cmath.pyi @@ -1,10 +1,6 @@ -import sys -from typing import SupportsComplex, SupportsFloat +from typing import SupportsComplex, SupportsFloat, SupportsIndex from typing_extensions import TypeAlias -if sys.version_info >= (3, 8): - from typing import SupportsIndex - e: float pi: float inf: float @@ -13,10 +9,7 @@ nan: float nanj: complex tau: float -if sys.version_info >= (3, 8): - _C: TypeAlias = SupportsFloat | SupportsComplex | SupportsIndex | complex -else: - _C: TypeAlias = SupportsFloat | SupportsComplex | complex +_C: TypeAlias = SupportsFloat | SupportsComplex | SupportsIndex | complex def acos(__z: _C) -> complex: ... def acosh(__z: _C) -> complex: ... diff --git a/mypy/typeshed/stdlib/cmd.pyi b/mypy/typeshed/stdlib/cmd.pyi index b658a873410b..9499847fb153 100644 --- a/mypy/typeshed/stdlib/cmd.pyi +++ b/mypy/typeshed/stdlib/cmd.pyi @@ -1,6 +1,5 @@ from collections.abc import Callable -from typing import IO, Any -from typing_extensions import Literal +from typing import IO, Any, Literal __all__ = ["Cmd"] diff --git a/mypy/typeshed/stdlib/codecs.pyi b/mypy/typeshed/stdlib/codecs.pyi index 985a52702bc8..7e192d91ddc5 100644 --- a/mypy/typeshed/stdlib/codecs.pyi +++ b/mypy/typeshed/stdlib/codecs.pyi @@ -1,11 +1,10 @@ -import sys import types from _codecs import * from _typeshed import ReadableBuffer from abc import abstractmethod from collections.abc import Callable, Generator, Iterable -from typing import Any, BinaryIO, Protocol, TextIO -from typing_extensions import Literal, Self +from typing import Any, BinaryIO, Literal, Protocol, TextIO +from typing_extensions import Self __all__ = [ "register", @@ -129,17 +128,9 @@ def getincrementalencoder(encoding: str) -> _IncrementalEncoder: ... def getincrementaldecoder(encoding: str) -> _IncrementalDecoder: ... def getreader(encoding: str) -> _StreamReader: ... def getwriter(encoding: str) -> _StreamWriter: ... - -if sys.version_info >= (3, 8): - def open( - filename: str, mode: str = "r", encoding: str | None = None, errors: str = "strict", buffering: int = -1 - ) -> StreamReaderWriter: ... - -else: - def open( - filename: str, mode: str = "r", encoding: str | None = None, errors: str = "strict", buffering: int = 1 - ) -> StreamReaderWriter: ... - +def open( + filename: str, mode: str = "r", encoding: str | None = None, errors: str = "strict", buffering: int = -1 +) -> StreamReaderWriter: ... def EncodedFile(file: _Stream, data_encoding: str, file_encoding: str | None = None, errors: str = "strict") -> StreamRecoder: ... def iterencode(iterator: Iterable[str], encoding: str, errors: str = "strict") -> Generator[bytes, None, None]: ... def iterdecode(iterator: Iterable[bytes], encoding: str, errors: str = "strict") -> Generator[str, None, None]: ... diff --git a/mypy/typeshed/stdlib/collections/__init__.pyi b/mypy/typeshed/stdlib/collections/__init__.pyi index 955681c6ac0c..0df800a4a3be 100644 --- a/mypy/typeshed/stdlib/collections/__init__.pyi +++ b/mypy/typeshed/stdlib/collections/__init__.pyi @@ -1,8 +1,8 @@ import sys from _collections_abc import dict_items, dict_keys, dict_values from _typeshed import SupportsItems, SupportsKeysAndGetItem, SupportsRichComparison, SupportsRichComparisonT -from typing import Any, Generic, NoReturn, TypeVar, overload -from typing_extensions import Self, SupportsIndex, final +from typing import Any, Generic, NoReturn, SupportsIndex, TypeVar, final, overload +from typing_extensions import Self if sys.version_info >= (3, 9): from types import GenericAlias @@ -169,20 +169,12 @@ class UserString(Sequence[UserString]): def __mul__(self, n: int) -> Self: ... def __rmul__(self, n: int) -> Self: ... def __mod__(self, args: Any) -> Self: ... - if sys.version_info >= (3, 8): - def __rmod__(self, template: object) -> Self: ... - else: - def __rmod__(self, format: Any) -> Self: ... - + def __rmod__(self, template: object) -> Self: ... def capitalize(self) -> Self: ... def casefold(self) -> Self: ... def center(self, width: int, *args: Any) -> Self: ... def count(self, sub: str | UserString, start: int = 0, end: int = sys.maxsize) -> int: ... - if sys.version_info >= (3, 8): - def encode(self: UserString, encoding: str | None = "utf-8", errors: str | None = "strict") -> bytes: ... - else: - def encode(self, encoding: str | None = None, errors: str | None = None) -> Self: ... - + def encode(self: UserString, encoding: str | None = "utf-8", errors: str | None = "strict") -> bytes: ... def endswith(self, suffix: str | tuple[str, ...], start: int | None = 0, end: int | None = sys.maxsize) -> bool: ... def expandtabs(self, tabsize: int = 8) -> Self: ... def find(self, sub: str | UserString, start: int = 0, end: int = sys.maxsize) -> int: ... diff --git a/mypy/typeshed/stdlib/concurrent/futures/__init__.pyi b/mypy/typeshed/stdlib/concurrent/futures/__init__.pyi index ff2e72bbf4fb..07314ce9d402 100644 --- a/mypy/typeshed/stdlib/concurrent/futures/__init__.pyi +++ b/mypy/typeshed/stdlib/concurrent/futures/__init__.pyi @@ -1,5 +1,3 @@ -import sys - from ._base import ( ALL_COMPLETED as ALL_COMPLETED, FIRST_COMPLETED as FIRST_COMPLETED, @@ -8,6 +6,7 @@ from ._base import ( CancelledError as CancelledError, Executor as Executor, Future as Future, + InvalidStateError as InvalidStateError, TimeoutError as TimeoutError, as_completed as as_completed, wait as wait, @@ -15,9 +14,6 @@ from ._base import ( from .process import ProcessPoolExecutor as ProcessPoolExecutor from .thread import ThreadPoolExecutor as ThreadPoolExecutor -if sys.version_info >= (3, 8): - from ._base import InvalidStateError as InvalidStateError - __all__ = ( "FIRST_COMPLETED", "FIRST_EXCEPTION", diff --git a/mypy/typeshed/stdlib/concurrent/futures/_base.pyi b/mypy/typeshed/stdlib/concurrent/futures/_base.pyi index 8a11f47e5670..9ea4d5dff6fb 100644 --- a/mypy/typeshed/stdlib/concurrent/futures/_base.pyi +++ b/mypy/typeshed/stdlib/concurrent/futures/_base.pyi @@ -4,8 +4,8 @@ from _typeshed import Unused from collections.abc import Callable, Iterable, Iterator from logging import Logger from types import TracebackType -from typing import Any, Generic, NamedTuple, TypeVar -from typing_extensions import Literal, ParamSpec, Self +from typing import Any, Generic, Literal, NamedTuple, Protocol, TypeVar +from typing_extensions import ParamSpec, Self if sys.version_info >= (3, 9): from types import GenericAlias @@ -30,15 +30,19 @@ if sys.version_info >= (3, 11): else: class TimeoutError(Error): ... -if sys.version_info >= (3, 8): - class InvalidStateError(Error): ... - +class InvalidStateError(Error): ... class BrokenExecutor(RuntimeError): ... _T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) _P = ParamSpec("_P") class Future(Generic[_T]): + _condition: threading.Condition + _state: str + _result: _T | None + _exception: BaseException | None + _waiters: list[_Waiter] def cancel(self) -> bool: ... def cancelled(self) -> bool: ... def running(self) -> bool: ... @@ -71,7 +75,17 @@ class Executor: self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> bool | None: ... -def as_completed(fs: Iterable[Future[_T]], timeout: float | None = None) -> Iterator[Future[_T]]: ... +class _AsCompletedFuture(Protocol[_T_co]): + # as_completed only mutates non-generic aspects of passed Futures and does not do any nominal + # checks. Therefore, we can use a Protocol here to allow as_completed to act covariantly. + # See the tests for concurrent.futures + _condition: threading.Condition + _state: str + _waiters: list[_Waiter] + # Not used by as_completed, but needed to propagate the generic type + def result(self, timeout: float | None = None) -> _T_co: ... + +def as_completed(fs: Iterable[_AsCompletedFuture[_T]], timeout: float | None = None) -> Iterator[Future[_T]]: ... class DoneAndNotDoneFutures(NamedTuple, Generic[_T]): done: set[Future[_T]] diff --git a/mypy/typeshed/stdlib/configparser.pyi b/mypy/typeshed/stdlib/configparser.pyi index e6fedb0328c2..07b57b17d56d 100644 --- a/mypy/typeshed/stdlib/configparser.pyi +++ b/mypy/typeshed/stdlib/configparser.pyi @@ -2,8 +2,8 @@ import sys from _typeshed import StrOrBytesPath, SupportsWrite from collections.abc import Callable, ItemsView, Iterable, Iterator, Mapping, MutableMapping, Sequence from re import Pattern -from typing import Any, ClassVar, TypeVar, overload -from typing_extensions import Literal, TypeAlias +from typing import Any, ClassVar, Literal, TypeVar, overload +from typing_extensions import TypeAlias if sys.version_info >= (3, 12): __all__ = ( diff --git a/mypy/typeshed/stdlib/contextvars.pyi b/mypy/typeshed/stdlib/contextvars.pyi index 825c018d580f..3245cdd5dad2 100644 --- a/mypy/typeshed/stdlib/contextvars.pyi +++ b/mypy/typeshed/stdlib/contextvars.pyi @@ -1,7 +1,7 @@ import sys from collections.abc import Callable, Iterator, Mapping -from typing import Any, ClassVar, Generic, TypeVar, overload -from typing_extensions import ParamSpec, final +from typing import Any, ClassVar, Generic, TypeVar, final, overload +from typing_extensions import ParamSpec if sys.version_info >= (3, 9): from types import GenericAlias diff --git a/mypy/typeshed/stdlib/csv.pyi b/mypy/typeshed/stdlib/csv.pyi index f48d9d2ff263..56f8bf029b12 100644 --- a/mypy/typeshed/stdlib/csv.pyi +++ b/mypy/typeshed/stdlib/csv.pyi @@ -24,15 +24,11 @@ from _csv import ( if sys.version_info >= (3, 12): from _csv import QUOTE_NOTNULL as QUOTE_NOTNULL, QUOTE_STRINGS as QUOTE_STRINGS + from _typeshed import SupportsWrite from collections.abc import Collection, Iterable, Iterator, Mapping, Sequence -from typing import Any, Generic, TypeVar, overload -from typing_extensions import Literal, Self - -if sys.version_info >= (3, 8): - from builtins import dict as _DictReadMapping -else: - from collections import OrderedDict as _DictReadMapping +from typing import Any, Generic, Literal, TypeVar, overload +from typing_extensions import Self if sys.version_info >= (3, 12): from types import GenericAlias @@ -69,7 +65,7 @@ class excel(Dialect): ... class excel_tab(excel): ... class unix_dialect(Dialect): ... -class DictReader(Iterator[_DictReadMapping[_T | Any, str | Any]], Generic[_T]): +class DictReader(Iterator[dict[_T | Any, str | Any]], Generic[_T]): fieldnames: Sequence[_T] | None restkey: _T | None restval: str | Any | None @@ -113,7 +109,7 @@ class DictReader(Iterator[_DictReadMapping[_T | Any, str | Any]], Generic[_T]): strict: bool = False, ) -> None: ... def __iter__(self) -> Self: ... - def __next__(self) -> _DictReadMapping[_T | Any, str | Any]: ... + def __next__(self) -> dict[_T | Any, str | Any]: ... if sys.version_info >= (3, 12): def __class_getitem__(cls, item: Any) -> GenericAlias: ... @@ -139,11 +135,7 @@ class DictWriter(Generic[_T]): quoting: _QuotingType = 0, strict: bool = False, ) -> None: ... - if sys.version_info >= (3, 8): - def writeheader(self) -> Any: ... - else: - def writeheader(self) -> None: ... - + def writeheader(self) -> Any: ... def writerow(self, rowdict: Mapping[_T, Any]) -> Any: ... def writerows(self, rowdicts: Iterable[Mapping[_T, Any]]) -> None: ... if sys.version_info >= (3, 12): diff --git a/mypy/typeshed/stdlib/ctypes/__init__.pyi b/mypy/typeshed/stdlib/ctypes/__init__.pyi index b14fb93c8163..2fe551fa9dc2 100644 --- a/mypy/typeshed/stdlib/ctypes/__init__.pyi +++ b/mypy/typeshed/stdlib/ctypes/__init__.pyi @@ -3,7 +3,6 @@ from _ctypes import ( POINTER as POINTER, RTLD_GLOBAL as RTLD_GLOBAL, RTLD_LOCAL as RTLD_LOCAL, - ArgumentError as ArgumentError, Array as Array, CFuncPtr as _CFuncPtr, Structure as Structure, @@ -27,12 +26,16 @@ from _ctypes import ( set_errno as set_errno, sizeof as sizeof, ) +from ctypes._endian import BigEndianStructure as BigEndianStructure, LittleEndianStructure as LittleEndianStructure from typing import Any, ClassVar, Generic, TypeVar from typing_extensions import TypeAlias if sys.platform == "win32": from _ctypes import FormatError as FormatError, get_last_error as get_last_error, set_last_error as set_last_error +if sys.version_info >= (3, 11): + from ctypes._endian import BigEndianUnion as BigEndianUnion, LittleEndianUnion as LittleEndianUnion + if sys.version_info >= (3, 9): from types import GenericAlias @@ -41,32 +44,23 @@ _DLLT = TypeVar("_DLLT", bound=CDLL) DEFAULT_MODE: int +class ArgumentError(Exception): ... + class CDLL: _func_flags_: ClassVar[int] _func_restype_: ClassVar[_CData] _name: str _handle: int _FuncPtr: type[_FuncPointer] - if sys.version_info >= (3, 8): - def __init__( - self, - name: str | None, - mode: int = ..., - handle: int | None = None, - use_errno: bool = False, - use_last_error: bool = False, - winmode: int | None = None, - ) -> None: ... - else: - def __init__( - self, - name: str | None, - mode: int = ..., - handle: int | None = None, - use_errno: bool = False, - use_last_error: bool = False, - ) -> None: ... - + def __init__( + self, + name: str | None, + mode: int = ..., + handle: int | None = None, + use_errno: bool = False, + use_last_error: bool = False, + winmode: int | None = None, + ) -> None: ... def __getattr__(self, name: str) -> _NamedFuncPointer: ... def __getitem__(self, name_or_ordinal: str) -> _NamedFuncPointer: ... @@ -148,30 +142,36 @@ 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]): ... +class c_longdouble(_SimpleCData[float]): ... # can be an alias for c_double class c_float(_SimpleCData[float]): ... -class c_int(_SimpleCData[int]): ... -class c_int8(_SimpleCData[int]): ... -class c_int16(_SimpleCData[int]): ... -class c_int32(_SimpleCData[int]): ... -class c_int64(_SimpleCData[int]): ... +class c_int(_SimpleCData[int]): ... # can be an alias for c_long class c_long(_SimpleCData[int]): ... -class c_longlong(_SimpleCData[int]): ... +class c_longlong(_SimpleCData[int]): ... # can be an alias for c_long class c_short(_SimpleCData[int]): ... -class c_size_t(_SimpleCData[int]): ... -class c_ssize_t(_SimpleCData[int]): ... +class c_size_t(_SimpleCData[int]): ... # alias for c_uint, c_ulong, or c_ulonglong +class c_ssize_t(_SimpleCData[int]): ... # alias for c_int, c_long, or c_longlong class c_ubyte(_SimpleCData[int]): ... -class c_uint(_SimpleCData[int]): ... -class c_uint8(_SimpleCData[int]): ... -class c_uint16(_SimpleCData[int]): ... -class c_uint32(_SimpleCData[int]): ... -class c_uint64(_SimpleCData[int]): ... +class c_uint(_SimpleCData[int]): ... # can be an alias for c_ulong class c_ulong(_SimpleCData[int]): ... -class c_ulonglong(_SimpleCData[int]): ... +class c_ulonglong(_SimpleCData[int]): ... # can be an alias for c_ulong class c_ushort(_SimpleCData[int]): ... class c_void_p(_PointerLike, _SimpleCData[int | None]): ... class c_wchar(_SimpleCData[str]): ... +c_int8 = c_byte + +# these are actually dynamic aliases for c_short, c_int, c_long, or c_longlong +class c_int16(_SimpleCData[int]): ... +class c_int32(_SimpleCData[int]): ... +class c_int64(_SimpleCData[int]): ... + +c_uint8 = c_ubyte + +# these are actually dynamic aliases for c_ushort, c_uint, c_ulong, or c_ulonglong +class c_uint16(_SimpleCData[int]): ... +class c_uint32(_SimpleCData[int]): ... +class c_uint64(_SimpleCData[int]): ... + class c_wchar_p(_PointerLike, _SimpleCData[str | None]): def __init__(self, value: int | str | None = ...) -> None: ... @@ -182,8 +182,6 @@ if sys.platform == "win32": class HRESULT(_SimpleCData[int]): ... # TODO undocumented if sys.version_info >= (3, 12): - c_time_t: type[c_int32 | c_int64] + c_time_t: type[c_int32 | c_int64] # alias for one or the other at runtime class py_object(_CanCastTo, _SimpleCData[_T]): ... -class BigEndianStructure(Structure): ... -class LittleEndianStructure(Structure): ... diff --git a/mypy/typeshed/stdlib/ctypes/_endian.pyi b/mypy/typeshed/stdlib/ctypes/_endian.pyi new file mode 100644 index 000000000000..add6365e615f --- /dev/null +++ b/mypy/typeshed/stdlib/ctypes/_endian.pyi @@ -0,0 +1,19 @@ +import sys +from _ctypes import RTLD_GLOBAL as RTLD_GLOBAL, RTLD_LOCAL as RTLD_LOCAL, Structure, Union +from ctypes import DEFAULT_MODE as DEFAULT_MODE, cdll as cdll, pydll as pydll, pythonapi as pythonapi + +if sys.version_info >= (3, 12): + from _ctypes import SIZEOF_TIME_T as SIZEOF_TIME_T + +if sys.platform == "win32": + from ctypes import oledll as oledll, windll as windll + +# At runtime, the native endianness is an alias for Structure, +# while the other is a subclass with a metaclass added in. +class BigEndianStructure(Structure): ... +class LittleEndianStructure(Structure): ... + +# Same thing for these: one is an alias of Union at runtime +if sys.version_info >= (3, 11): + class BigEndianUnion(Union): ... + class LittleEndianUnion(Union): ... diff --git a/mypy/typeshed/stdlib/ctypes/wintypes.pyi b/mypy/typeshed/stdlib/ctypes/wintypes.pyi index 84c9c9157a88..8847860f2002 100644 --- a/mypy/typeshed/stdlib/ctypes/wintypes.pyi +++ b/mypy/typeshed/stdlib/ctypes/wintypes.pyi @@ -186,53 +186,113 @@ class WIN32_FIND_DATAW(Structure): cFileName: _CField[Array[WCHAR], str, str] cAlternateFileName: _CField[Array[WCHAR], str, str] -class PBOOL(_Pointer[BOOL]): ... -class LPBOOL(_Pointer[BOOL]): ... -class PBOOLEAN(_Pointer[BOOLEAN]): ... +# These are all defined with the POINTER() function, which keeps a cache and will +# return a previously created class if it can. The self-reported __name__ +# of these classes is f"LP_{typ.__name__}", where typ is the original class +# passed in to the POINTER() function. + +# LP_c_short +class PSHORT(_Pointer[SHORT]): ... + +# LP_c_ushort +class PUSHORT(_Pointer[USHORT]): ... + +PWORD = PUSHORT +LPWORD = PUSHORT + +# LP_c_long +class PLONG(_Pointer[LONG]): ... + +LPLONG = PLONG +PBOOL = PLONG +LPBOOL = PLONG + +# LP_c_ulong +class PULONG(_Pointer[ULONG]): ... + +PDWORD = PULONG +LPDWORD = PDWORD +LPCOLORREF = PDWORD +PLCID = PDWORD + +# LP_c_int (or LP_c_long if int and long have the same size) +class PINT(_Pointer[INT]): ... + +LPINT = PINT + +# LP_c_uint (or LP_c_ulong if int and long have the same size) +class PUINT(_Pointer[UINT]): ... + +LPUINT = PUINT + +# LP_c_float +class PFLOAT(_Pointer[FLOAT]): ... + +# LP_c_longlong (or LP_c_long if long and long long have the same size) +class PLARGE_INTEGER(_Pointer[LARGE_INTEGER]): ... + +# LP_c_ulonglong (or LP_c_ulong if long and long long have the same size) +class PULARGE_INTEGER(_Pointer[ULARGE_INTEGER]): ... + +# LP_c_byte types class PBYTE(_Pointer[BYTE]): ... -class LPBYTE(_Pointer[BYTE]): ... + +LPBYTE = PBYTE +PBOOLEAN = PBYTE + +# LP_c_char class PCHAR(_Pointer[CHAR]): ... -class LPCOLORREF(_Pointer[COLORREF]): ... -class PDWORD(_Pointer[DWORD]): ... -class LPDWORD(_Pointer[DWORD]): ... -class PFILETIME(_Pointer[FILETIME]): ... -class LPFILETIME(_Pointer[FILETIME]): ... -class PFLOAT(_Pointer[FLOAT]): ... + +# LP_c_wchar +class PWCHAR(_Pointer[WCHAR]): ... + +# LP_c_void_p class PHANDLE(_Pointer[HANDLE]): ... -class LPHANDLE(_Pointer[HANDLE]): ... -class PHKEY(_Pointer[HKEY]): ... -class LPHKL(_Pointer[HKL]): ... -class PINT(_Pointer[INT]): ... -class LPINT(_Pointer[INT]): ... -class PLARGE_INTEGER(_Pointer[LARGE_INTEGER]): ... -class PLCID(_Pointer[LCID]): ... -class PLONG(_Pointer[LONG]): ... -class LPLONG(_Pointer[LONG]): ... + +LPHANDLE = PHANDLE +PHKEY = PHANDLE +LPHKL = PHANDLE +LPSC_HANDLE = PHANDLE + +# LP_FILETIME +class PFILETIME(_Pointer[FILETIME]): ... + +LPFILETIME = PFILETIME + +# LP_MSG class PMSG(_Pointer[MSG]): ... -class LPMSG(_Pointer[MSG]): ... + +LPMSG = PMSG + +# LP_POINT class PPOINT(_Pointer[POINT]): ... -class LPPOINT(_Pointer[POINT]): ... -class PPOINTL(_Pointer[POINTL]): ... + +LPPOINT = PPOINT +PPOINTL = PPOINT + +# LP_RECT class PRECT(_Pointer[RECT]): ... -class LPRECT(_Pointer[RECT]): ... -class PRECTL(_Pointer[RECTL]): ... -class LPRECTL(_Pointer[RECTL]): ... -class LPSC_HANDLE(_Pointer[SC_HANDLE]): ... -class PSHORT(_Pointer[SHORT]): ... + +LPRECT = PRECT +PRECTL = PRECT +LPRECTL = PRECT + +# LP_SIZE class PSIZE(_Pointer[SIZE]): ... -class LPSIZE(_Pointer[SIZE]): ... -class PSIZEL(_Pointer[SIZEL]): ... -class LPSIZEL(_Pointer[SIZEL]): ... + +LPSIZE = PSIZE +PSIZEL = PSIZE +LPSIZEL = PSIZE + +# LP__SMALL_RECT class PSMALL_RECT(_Pointer[SMALL_RECT]): ... -class PUINT(_Pointer[UINT]): ... -class LPUINT(_Pointer[UINT]): ... -class PULARGE_INTEGER(_Pointer[ULARGE_INTEGER]): ... -class PULONG(_Pointer[ULONG]): ... -class PUSHORT(_Pointer[USHORT]): ... -class PWCHAR(_Pointer[WCHAR]): ... + +# LP_WIN32_FIND_DATAA class PWIN32_FIND_DATAA(_Pointer[WIN32_FIND_DATAA]): ... -class LPWIN32_FIND_DATAA(_Pointer[WIN32_FIND_DATAA]): ... + +LPWIN32_FIND_DATAA = PWIN32_FIND_DATAA + +# LP_WIN32_FIND_DATAW class PWIN32_FIND_DATAW(_Pointer[WIN32_FIND_DATAW]): ... -class LPWIN32_FIND_DATAW(_Pointer[WIN32_FIND_DATAW]): ... -class PWORD(_Pointer[WORD]): ... -class LPWORD(_Pointer[WORD]): ... + +LPWIN32_FIND_DATAW = PWIN32_FIND_DATAW diff --git a/mypy/typeshed/stdlib/dataclasses.pyi b/mypy/typeshed/stdlib/dataclasses.pyi index 13cffcd70c0e..389a159a915f 100644 --- a/mypy/typeshed/stdlib/dataclasses.pyi +++ b/mypy/typeshed/stdlib/dataclasses.pyi @@ -4,8 +4,8 @@ import types from _typeshed import DataclassInstance from builtins import type as Type # alias to avoid name clashes with fields named "type" from collections.abc import Callable, Iterable, Mapping -from typing import Any, Generic, Protocol, TypeVar, overload -from typing_extensions import Literal, TypeAlias, TypeGuard +from typing import Any, Generic, Literal, Protocol, TypeVar, overload +from typing_extensions import TypeAlias, TypeGuard if sys.version_info >= (3, 9): from types import GenericAlias @@ -54,19 +54,10 @@ def asdict(obj: DataclassInstance, *, dict_factory: Callable[[list[tuple[str, An def astuple(obj: DataclassInstance) -> tuple[Any, ...]: ... @overload def astuple(obj: DataclassInstance, *, tuple_factory: Callable[[list[Any]], _T]) -> _T: ... - -if sys.version_info >= (3, 8): - # cls argument is now positional-only - @overload - def dataclass(__cls: None) -> Callable[[type[_T]], type[_T]]: ... - @overload - def dataclass(__cls: type[_T]) -> type[_T]: ... - -else: - @overload - def dataclass(_cls: None) -> Callable[[type[_T]], type[_T]]: ... - @overload - def dataclass(_cls: type[_T]) -> type[_T]: ... +@overload +def dataclass(__cls: None) -> Callable[[type[_T]], type[_T]]: ... +@overload +def dataclass(__cls: type[_T]) -> type[_T]: ... if sys.version_info >= (3, 11): @overload diff --git a/mypy/typeshed/stdlib/datetime.pyi b/mypy/typeshed/stdlib/datetime.pyi index 36577c5b7e1b..54ecddec3a9a 100644 --- a/mypy/typeshed/stdlib/datetime.pyi +++ b/mypy/typeshed/stdlib/datetime.pyi @@ -1,8 +1,8 @@ import sys from abc import abstractmethod from time import struct_time -from typing import ClassVar, NamedTuple, NoReturn, TypeVar, overload -from typing_extensions import Literal, Self, SupportsIndex, TypeAlias, final +from typing import ClassVar, Literal, NamedTuple, NoReturn, SupportsIndex, TypeVar, final, overload +from typing_extensions import Self, TypeAlias if sys.version_info >= (3, 11): __all__ = ("date", "datetime", "time", "timedelta", "timezone", "tzinfo", "MINYEAR", "MAXYEAR", "UTC") @@ -60,10 +60,8 @@ class date: def fromordinal(cls, __n: int) -> Self: ... @classmethod def fromisoformat(cls, __date_string: str) -> Self: ... - if sys.version_info >= (3, 8): - @classmethod - def fromisocalendar(cls, year: int, week: int, day: int) -> Self: ... - + @classmethod + def fromisocalendar(cls, year: int, week: int, day: int) -> Self: ... @property def year(self) -> int: ... @property @@ -89,26 +87,14 @@ class date: def __ge__(self, __value: date) -> bool: ... def __gt__(self, __value: date) -> bool: ... def __eq__(self, __value: object) -> bool: ... - if sys.version_info >= (3, 8): - def __add__(self, __value: timedelta) -> Self: ... - def __radd__(self, __value: timedelta) -> Self: ... - @overload - def __sub__(self, __value: timedelta) -> Self: ... - @overload - def __sub__(self, __value: datetime) -> NoReturn: ... - @overload - def __sub__(self: _D, __value: _D) -> timedelta: ... - else: - # Prior to Python 3.8, arithmetic operations always returned `date`, even in subclasses - def __add__(self, __value: timedelta) -> date: ... - def __radd__(self, __value: timedelta) -> date: ... - @overload - def __sub__(self, __value: timedelta) -> date: ... - @overload - def __sub__(self, __value: datetime) -> NoReturn: ... - @overload - def __sub__(self, __value: date) -> timedelta: ... - + def __add__(self, __value: timedelta) -> Self: ... + def __radd__(self, __value: timedelta) -> Self: ... + @overload + def __sub__(self, __value: timedelta) -> Self: ... + @overload + def __sub__(self, __value: datetime) -> NoReturn: ... + @overload + def __sub__(self: _D, __value: _D) -> timedelta: ... def __hash__(self) -> int: ... def weekday(self) -> int: ... def isoweekday(self) -> int: ... @@ -266,17 +252,8 @@ class datetime(date): @classmethod def utcfromtimestamp(cls, __t: float) -> Self: ... - if sys.version_info >= (3, 8): - @classmethod - def now(cls, tz: _TzInfo | None = None) -> Self: ... - else: - @overload - @classmethod - def now(cls, tz: None = None) -> Self: ... - @overload - @classmethod - def now(cls, tz: _TzInfo) -> datetime: ... - + @classmethod + def now(cls, tz: _TzInfo | None = None) -> Self: ... @classmethod def utcnow(cls) -> Self: ... @classmethod @@ -299,11 +276,7 @@ class datetime(date): *, fold: int = ..., ) -> Self: ... - if sys.version_info >= (3, 8): - def astimezone(self, tz: _TzInfo | None = ...) -> Self: ... - else: - def astimezone(self, tz: _TzInfo | None = ...) -> datetime: ... - + def astimezone(self, tz: _TzInfo | None = ...) -> Self: ... def isoformat(self, sep: str = ..., timespec: str = ...) -> str: ... @classmethod def strptime(cls, __date_string: str, __format: str) -> Self: ... @@ -316,16 +289,7 @@ class datetime(date): def __gt__(self, __value: datetime) -> bool: ... # type: ignore[override] def __eq__(self, __value: object) -> bool: ... def __hash__(self) -> int: ... - if sys.version_info >= (3, 8): - @overload # type: ignore[override] - def __sub__(self, __value: timedelta) -> Self: ... - @overload - def __sub__(self: _D, __value: _D) -> timedelta: ... - else: - # Prior to Python 3.8, arithmetic operations always returned `datetime`, even in subclasses - def __add__(self, __value: timedelta) -> datetime: ... - def __radd__(self, __value: timedelta) -> datetime: ... - @overload # type: ignore[override] - def __sub__(self, __value: datetime) -> timedelta: ... - @overload - def __sub__(self, __value: timedelta) -> datetime: ... + @overload # type: ignore[override] + def __sub__(self, __value: timedelta) -> Self: ... + @overload + def __sub__(self: _D, __value: _D) -> timedelta: ... diff --git a/mypy/typeshed/stdlib/dbm/__init__.pyi b/mypy/typeshed/stdlib/dbm/__init__.pyi index d7115528868b..9c6989a1c151 100644 --- a/mypy/typeshed/stdlib/dbm/__init__.pyi +++ b/mypy/typeshed/stdlib/dbm/__init__.pyi @@ -1,6 +1,7 @@ from collections.abc import Iterator, MutableMapping from types import TracebackType -from typing_extensions import Literal, Self, TypeAlias +from typing import Literal +from typing_extensions import Self, TypeAlias __all__ = ["open", "whichdb", "error"] diff --git a/mypy/typeshed/stdlib/distutils/ccompiler.pyi b/mypy/typeshed/stdlib/distutils/ccompiler.pyi index e7277aa3f9c4..cc097728f77c 100644 --- a/mypy/typeshed/stdlib/distutils/ccompiler.pyi +++ b/mypy/typeshed/stdlib/distutils/ccompiler.pyi @@ -56,7 +56,7 @@ class CCompiler: self, sources: list[str], output_dir: str | None = None, - macros: _Macro | None = None, + macros: list[_Macro] | None = None, include_dirs: list[str] | None = None, debug: bool = ..., extra_preargs: list[str] | None = None, diff --git a/mypy/typeshed/stdlib/distutils/cygwinccompiler.pyi b/mypy/typeshed/stdlib/distutils/cygwinccompiler.pyi index a990c3e28f36..5f2e623eeff6 100644 --- a/mypy/typeshed/stdlib/distutils/cygwinccompiler.pyi +++ b/mypy/typeshed/stdlib/distutils/cygwinccompiler.pyi @@ -1,7 +1,7 @@ from distutils.unixccompiler import UnixCCompiler from distutils.version import LooseVersion from re import Pattern -from typing_extensions import Literal +from typing import Literal def get_msvcr() -> list[str] | None: ... diff --git a/mypy/typeshed/stdlib/distutils/filelist.pyi b/mypy/typeshed/stdlib/distutils/filelist.pyi index bea48ac16ac5..25db2f3cb6cc 100644 --- a/mypy/typeshed/stdlib/distutils/filelist.pyi +++ b/mypy/typeshed/stdlib/distutils/filelist.pyi @@ -1,7 +1,6 @@ from collections.abc import Iterable from re import Pattern -from typing import overload -from typing_extensions import Literal +from typing import Literal, overload # class is entirely undocumented class FileList: diff --git a/mypy/typeshed/stdlib/distutils/util.pyi b/mypy/typeshed/stdlib/distutils/util.pyi index 83b03747fda6..835266edde59 100644 --- a/mypy/typeshed/stdlib/distutils/util.pyi +++ b/mypy/typeshed/stdlib/distutils/util.pyi @@ -1,12 +1,8 @@ -import sys from _typeshed import StrPath, Unused from collections.abc import Callable, Container, Iterable, Mapping -from typing import Any -from typing_extensions import Literal - -if sys.version_info >= (3, 8): - def get_host_platform() -> str: ... +from typing import Any, Literal +def get_host_platform() -> str: ... def get_platform() -> str: ... def convert_path(pathname: str) -> str: ... def change_root(new_root: str, pathname: str) -> str: ... diff --git a/mypy/typeshed/stdlib/email/_header_value_parser.pyi b/mypy/typeshed/stdlib/email/_header_value_parser.pyi index 97008140ec5d..806fc84cf784 100644 --- a/mypy/typeshed/stdlib/email/_header_value_parser.pyi +++ b/mypy/typeshed/stdlib/email/_header_value_parser.pyi @@ -1,10 +1,9 @@ -import sys from collections.abc import Iterable, Iterator from email.errors import HeaderParseError, MessageDefect from email.policy import Policy from re import Pattern -from typing import Any -from typing_extensions import Final, Self +from typing import Any, Final +from typing_extensions import Self WSP: Final[set[str]] CFWS_LEADER: Final[set[str]] @@ -195,10 +194,9 @@ class DotAtomText(TokenList): token_type: str as_ew_allowed: bool -if sys.version_info >= (3, 8): - class NoFoldLiteral(TokenList): - token_type: str - as_ew_allowed: bool +class NoFoldLiteral(TokenList): + token_type: str + as_ew_allowed: bool class AddrSpec(TokenList): token_type: str @@ -296,17 +294,16 @@ class HeaderLabel(TokenList): token_type: str as_ew_allowed: bool -if sys.version_info >= (3, 8): - class MsgID(TokenList): - token_type: str - as_ew_allowed: bool - def fold(self, policy: Policy) -> str: ... +class MsgID(TokenList): + token_type: str + as_ew_allowed: bool + def fold(self, policy: Policy) -> str: ... - class MessageID(MsgID): - token_type: str +class MessageID(MsgID): + token_type: str - class InvalidMessageID(MessageID): - token_type: str +class InvalidMessageID(MessageID): + token_type: str class Header(TokenList): token_type: str @@ -375,12 +372,9 @@ def get_group_list(value: str) -> tuple[GroupList, str]: ... def get_group(value: str) -> tuple[Group, str]: ... def get_address(value: str) -> tuple[Address, str]: ... def get_address_list(value: str) -> tuple[AddressList, str]: ... - -if sys.version_info >= (3, 8): - def get_no_fold_literal(value: str) -> tuple[NoFoldLiteral, str]: ... - def get_msg_id(value: str) -> tuple[MsgID, str]: ... - def parse_message_id(value: str) -> MessageID: ... - +def get_no_fold_literal(value: str) -> tuple[NoFoldLiteral, str]: ... +def get_msg_id(value: str) -> tuple[MsgID, str]: ... +def parse_message_id(value: str) -> MessageID: ... def parse_mime_version(value: str) -> MIMEVersion: ... def get_invalid_parameter(value: str) -> tuple[InvalidParameter, str]: ... def get_ttext(value: str) -> tuple[ValueTerminal, str]: ... diff --git a/mypy/typeshed/stdlib/email/headerregistry.pyi b/mypy/typeshed/stdlib/email/headerregistry.pyi index 94623e96f208..93a2b3ee72b5 100644 --- a/mypy/typeshed/stdlib/email/headerregistry.pyi +++ b/mypy/typeshed/stdlib/email/headerregistry.pyi @@ -1,4 +1,3 @@ -import sys import types from collections.abc import Iterable, Mapping from datetime import datetime as _datetime @@ -7,14 +6,15 @@ from email._header_value_parser import ( ContentDisposition, ContentTransferEncoding, ContentType, + MessageID, MIMEVersion, TokenList, UnstructuredTokenList, ) from email.errors import MessageDefect from email.policy import Policy -from typing import Any, ClassVar, Protocol -from typing_extensions import Literal, Self +from typing import Any, ClassVar, Literal, Protocol +from typing_extensions import Self class BaseHeader(str): # max_count is actually more of an abstract ClassVar (not defined on the base class, but expected to be defined in subclasses) @@ -130,15 +130,12 @@ class ContentTransferEncodingHeader: @staticmethod def value_parser(value: str) -> ContentTransferEncoding: ... -if sys.version_info >= (3, 8): - from email._header_value_parser import MessageID - - class MessageIDHeader: - max_count: ClassVar[Literal[1]] - @classmethod - def parse(cls, value: str, kwds: dict[str, Any]) -> None: ... - @staticmethod - def value_parser(value: str) -> MessageID: ... +class MessageIDHeader: + max_count: ClassVar[Literal[1]] + @classmethod + def parse(cls, value: str, kwds: dict[str, Any]) -> None: ... + @staticmethod + def value_parser(value: str) -> MessageID: ... class _HeaderParser(Protocol): max_count: ClassVar[Literal[1] | None] diff --git a/mypy/typeshed/stdlib/email/message.pyi b/mypy/typeshed/stdlib/email/message.pyi index 71c8da3a6a5a..7384f3146a8e 100644 --- a/mypy/typeshed/stdlib/email/message.pyi +++ b/mypy/typeshed/stdlib/email/message.pyi @@ -5,8 +5,8 @@ from email.contentmanager import ContentManager from email.errors import MessageDefect from email.header import Header from email.policy import Policy -from typing import Any, Protocol, TypeVar, overload -from typing_extensions import Literal, Self, TypeAlias +from typing import Any, Literal, Protocol, TypeVar, overload +from typing_extensions import Self, TypeAlias __all__ = ["Message", "EmailMessage"] diff --git a/mypy/typeshed/stdlib/enum.pyi b/mypy/typeshed/stdlib/enum.pyi index 10ea19257144..42d0c19d39e7 100644 --- a/mypy/typeshed/stdlib/enum.pyi +++ b/mypy/typeshed/stdlib/enum.pyi @@ -4,8 +4,8 @@ import types from _typeshed import SupportsKeysAndGetItem, Unused from builtins import property as _builtins_property from collections.abc import Callable, Iterable, Iterator, Mapping -from typing import Any, Generic, TypeVar, overload -from typing_extensions import Literal, Self, TypeAlias +from typing import Any, Generic, Literal, TypeVar, overload +from typing_extensions import Self, TypeAlias __all__ = ["EnumMeta", "Enum", "IntEnum", "Flag", "IntFlag", "auto", "unique"] diff --git a/mypy/typeshed/stdlib/fcntl.pyi b/mypy/typeshed/stdlib/fcntl.pyi index 56fd5679a1c8..7e5af76c2aae 100644 --- a/mypy/typeshed/stdlib/fcntl.pyi +++ b/mypy/typeshed/stdlib/fcntl.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import FileDescriptorLike, ReadOnlyBuffer, WriteableBuffer -from typing import Any, overload -from typing_extensions import Buffer, Literal +from typing import Any, Literal, overload +from typing_extensions import Buffer if sys.platform != "win32": FASYNC: int @@ -37,13 +37,12 @@ if sys.platform != "win32": F_NOTIFY: int F_EXLCK: int F_GETLK64: int - if sys.version_info >= (3, 8): - F_ADD_SEALS: int - F_GET_SEALS: int - F_SEAL_GROW: int - F_SEAL_SEAL: int - F_SEAL_SHRINK: int - F_SEAL_WRITE: int + F_ADD_SEALS: int + F_GET_SEALS: int + F_SEAL_GROW: int + F_SEAL_SEAL: int + F_SEAL_SHRINK: int + F_SEAL_WRITE: int if sys.version_info >= (3, 9): F_OFD_GETLK: int F_OFD_SETLK: int diff --git a/mypy/typeshed/stdlib/filecmp.pyi b/mypy/typeshed/stdlib/filecmp.pyi index 008d7a44e6c4..4f54a9bff6ee 100644 --- a/mypy/typeshed/stdlib/filecmp.pyi +++ b/mypy/typeshed/stdlib/filecmp.pyi @@ -1,8 +1,7 @@ import sys from _typeshed import GenericPath, StrOrBytesPath from collections.abc import Callable, Iterable, Sequence -from typing import Any, AnyStr, Generic -from typing_extensions import Literal +from typing import Any, AnyStr, Generic, Literal if sys.version_info >= (3, 9): from types import GenericAlias diff --git a/mypy/typeshed/stdlib/fileinput.pyi b/mypy/typeshed/stdlib/fileinput.pyi index c2fd31d1ea77..e8d5dd8d2d5b 100644 --- a/mypy/typeshed/stdlib/fileinput.pyi +++ b/mypy/typeshed/stdlib/fileinput.pyi @@ -2,8 +2,8 @@ import sys from _typeshed import AnyStr_co, StrOrBytesPath from collections.abc import Callable, Iterable, Iterator from types import TracebackType -from typing import IO, Any, AnyStr, Protocol, overload -from typing_extensions import Literal, Self, TypeAlias +from typing import IO, Any, AnyStr, Literal, Protocol, overload +from typing_extensions import Self, TypeAlias if sys.version_info >= (3, 9): from types import GenericAlias @@ -68,7 +68,7 @@ if sys.version_info >= (3, 10): errors: str | None = None, ) -> FileInput[Any]: ... -elif sys.version_info >= (3, 8): +else: # bufsize is dropped and mode and openhook become keyword-only @overload def input( @@ -98,57 +98,6 @@ elif sys.version_info >= (3, 8): openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[Any]] | None = None, ) -> FileInput[Any]: ... -else: - @overload - def input( - files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, - inplace: bool = False, - backup: str = "", - bufsize: int = 0, - mode: _TextMode = "r", - openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[str]] | None = None, - ) -> FileInput[str]: ... - # Because mode isn't keyword-only here yet, we need two overloads each for - # the bytes case and the fallback case. - @overload - def input( - files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, - inplace: bool = False, - backup: str = "", - bufsize: int = 0, - *, - mode: Literal["rb"], - openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[bytes]] | None = None, - ) -> FileInput[bytes]: ... - @overload - def input( - files: StrOrBytesPath | Iterable[StrOrBytesPath] | None, - inplace: bool, - backup: str, - bufsize: int, - mode: Literal["rb"], - openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[bytes]] | None = None, - ) -> FileInput[bytes]: ... - @overload - def input( - files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, - inplace: bool = False, - backup: str = "", - bufsize: int = 0, - *, - mode: str, - openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[Any]] | None = None, - ) -> FileInput[Any]: ... - @overload - def input( - files: StrOrBytesPath | Iterable[StrOrBytesPath] | None, - inplace: bool, - backup: str, - bufsize: int, - mode: str, - openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[Any]] | None = None, - ) -> FileInput[Any]: ... - def close() -> None: ... def nextfile() -> None: ... def filename() -> str: ... @@ -198,7 +147,7 @@ class FileInput(Iterator[AnyStr]): errors: str | None = None, ) -> None: ... - elif sys.version_info >= (3, 8): + else: # bufsize is dropped and mode and openhook become keyword-only @overload def __init__( @@ -231,62 +180,6 @@ class FileInput(Iterator[AnyStr]): openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[Any]] | None = None, ) -> None: ... - else: - @overload - def __init__( - self: FileInput[str], - files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, - inplace: bool = False, - backup: str = "", - bufsize: int = 0, - mode: _TextMode = "r", - openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[str]] | None = None, - ) -> None: ... - # Because mode isn't keyword-only here yet, we need two overloads each for - # the bytes case and the fallback case. - @overload - def __init__( - self: FileInput[bytes], - files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, - inplace: bool = False, - backup: str = "", - bufsize: int = 0, - *, - mode: Literal["rb"], - openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[bytes]] | None = None, - ) -> None: ... - @overload - def __init__( - self: FileInput[bytes], - files: StrOrBytesPath | Iterable[StrOrBytesPath] | None, - inplace: bool, - backup: str, - bufsize: int, - mode: Literal["rb"], - openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[bytes]] | None = None, - ) -> None: ... - @overload - def __init__( - self: FileInput[Any], - files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, - inplace: bool = False, - backup: str = "", - bufsize: int = 0, - *, - mode: str, - openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[Any]] | None = None, - ) -> None: ... - @overload - def __init__( - self: FileInput[Any], - files: StrOrBytesPath | Iterable[StrOrBytesPath] | None, - inplace: bool, - backup: str, - bufsize: int, - mode: str, - openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[Any]] | None = None, - ) -> None: ... - def __del__(self) -> None: ... def close(self) -> None: ... def __enter__(self) -> Self: ... diff --git a/mypy/typeshed/stdlib/fractions.pyi b/mypy/typeshed/stdlib/fractions.pyi index 7ec8addeb136..43eaa21bd039 100644 --- a/mypy/typeshed/stdlib/fractions.pyi +++ b/mypy/typeshed/stdlib/fractions.pyi @@ -2,8 +2,8 @@ import sys from collections.abc import Callable from decimal import Decimal from numbers import Integral, Rational, Real -from typing import Any, overload -from typing_extensions import Literal, Self, SupportsIndex, TypeAlias +from typing import Any, Literal, SupportsIndex, overload +from typing_extensions import Self, TypeAlias _ComparableNum: TypeAlias = int | float | Decimal | Real @@ -30,8 +30,7 @@ class Fraction(Rational): @classmethod def from_decimal(cls, dec: Decimal) -> Self: ... def limit_denominator(self, max_denominator: int = 1000000) -> Fraction: ... - if sys.version_info >= (3, 8): - def as_integer_ratio(self) -> tuple[int, int]: ... + def as_integer_ratio(self) -> tuple[int, int]: ... if sys.version_info >= (3, 12): def is_integer(self) -> bool: ... @@ -103,25 +102,14 @@ class Fraction(Rational): def __rmod__(b, a: int | Fraction) -> Fraction: ... @overload def __rmod__(b, a: float) -> float: ... - if sys.version_info >= (3, 8): - @overload - def __divmod__(a, b: int | Fraction) -> tuple[int, Fraction]: ... - @overload - def __divmod__(a, b: float) -> tuple[float, Fraction]: ... - @overload - def __rdivmod__(a, b: int | Fraction) -> tuple[int, Fraction]: ... - @overload - def __rdivmod__(a, b: float) -> tuple[float, Fraction]: ... - else: - @overload - def __divmod__(self, other: int | Fraction) -> tuple[int, Fraction]: ... - @overload - def __divmod__(self, other: float) -> tuple[float, Fraction]: ... - @overload - def __rdivmod__(self, other: int | Fraction) -> tuple[int, Fraction]: ... - @overload - def __rdivmod__(self, other: float) -> tuple[float, Fraction]: ... - + @overload + def __divmod__(a, b: int | Fraction) -> tuple[int, Fraction]: ... + @overload + def __divmod__(a, b: float) -> tuple[float, Fraction]: ... + @overload + def __rdivmod__(a, b: int | Fraction) -> tuple[int, Fraction]: ... + @overload + def __rdivmod__(a, b: float) -> tuple[float, Fraction]: ... @overload def __pow__(a, b: int) -> Fraction: ... @overload diff --git a/mypy/typeshed/stdlib/ftplib.pyi b/mypy/typeshed/stdlib/ftplib.pyi index 2d2ffa9aff03..3bc03a0ff121 100644 --- a/mypy/typeshed/stdlib/ftplib.pyi +++ b/mypy/typeshed/stdlib/ftplib.pyi @@ -4,8 +4,8 @@ from collections.abc import Callable, Iterable, Iterator from socket import socket from ssl import SSLContext from types import TracebackType -from typing import Any, TextIO -from typing_extensions import Literal, Self +from typing import Any, Literal, TextIO +from typing_extensions import Self __all__ = ["FTP", "error_reply", "error_temp", "error_perm", "error_proto", "all_errors", "FTP_TLS"] diff --git a/mypy/typeshed/stdlib/functools.pyi b/mypy/typeshed/stdlib/functools.pyi index 4d8c45e96103..8c48e77c16cf 100644 --- a/mypy/typeshed/stdlib/functools.pyi +++ b/mypy/typeshed/stdlib/functools.pyi @@ -1,9 +1,9 @@ import sys import types -from _typeshed import IdentityFunction, SupportsAllComparisons, SupportsItems +from _typeshed import SupportsAllComparisons, SupportsItems from collections.abc import Callable, Hashable, Iterable, Sequence, Sized -from typing import Any, Generic, NamedTuple, TypeVar, overload -from typing_extensions import Literal, Self, TypeAlias, TypedDict, final +from typing import Any, Generic, Literal, NamedTuple, TypedDict, TypeVar, final, overload +from typing_extensions import ParamSpec, Self, TypeAlias if sys.version_info >= (3, 9): from types import GenericAlias @@ -20,18 +20,19 @@ __all__ = [ "partial", "partialmethod", "singledispatch", + "cached_property", + "singledispatchmethod", ] -if sys.version_info >= (3, 8): - __all__ += ["cached_property", "singledispatchmethod"] - if sys.version_info >= (3, 9): __all__ += ["cache"] -_AnyCallable: TypeAlias = Callable[..., object] - _T = TypeVar("_T") _S = TypeVar("_S") +_PWrapped = ParamSpec("_PWrapped") +_RWrapped = TypeVar("_RWrapped") +_PWrapper = ParamSpec("_PWrapper") +_RWrapper = TypeVar("_RWrapper") @overload def reduce(__function: Callable[[_T, _S], _T], __sequence: Iterable[_S], __initial: _T) -> _T: ... @@ -61,14 +62,10 @@ class _lru_cache_wrapper(Generic[_T]): def __copy__(self) -> _lru_cache_wrapper[_T]: ... def __deepcopy__(self, __memo: Any) -> _lru_cache_wrapper[_T]: ... -if sys.version_info >= (3, 8): - @overload - def lru_cache(maxsize: int | None = 128, typed: bool = False) -> Callable[[Callable[..., _T]], _lru_cache_wrapper[_T]]: ... - @overload - def lru_cache(maxsize: Callable[..., _T], typed: bool = False) -> _lru_cache_wrapper[_T]: ... - -else: - def lru_cache(maxsize: int | None = 128, typed: bool = False) -> Callable[[Callable[..., _T]], _lru_cache_wrapper[_T]]: ... +@overload +def lru_cache(maxsize: int | None = 128, typed: bool = False) -> Callable[[Callable[..., _T]], _lru_cache_wrapper[_T]]: ... +@overload +def lru_cache(maxsize: Callable[..., _T], typed: bool = False) -> _lru_cache_wrapper[_T]: ... if sys.version_info >= (3, 12): WRAPPER_ASSIGNMENTS: tuple[ @@ -85,31 +82,41 @@ else: ] WRAPPER_UPDATES: tuple[Literal["__dict__"]] +class _Wrapped(Generic[_PWrapped, _RWrapped, _PWrapper, _RWrapper]): + __wrapped__: Callable[_PWrapped, _RWrapped] + def __call__(self, *args: _PWrapper.args, **kwargs: _PWrapper.kwargs) -> _RWrapper: ... + # as with ``Callable``, we'll assume that these attributes exist + __name__: str + __qualname__: str + +class _Wrapper(Generic[_PWrapped, _RWrapped]): + def __call__(self, f: Callable[_PWrapper, _RWrapper]) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWrapper]: ... + if sys.version_info >= (3, 12): def update_wrapper( - wrapper: _T, - wrapped: _AnyCallable, + wrapper: Callable[_PWrapper, _RWrapper], + wrapped: Callable[_PWrapped, _RWrapped], assigned: Sequence[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotations__", "__type_params__"), updated: Sequence[str] = ("__dict__",), - ) -> _T: ... + ) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWrapper]: ... def wraps( - wrapped: _AnyCallable, + wrapped: Callable[_PWrapped, _RWrapped], assigned: Sequence[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotations__", "__type_params__"), updated: Sequence[str] = ("__dict__",), - ) -> IdentityFunction: ... + ) -> _Wrapper[_PWrapped, _RWrapped]: ... else: def update_wrapper( - wrapper: _T, - wrapped: _AnyCallable, + wrapper: Callable[_PWrapper, _RWrapper], + wrapped: Callable[_PWrapped, _RWrapped], assigned: Sequence[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotations__"), updated: Sequence[str] = ("__dict__",), - ) -> _T: ... + ) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWrapper]: ... def wraps( - wrapped: _AnyCallable, + wrapped: Callable[_PWrapped, _RWrapped], assigned: Sequence[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotations__"), updated: Sequence[str] = ("__dict__",), - ) -> IdentityFunction: ... + ) -> _Wrapper[_PWrapped, _RWrapped]: ... def total_ordering(cls: type[_T]) -> type[_T]: ... def cmp_to_key(mycmp: Callable[[_T, _T], int]) -> Callable[[_T], SupportsAllComparisons]: ... @@ -137,11 +144,7 @@ class partialmethod(Generic[_T]): def __init__(self, __func: Callable[..., _T], *args: Any, **keywords: Any) -> None: ... @overload def __init__(self, __func: _Descriptor, *args: Any, **keywords: Any) -> None: ... - if sys.version_info >= (3, 8): - def __get__(self, obj: Any, cls: type[Any] | None = None) -> Callable[..., _T]: ... - else: - def __get__(self, obj: Any, cls: type[Any] | None) -> Callable[..., _T]: ... - + def __get__(self, obj: Any, cls: type[Any] | None = None) -> Callable[..., _T]: ... @property def __isabstractmethod__(self) -> bool: ... if sys.version_info >= (3, 9): @@ -166,34 +169,33 @@ class _SingleDispatchCallable(Generic[_T]): def singledispatch(func: Callable[..., _T]) -> _SingleDispatchCallable[_T]: ... -if sys.version_info >= (3, 8): - class singledispatchmethod(Generic[_T]): - dispatcher: _SingleDispatchCallable[_T] - func: Callable[..., _T] - def __init__(self, func: Callable[..., _T]) -> None: ... - @property - def __isabstractmethod__(self) -> bool: ... - @overload - def register(self, cls: type[Any], method: None = None) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... - @overload - def register(self, cls: Callable[..., _T], method: None = None) -> Callable[..., _T]: ... - @overload - def register(self, cls: type[Any], method: Callable[..., _T]) -> Callable[..., _T]: ... - def __get__(self, obj: _S, cls: type[_S] | None = None) -> Callable[..., _T]: ... - - class cached_property(Generic[_T]): - func: Callable[[Any], _T] - attrname: str | None - def __init__(self, func: Callable[[Any], _T]) -> None: ... - @overload - def __get__(self, instance: None, owner: type[Any] | None = None) -> Self: ... - @overload - def __get__(self, instance: object, owner: type[Any] | None = None) -> _T: ... - def __set_name__(self, owner: type[Any], name: str) -> None: ... - # __set__ is not defined at runtime, but @cached_property is designed to be settable - def __set__(self, instance: object, value: _T) -> None: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... +class singledispatchmethod(Generic[_T]): + dispatcher: _SingleDispatchCallable[_T] + func: Callable[..., _T] + def __init__(self, func: Callable[..., _T]) -> None: ... + @property + def __isabstractmethod__(self) -> bool: ... + @overload + def register(self, cls: type[Any], method: None = None) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... + @overload + def register(self, cls: Callable[..., _T], method: None = None) -> Callable[..., _T]: ... + @overload + def register(self, cls: type[Any], method: Callable[..., _T]) -> Callable[..., _T]: ... + def __get__(self, obj: _S, cls: type[_S] | None = None) -> Callable[..., _T]: ... + +class cached_property(Generic[_T]): + func: Callable[[Any], _T] + attrname: str | None + def __init__(self, func: Callable[[Any], _T]) -> None: ... + @overload + def __get__(self, instance: None, owner: type[Any] | None = None) -> Self: ... + @overload + def __get__(self, instance: object, owner: type[Any] | None = None) -> _T: ... + def __set_name__(self, owner: type[Any], name: str) -> None: ... + # __set__ is not defined at runtime, but @cached_property is designed to be settable + def __set__(self, instance: object, value: _T) -> None: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... if sys.version_info >= (3, 9): def cache(__user_function: Callable[..., _T]) -> _lru_cache_wrapper[_T]: ... diff --git a/mypy/typeshed/stdlib/gc.pyi b/mypy/typeshed/stdlib/gc.pyi index 27cee726ba09..914c41434791 100644 --- a/mypy/typeshed/stdlib/gc.pyi +++ b/mypy/typeshed/stdlib/gc.pyi @@ -1,7 +1,7 @@ import sys from collections.abc import Callable -from typing import Any -from typing_extensions import Literal, TypeAlias +from typing import Any, Literal +from typing_extensions import TypeAlias DEBUG_COLLECTABLE: Literal[2] DEBUG_LEAK: Literal[38] @@ -19,13 +19,7 @@ def disable() -> None: ... def enable() -> None: ... def get_count() -> tuple[int, int, int]: ... def get_debug() -> int: ... - -if sys.version_info >= (3, 8): - def get_objects(generation: int | None = None) -> list[Any]: ... - -else: - def get_objects() -> list[Any]: ... - +def get_objects(generation: int | None = None) -> list[Any]: ... def freeze() -> None: ... def unfreeze() -> None: ... def get_freeze_count() -> int: ... diff --git a/mypy/typeshed/stdlib/genericpath.pyi b/mypy/typeshed/stdlib/genericpath.pyi index be08f7a3cb79..0dd5dec4b2ec 100644 --- a/mypy/typeshed/stdlib/genericpath.pyi +++ b/mypy/typeshed/stdlib/genericpath.pyi @@ -2,8 +2,8 @@ import os import sys from _typeshed import BytesPath, FileDescriptorOrPath, StrOrBytesPath, StrPath, SupportsRichComparisonT from collections.abc import Sequence -from typing import overload -from typing_extensions import Literal, LiteralString +from typing import Literal, overload +from typing_extensions import LiteralString __all__ = [ "commonprefix", diff --git a/mypy/typeshed/stdlib/gettext.pyi b/mypy/typeshed/stdlib/gettext.pyi index 57e81120b8ca..4c17c0dc5de4 100644 --- a/mypy/typeshed/stdlib/gettext.pyi +++ b/mypy/typeshed/stdlib/gettext.pyi @@ -2,8 +2,7 @@ import io import sys from _typeshed import StrPath from collections.abc import Callable, Container, Iterable, Sequence -from typing import Any, Protocol, TypeVar, overload -from typing_extensions import Final, Literal +from typing import Any, Final, Literal, Protocol, TypeVar, overload __all__ = [ "NullTranslations", @@ -18,14 +17,15 @@ __all__ = [ "dngettext", "gettext", "ngettext", + "dnpgettext", + "dpgettext", + "npgettext", + "pgettext", ] if sys.version_info < (3, 11): __all__ += ["bind_textdomain_codeset", "ldgettext", "ldngettext", "lgettext", "lngettext"] -if sys.version_info >= (3, 8): - __all__ += ["dnpgettext", "dpgettext", "npgettext", "pgettext"] - class _TranslationsReader(Protocol): def read(self) -> bytes: ... # optional: @@ -37,10 +37,8 @@ class NullTranslations: def add_fallback(self, fallback: NullTranslations) -> None: ... def gettext(self, message: str) -> str: ... def ngettext(self, msgid1: str, msgid2: str, n: int) -> str: ... - if sys.version_info >= (3, 8): - def pgettext(self, context: str, message: str) -> str: ... - def npgettext(self, context: str, msgid1: str, msgid2: str, n: int) -> str: ... - + def pgettext(self, context: str, message: str) -> str: ... + def npgettext(self, context: str, msgid1: str, msgid2: str, n: int) -> str: ... def info(self) -> dict[str, str]: ... def charset(self) -> str | None: ... if sys.version_info < (3, 11): @@ -156,12 +154,10 @@ def dgettext(domain: str, message: str) -> str: ... def dngettext(domain: str, msgid1: str, msgid2: str, n: int) -> str: ... def gettext(message: str) -> str: ... def ngettext(msgid1: str, msgid2: str, n: int) -> str: ... - -if sys.version_info >= (3, 8): - def pgettext(context: str, message: str) -> str: ... - def dpgettext(domain: str, context: str, message: str) -> str: ... - def npgettext(context: str, msgid1: str, msgid2: str, n: int) -> str: ... - def dnpgettext(domain: str, context: str, msgid1: str, msgid2: str, n: int) -> str: ... +def pgettext(context: str, message: str) -> str: ... +def dpgettext(domain: str, context: str, message: str) -> str: ... +def npgettext(context: str, msgid1: str, msgid2: str, n: int) -> str: ... +def dnpgettext(domain: str, context: str, msgid1: str, msgid2: str, n: int) -> str: ... if sys.version_info < (3, 11): def lgettext(message: str) -> str: ... diff --git a/mypy/typeshed/stdlib/grp.pyi b/mypy/typeshed/stdlib/grp.pyi index 4b66b84b6389..bb0d65180918 100644 --- a/mypy/typeshed/stdlib/grp.pyi +++ b/mypy/typeshed/stdlib/grp.pyi @@ -1,7 +1,6 @@ import sys from _typeshed import structseq -from typing import Any -from typing_extensions import Final, final +from typing import Any, Final, final if sys.platform != "win32": @final diff --git a/mypy/typeshed/stdlib/gzip.pyi b/mypy/typeshed/stdlib/gzip.pyi index d001849e609c..2c33d7cf5810 100644 --- a/mypy/typeshed/stdlib/gzip.pyi +++ b/mypy/typeshed/stdlib/gzip.pyi @@ -3,13 +3,10 @@ import sys import zlib from _typeshed import ReadableBuffer, SizedBuffer, StrOrBytesPath from io import FileIO -from typing import Protocol, TextIO, overload -from typing_extensions import Literal, TypeAlias +from typing import Literal, Protocol, TextIO, overload +from typing_extensions import TypeAlias -if sys.version_info >= (3, 8): - __all__ = ["BadGzipFile", "GzipFile", "open", "compress", "decompress"] -else: - __all__ = ["GzipFile", "open", "compress", "decompress"] +__all__ = ["BadGzipFile", "GzipFile", "open", "compress", "decompress"] _ReadBinaryMode: TypeAlias = Literal["r", "rb"] _WriteBinaryMode: TypeAlias = Literal["a", "ab", "w", "wb", "x", "xb"] @@ -85,8 +82,7 @@ class _PaddedFile: def seek(self, off: int) -> int: ... def seekable(self) -> bool: ... -if sys.version_info >= (3, 8): - class BadGzipFile(OSError): ... +class BadGzipFile(OSError): ... class GzipFile(_compression.BaseStream): myfileobj: FileIO | None @@ -160,10 +156,5 @@ class GzipFile(_compression.BaseStream): class _GzipReader(_compression.DecompressReader): def __init__(self, fp: _ReadableFileobj) -> None: ... -if sys.version_info >= (3, 8): - def compress(data: SizedBuffer, compresslevel: int = 9, *, mtime: float | None = None) -> bytes: ... - -else: - def compress(data: SizedBuffer, compresslevel: int = 9) -> bytes: ... - +def compress(data: SizedBuffer, compresslevel: int = 9, *, mtime: float | None = None) -> bytes: ... def decompress(data: ReadableBuffer) -> bytes: ... diff --git a/mypy/typeshed/stdlib/hashlib.pyi b/mypy/typeshed/stdlib/hashlib.pyi index ed1321f23b9e..38e846ab7eb3 100644 --- a/mypy/typeshed/stdlib/hashlib.pyi +++ b/mypy/typeshed/stdlib/hashlib.pyi @@ -1,8 +1,8 @@ import sys from _typeshed import ReadableBuffer from collections.abc import Callable, Set as AbstractSet -from typing import Protocol -from typing_extensions import Self, final +from typing import Protocol, final +from typing_extensions import Self if sys.version_info >= (3, 11): __all__ = ( @@ -70,7 +70,7 @@ if sys.version_info >= (3, 9): def sha384(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> _Hash: ... def sha512(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> _Hash: ... -elif sys.version_info >= (3, 8): +else: def new(name: str, data: ReadableBuffer = b"") -> _Hash: ... def md5(string: ReadableBuffer = b"") -> _Hash: ... def sha1(string: ReadableBuffer = b"") -> _Hash: ... @@ -79,15 +79,6 @@ elif sys.version_info >= (3, 8): def sha384(string: ReadableBuffer = b"") -> _Hash: ... def sha512(string: ReadableBuffer = b"") -> _Hash: ... -else: - def new(name: str, data: ReadableBuffer = b"") -> _Hash: ... - def md5(__string: ReadableBuffer = ...) -> _Hash: ... - def sha1(__string: ReadableBuffer = ...) -> _Hash: ... - def sha224(__string: ReadableBuffer = ...) -> _Hash: ... - def sha256(__string: ReadableBuffer = ...) -> _Hash: ... - def sha384(__string: ReadableBuffer = ...) -> _Hash: ... - def sha512(__string: ReadableBuffer = ...) -> _Hash: ... - algorithms_guaranteed: AbstractSet[str] algorithms_available: AbstractSet[str] diff --git a/mypy/typeshed/stdlib/heapq.pyi b/mypy/typeshed/stdlib/heapq.pyi index 3f4f274b9769..9198febd3cfa 100644 --- a/mypy/typeshed/stdlib/heapq.pyi +++ b/mypy/typeshed/stdlib/heapq.pyi @@ -1,8 +1,7 @@ from _heapq import * from _typeshed import SupportsRichComparison from collections.abc import Callable, Iterable -from typing import Any, TypeVar -from typing_extensions import Final +from typing import Any, Final, TypeVar __all__ = ["heappush", "heappop", "heapify", "heapreplace", "merge", "nlargest", "nsmallest", "heappushpop"] diff --git a/mypy/typeshed/stdlib/hmac.pyi b/mypy/typeshed/stdlib/hmac.pyi index 9ff99a5a05d5..614121529416 100644 --- a/mypy/typeshed/stdlib/hmac.pyi +++ b/mypy/typeshed/stdlib/hmac.pyi @@ -1,4 +1,3 @@ -import sys from _typeshed import ReadableBuffer, SizedBuffer from collections.abc import Callable from types import ModuleType @@ -14,29 +13,19 @@ trans_36: bytes digest_size: None -if sys.version_info >= (3, 8): - # In reality digestmod has a default value, but the function always throws an error - # if the argument is not given, so we pretend it is a required argument. - @overload - def new(key: bytes | bytearray, msg: ReadableBuffer | None, digestmod: _DigestMod) -> HMAC: ... - @overload - def new(key: bytes | bytearray, *, digestmod: _DigestMod) -> HMAC: ... - -else: - def new(key: bytes | bytearray, msg: ReadableBuffer | None = None, digestmod: _DigestMod | None = None) -> HMAC: ... +# In reality digestmod has a default value, but the function always throws an error +# if the argument is not given, so we pretend it is a required argument. +@overload +def new(key: bytes | bytearray, msg: ReadableBuffer | None, digestmod: _DigestMod) -> HMAC: ... +@overload +def new(key: bytes | bytearray, *, digestmod: _DigestMod) -> HMAC: ... class HMAC: digest_size: int block_size: int @property def name(self) -> str: ... - if sys.version_info >= (3, 8): - def __init__(self, key: bytes | bytearray, msg: ReadableBuffer | None = None, digestmod: _DigestMod = "") -> None: ... - else: - def __init__( - self, key: bytes | bytearray, msg: ReadableBuffer | None = None, digestmod: _DigestMod | None = None - ) -> None: ... - + def __init__(self, key: bytes | bytearray, msg: ReadableBuffer | None = None, digestmod: _DigestMod = "") -> None: ... def update(self, msg: ReadableBuffer) -> None: ... def digest(self) -> bytes: ... def hexdigest(self) -> str: ... diff --git a/mypy/typeshed/stdlib/http/__init__.pyi b/mypy/typeshed/stdlib/http/__init__.pyi index 4310c79b9269..2eee06fdaaa9 100644 --- a/mypy/typeshed/stdlib/http/__init__.pyi +++ b/mypy/typeshed/stdlib/http/__init__.pyi @@ -1,6 +1,6 @@ import sys from enum import IntEnum -from typing_extensions import Literal +from typing import Literal if sys.version_info >= (3, 11): from enum import StrEnum @@ -73,8 +73,7 @@ class HTTPStatus(IntEnum): NOT_EXTENDED: int NETWORK_AUTHENTICATION_REQUIRED: int MISDIRECTED_REQUEST: int - if sys.version_info >= (3, 8): - UNAVAILABLE_FOR_LEGAL_REASONS: int + UNAVAILABLE_FOR_LEGAL_REASONS: int if sys.version_info >= (3, 9): EARLY_HINTS: Literal[103] IM_A_TEAPOT: Literal[418] diff --git a/mypy/typeshed/stdlib/http/cookiejar.pyi b/mypy/typeshed/stdlib/http/cookiejar.pyi index 482cbca1d88a..faac20d13125 100644 --- a/mypy/typeshed/stdlib/http/cookiejar.pyi +++ b/mypy/typeshed/stdlib/http/cookiejar.pyi @@ -44,13 +44,7 @@ class CookieJar(Iterable[Cookie]): class FileCookieJar(CookieJar): filename: str delayload: bool - if sys.version_info >= (3, 8): - def __init__( - self, filename: StrPath | None = None, delayload: bool = False, policy: CookiePolicy | None = None - ) -> None: ... - else: - def __init__(self, filename: str | None = None, delayload: bool = False, policy: CookiePolicy | None = None) -> None: ... - + def __init__(self, filename: StrPath | None = None, delayload: bool = False, policy: CookiePolicy | None = None) -> None: ... def save(self, filename: str | None = None, ignore_discard: bool = False, ignore_expires: bool = False) -> None: ... def load(self, filename: str | None = None, ignore_discard: bool = False, ignore_expires: bool = False) -> None: ... def revert(self, filename: str | None = None, ignore_discard: bool = False, ignore_expires: bool = False) -> None: ... @@ -84,40 +78,22 @@ class DefaultCookiePolicy(CookiePolicy): DomainRFC2965Match: ClassVar[int] DomainLiberal: ClassVar[int] DomainStrict: ClassVar[int] - if sys.version_info >= (3, 8): - def __init__( - self, - blocked_domains: Sequence[str] | None = None, - allowed_domains: Sequence[str] | None = None, - netscape: bool = True, - rfc2965: bool = False, - rfc2109_as_netscape: bool | None = None, - hide_cookie2: bool = False, - strict_domain: bool = False, - strict_rfc2965_unverifiable: bool = True, - strict_ns_unverifiable: bool = False, - strict_ns_domain: int = 0, - strict_ns_set_initial_dollar: bool = False, - strict_ns_set_path: bool = False, - secure_protocols: Sequence[str] = ("https", "wss"), - ) -> None: ... - else: - def __init__( - self, - blocked_domains: Sequence[str] | None = None, - allowed_domains: Sequence[str] | None = None, - netscape: bool = True, - rfc2965: bool = False, - rfc2109_as_netscape: bool | None = None, - hide_cookie2: bool = False, - strict_domain: bool = False, - strict_rfc2965_unverifiable: bool = True, - strict_ns_unverifiable: bool = False, - strict_ns_domain: int = 0, - strict_ns_set_initial_dollar: bool = False, - strict_ns_set_path: bool = False, - ) -> None: ... - + def __init__( + self, + blocked_domains: Sequence[str] | None = None, + allowed_domains: Sequence[str] | None = None, + netscape: bool = True, + rfc2965: bool = False, + rfc2109_as_netscape: bool | None = None, + hide_cookie2: bool = False, + strict_domain: bool = False, + strict_rfc2965_unverifiable: bool = True, + strict_ns_unverifiable: bool = False, + strict_ns_domain: int = 0, + strict_ns_set_initial_dollar: bool = False, + strict_ns_set_path: bool = False, + secure_protocols: Sequence[str] = ("https", "wss"), + ) -> None: ... def blocked_domains(self) -> tuple[str, ...]: ... def set_blocked_domains(self, blocked_domains: Sequence[str]) -> None: ... def is_blocked(self, domain: str) -> bool: ... diff --git a/mypy/typeshed/stdlib/http/server.pyi b/mypy/typeshed/stdlib/http/server.pyi index 22c33bc3787a..07cde553c1df 100644 --- a/mypy/typeshed/stdlib/http/server.pyi +++ b/mypy/typeshed/stdlib/http/server.pyi @@ -45,7 +45,7 @@ class BaseHTTPRequestHandler(socketserver.StreamRequestHandler): def log_error(self, format: str, *args: Any) -> None: ... def log_message(self, format: str, *args: Any) -> None: ... def version_string(self) -> str: ... - def date_time_string(self, timestamp: int | None = None) -> str: ... + def date_time_string(self, timestamp: float | None = None) -> str: ... def log_date_time_string(self) -> str: ... def address_string(self) -> str: ... def parse_request(self) -> bool: ... # undocumented diff --git a/mypy/typeshed/stdlib/imaplib.pyi b/mypy/typeshed/stdlib/imaplib.pyi index a61848c9af13..6a4d8b2e720a 100644 --- a/mypy/typeshed/stdlib/imaplib.pyi +++ b/mypy/typeshed/stdlib/imaplib.pyi @@ -9,8 +9,8 @@ from re import Pattern from socket import socket as _socket from ssl import SSLContext, SSLSocket from types import TracebackType -from typing import IO, Any, SupportsAbs, SupportsInt -from typing_extensions import Literal, Self, TypeAlias +from typing import IO, Any, Literal, SupportsAbs, SupportsInt +from typing_extensions import Self, TypeAlias __all__ = ["IMAP4", "IMAP4_stream", "Internaldate2tuple", "Int2AP", "ParseFlags", "Time2Internaldate", "IMAP4_SSL"] diff --git a/mypy/typeshed/stdlib/importlib/abc.pyi b/mypy/typeshed/stdlib/importlib/abc.pyi index eb13240f84ff..825eab7ffde2 100644 --- a/mypy/typeshed/stdlib/importlib/abc.pyi +++ b/mypy/typeshed/stdlib/importlib/abc.pyi @@ -6,8 +6,7 @@ from abc import ABCMeta, abstractmethod from collections.abc import Iterator, Mapping, Sequence from importlib.machinery import ModuleSpec from io import BufferedReader -from typing import IO, Any, Protocol, overload, runtime_checkable -from typing_extensions import Literal +from typing import IO, Any, Literal, Protocol, overload, runtime_checkable if sys.version_info >= (3, 11): __all__ = [ diff --git a/mypy/typeshed/stdlib/importlib/machinery.pyi b/mypy/typeshed/stdlib/importlib/machinery.pyi index a0431905a828..586c2b80ab7b 100644 --- a/mypy/typeshed/stdlib/importlib/machinery.pyi +++ b/mypy/typeshed/stdlib/importlib/machinery.pyi @@ -3,11 +3,9 @@ import sys import types from _typeshed import ReadableBuffer from collections.abc import Callable, Iterable, MutableSequence, Sequence -from typing import Any -from typing_extensions import Literal, deprecated - -if sys.version_info >= (3, 8): - from importlib.metadata import DistributionFinder, PathDistribution +from importlib.metadata import DistributionFinder, PathDistribution +from typing import Any, Literal +from typing_extensions import deprecated class ModuleSpec: def __init__( @@ -117,7 +115,7 @@ class PathFinder: if sys.version_info >= (3, 10): @staticmethod def find_distributions(context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]: ... - elif sys.version_info >= (3, 8): + else: @classmethod def find_distributions(cls, context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]: ... diff --git a/mypy/typeshed/stdlib/importlib/readers.pyi b/mypy/typeshed/stdlib/importlib/readers.pyi index f34794601b59..41d7af966d58 100644 --- a/mypy/typeshed/stdlib/importlib/readers.pyi +++ b/mypy/typeshed/stdlib/importlib/readers.pyi @@ -8,8 +8,8 @@ import zipfile from _typeshed import Incomplete, StrPath from collections.abc import Iterable, Iterator from io import BufferedReader -from typing import NoReturn, TypeVar -from typing_extensions import Literal, Never +from typing import Literal, NoReturn, TypeVar +from typing_extensions import Never if sys.version_info >= (3, 11): import importlib.resources.abc as abc diff --git a/mypy/typeshed/stdlib/importlib/resources/simple.pyi b/mypy/typeshed/stdlib/importlib/resources/simple.pyi index 9502375d00a2..9ff415156365 100644 --- a/mypy/typeshed/stdlib/importlib/resources/simple.pyi +++ b/mypy/typeshed/stdlib/importlib/resources/simple.pyi @@ -3,8 +3,8 @@ import sys from _typeshed import Incomplete, OpenBinaryMode, OpenTextMode, Unused from collections.abc import Iterator from io import TextIOWrapper -from typing import IO, Any, BinaryIO, NoReturn, overload -from typing_extensions import Literal, Never +from typing import IO, Any, BinaryIO, Literal, NoReturn, overload +from typing_extensions import Never if sys.version_info >= (3, 11): from .abc import Traversable, TraversableResources diff --git a/mypy/typeshed/stdlib/inspect.pyi b/mypy/typeshed/stdlib/inspect.pyi index 6498719df887..a26dc67f9945 100644 --- a/mypy/typeshed/stdlib/inspect.pyi +++ b/mypy/typeshed/stdlib/inspect.pyi @@ -25,8 +25,8 @@ from types import ( TracebackType, WrapperDescriptorType, ) -from typing import Any, ClassVar, NamedTuple, Protocol, TypeVar, overload -from typing_extensions import Literal, ParamSpec, Self, TypeAlias, TypeGuard +from typing import Any, ClassVar, Literal, NamedTuple, Protocol, TypeVar, overload +from typing_extensions import ParamSpec, Self, TypeAlias, TypeGuard if sys.version_info >= (3, 11): __all__ = [ @@ -200,57 +200,29 @@ def isfunction(object: object) -> TypeGuard[FunctionType]: ... if sys.version_info >= (3, 12): def markcoroutinefunction(func: _F) -> _F: ... -if sys.version_info >= (3, 8): - @overload - def isgeneratorfunction(obj: Callable[..., Generator[Any, Any, Any]]) -> bool: ... - @overload - def isgeneratorfunction(obj: Callable[_P, Any]) -> TypeGuard[Callable[_P, GeneratorType[Any, Any, Any]]]: ... - @overload - def isgeneratorfunction(obj: object) -> TypeGuard[Callable[..., GeneratorType[Any, Any, Any]]]: ... - @overload - def iscoroutinefunction(obj: Callable[..., Coroutine[Any, Any, Any]]) -> bool: ... - @overload - def iscoroutinefunction(obj: Callable[_P, Awaitable[_T]]) -> TypeGuard[Callable[_P, CoroutineType[Any, Any, _T]]]: ... - @overload - def iscoroutinefunction(obj: Callable[_P, object]) -> TypeGuard[Callable[_P, CoroutineType[Any, Any, Any]]]: ... - @overload - def iscoroutinefunction(obj: object) -> TypeGuard[Callable[..., CoroutineType[Any, Any, Any]]]: ... - -else: - @overload - def isgeneratorfunction(object: Callable[..., Generator[Any, Any, Any]]) -> bool: ... - @overload - def isgeneratorfunction(object: Callable[_P, Any]) -> TypeGuard[Callable[_P, GeneratorType[Any, Any, Any]]]: ... - @overload - def isgeneratorfunction(object: object) -> TypeGuard[Callable[..., GeneratorType[Any, Any, Any]]]: ... - @overload - def iscoroutinefunction(object: Callable[..., Coroutine[Any, Any, Any]]) -> bool: ... - @overload - def iscoroutinefunction(object: Callable[_P, Awaitable[_T]]) -> TypeGuard[Callable[_P, CoroutineType[Any, Any, _T]]]: ... - @overload - def iscoroutinefunction(object: Callable[_P, Any]) -> TypeGuard[Callable[_P, CoroutineType[Any, Any, Any]]]: ... - @overload - def iscoroutinefunction(object: object) -> TypeGuard[Callable[..., CoroutineType[Any, Any, Any]]]: ... - +@overload +def isgeneratorfunction(obj: Callable[..., Generator[Any, Any, Any]]) -> bool: ... +@overload +def isgeneratorfunction(obj: Callable[_P, Any]) -> TypeGuard[Callable[_P, GeneratorType[Any, Any, Any]]]: ... +@overload +def isgeneratorfunction(obj: object) -> TypeGuard[Callable[..., GeneratorType[Any, Any, Any]]]: ... +@overload +def iscoroutinefunction(obj: Callable[..., Coroutine[Any, Any, Any]]) -> bool: ... +@overload +def iscoroutinefunction(obj: Callable[_P, Awaitable[_T]]) -> TypeGuard[Callable[_P, CoroutineType[Any, Any, _T]]]: ... +@overload +def iscoroutinefunction(obj: Callable[_P, object]) -> TypeGuard[Callable[_P, CoroutineType[Any, Any, Any]]]: ... +@overload +def iscoroutinefunction(obj: object) -> TypeGuard[Callable[..., CoroutineType[Any, Any, Any]]]: ... def isgenerator(object: object) -> TypeGuard[GeneratorType[Any, Any, Any]]: ... def iscoroutine(object: object) -> TypeGuard[CoroutineType[Any, Any, Any]]: ... def isawaitable(object: object) -> TypeGuard[Awaitable[Any]]: ... - -if sys.version_info >= (3, 8): - @overload - def isasyncgenfunction(obj: Callable[..., AsyncGenerator[Any, Any]]) -> bool: ... - @overload - def isasyncgenfunction(obj: Callable[_P, Any]) -> TypeGuard[Callable[_P, AsyncGeneratorType[Any, Any]]]: ... - @overload - def isasyncgenfunction(obj: object) -> TypeGuard[Callable[..., AsyncGeneratorType[Any, Any]]]: ... - -else: - @overload - def isasyncgenfunction(object: Callable[..., AsyncGenerator[Any, Any]]) -> bool: ... - @overload - def isasyncgenfunction(object: Callable[_P, Any]) -> TypeGuard[Callable[_P, AsyncGeneratorType[Any, Any]]]: ... - @overload - def isasyncgenfunction(object: object) -> TypeGuard[Callable[..., AsyncGeneratorType[Any, Any]]]: ... +@overload +def isasyncgenfunction(obj: Callable[..., AsyncGenerator[Any, Any]]) -> bool: ... +@overload +def isasyncgenfunction(obj: Callable[_P, Any]) -> TypeGuard[Callable[_P, AsyncGeneratorType[Any, Any]]]: ... +@overload +def isasyncgenfunction(obj: object) -> TypeGuard[Callable[..., AsyncGeneratorType[Any, Any]]]: ... class _SupportsSet(Protocol[_T_cont, _V_cont]): def __set__(self, __instance: _T_cont, __value: _V_cont) -> None: ... @@ -381,9 +353,8 @@ class _ParameterKind(enum.IntEnum): KEYWORD_ONLY: int VAR_KEYWORD: int - if sys.version_info >= (3, 8): - @property - def description(self) -> str: ... + @property + def description(self) -> str: ... if sys.version_info >= (3, 12): AGEN_CREATED: Literal["AGEN_CREATED"] diff --git a/mypy/typeshed/stdlib/io.pyi b/mypy/typeshed/stdlib/io.pyi index ee4eda1b4eb0..d949971048b0 100644 --- a/mypy/typeshed/stdlib/io.pyi +++ b/mypy/typeshed/stdlib/io.pyi @@ -6,12 +6,13 @@ from _typeshed import FileDescriptorOrPath, ReadableBuffer, WriteableBuffer from collections.abc import Callable, Iterable, Iterator from os import _Opener from types import TracebackType -from typing import IO, Any, BinaryIO, TextIO, TypeVar, overload -from typing_extensions import Literal, Self +from typing import IO, Any, BinaryIO, Literal, TextIO, TypeVar, overload +from typing_extensions import Self __all__ = [ "BlockingIOError", "open", + "open_code", "IOBase", "RawIOBase", "FileIO", @@ -30,9 +31,6 @@ __all__ = [ "SEEK_END", ] -if sys.version_info >= (3, 8): - __all__ += ["open_code"] - if sys.version_info >= (3, 11): __all__ += ["DEFAULT_BUFFER_SIZE", "IncrementalNewlineDecoder", "text_encoding"] @@ -46,8 +44,7 @@ SEEK_END: Literal[2] open = builtins.open -if sys.version_info >= (3, 8): - def open_code(path: str) -> IO[bytes]: ... +def open_code(path: str) -> IO[bytes]: ... BlockingIOError = builtins.BlockingIOError diff --git a/mypy/typeshed/stdlib/ipaddress.pyi b/mypy/typeshed/stdlib/ipaddress.pyi index 13a8c4330a50..98b1893d2a8a 100644 --- a/mypy/typeshed/stdlib/ipaddress.pyi +++ b/mypy/typeshed/stdlib/ipaddress.pyi @@ -1,7 +1,7 @@ import sys from collections.abc import Iterable, Iterator -from typing import Any, Generic, SupportsInt, TypeVar, overload -from typing_extensions import Literal, Self, TypeAlias +from typing import Any, Generic, Literal, SupportsInt, TypeVar, overload +from typing_extensions import Self, TypeAlias # Undocumented length constants IPV4LENGTH: Literal[32] diff --git a/mypy/typeshed/stdlib/itertools.pyi b/mypy/typeshed/stdlib/itertools.pyi index 1bc0b2ec7390..1fa76399444a 100644 --- a/mypy/typeshed/stdlib/itertools.pyi +++ b/mypy/typeshed/stdlib/itertools.pyi @@ -1,7 +1,7 @@ import sys from collections.abc import Callable, Iterable, Iterator -from typing import Any, Generic, SupportsComplex, SupportsFloat, SupportsInt, TypeVar, overload -from typing_extensions import Literal, Self, SupportsIndex, TypeAlias +from typing import Any, Generic, Literal, SupportsComplex, SupportsFloat, SupportsIndex, SupportsInt, TypeVar, overload +from typing_extensions import Self, TypeAlias if sys.version_info >= (3, 9): from types import GenericAlias @@ -49,14 +49,10 @@ class repeat(Iterator[_T]): def __length_hint__(self) -> int: ... class accumulate(Iterator[_T]): - if sys.version_info >= (3, 8): - @overload - def __init__(self, iterable: Iterable[_T], func: None = None, *, initial: _T | None = ...) -> None: ... - @overload - def __init__(self, iterable: Iterable[_S], func: Callable[[_T, _S], _T], *, initial: _T | None = ...) -> None: ... - else: - def __init__(self, iterable: Iterable[_T], func: Callable[[_T, _T], _T] | None = ...) -> None: ... - + @overload + def __init__(self, iterable: Iterable[_T], func: None = None, *, initial: _T | None = ...) -> None: ... + @overload + def __init__(self, iterable: Iterable[_S], func: Callable[[_T, _S], _T], *, initial: _T | None = ...) -> None: ... def __iter__(self) -> Self: ... def __next__(self) -> _T: ... diff --git a/mypy/typeshed/stdlib/keyword.pyi b/mypy/typeshed/stdlib/keyword.pyi index 46c386048858..5eb7aab85317 100644 --- a/mypy/typeshed/stdlib/keyword.pyi +++ b/mypy/typeshed/stdlib/keyword.pyi @@ -1,6 +1,6 @@ import sys from collections.abc import Sequence -from typing_extensions import Final +from typing import Final if sys.version_info >= (3, 9): __all__ = ["iskeyword", "issoftkeyword", "kwlist", "softkwlist"] diff --git a/mypy/typeshed/stdlib/lib2to3/fixer_base.pyi b/mypy/typeshed/stdlib/lib2to3/fixer_base.pyi index eef386f709ac..5468ab1db5c3 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixer_base.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixer_base.pyi @@ -1,8 +1,7 @@ from _typeshed import Incomplete, StrPath from abc import ABCMeta, abstractmethod from collections.abc import MutableMapping -from typing import ClassVar, TypeVar -from typing_extensions import Literal +from typing import ClassVar, Literal, TypeVar from .pytree import Base, Leaf, Node diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_apply.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_apply.pyi index 7c5451c15220..e53e3dd86457 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_apply.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_apply.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_asserts.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_asserts.pyi index bf73009e9dbf..fb0b472aa12a 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_asserts.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_asserts.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from ..fixer_base import BaseFix diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_basestring.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_basestring.pyi index 84a354d32777..8ed5ccaa7fd3 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_basestring.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_basestring.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_buffer.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_buffer.pyi index 857c1e2241b9..1efca6228ea2 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_buffer.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_buffer.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_dict.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_dict.pyi index 2e66911195bf..08c54c3bc376 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_dict.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_dict.pyi @@ -1,6 +1,5 @@ from _typeshed import Incomplete -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_except.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_except.pyi index b87aacd342e9..30930a2c381e 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_except.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_except.pyi @@ -1,6 +1,5 @@ from collections.abc import Generator, Iterable -from typing import ClassVar, TypeVar -from typing_extensions import Literal +from typing import ClassVar, Literal, TypeVar from .. import fixer_base from ..pytree import Base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_exec.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_exec.pyi index 306937eb9759..71e2a820a564 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_exec.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_exec.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_execfile.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_execfile.pyi index fb245e5a1c1c..8122a6389b12 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_execfile.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_execfile.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_exitfunc.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_exitfunc.pyi index 10341d7985a8..7fc910c0a1bc 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_exitfunc.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_exitfunc.pyi @@ -1,7 +1,6 @@ from _typeshed import Incomplete, StrPath from lib2to3 import fixer_base -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from ..pytree import Node diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_filter.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_filter.pyi index 3998a1dd001e..638889be8b65 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_filter.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_filter.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_funcattrs.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_funcattrs.pyi index 59919446ffdd..60487bb1f2a6 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_funcattrs.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_funcattrs.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_future.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_future.pyi index 8eb5ca35dcc3..12ed93f21223 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_future.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_future.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_getcwdu.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_getcwdu.pyi index d18a38f69be0..aa3ccf50be9e 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_getcwdu.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_getcwdu.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_has_key.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_has_key.pyi index 1e6b58dd3512..f6f5a072e21b 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_has_key.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_has_key.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_idioms.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_idioms.pyi index 8f02252f7bb9..4595c57c7eb9 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_idioms.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_idioms.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_import.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_import.pyi index 436e7f1915b2..bf4b2d00925e 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_import.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_import.pyi @@ -1,7 +1,6 @@ from _typeshed import StrPath from collections.abc import Generator -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base from ..pytree import Node diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_imports.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_imports.pyi index 277a172d3af9..dd6f72dd88ac 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_imports.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_imports.pyi @@ -1,7 +1,6 @@ from _typeshed import StrPath from collections.abc import Generator -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base from ..pytree import Node diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_input.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_input.pyi index df52f8d77427..fc1279535bed 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_input.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_input.pyi @@ -1,6 +1,5 @@ from _typeshed import Incomplete -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_intern.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_intern.pyi index f4e71b6da5f2..804b7b2517a5 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_intern.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_intern.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_isinstance.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_isinstance.pyi index e776ea043714..31eefd625317 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_isinstance.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_isinstance.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_itertools.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_itertools.pyi index a19f7b5e8a00..229d86ee71bb 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_itertools.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_itertools.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_itertools_imports.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_itertools_imports.pyi index 1ea0b506aaa2..39a4da506867 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_itertools_imports.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_itertools_imports.pyi @@ -1,6 +1,5 @@ from lib2to3 import fixer_base -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal class FixItertoolsImports(fixer_base.BaseFix): BM_compatible: ClassVar[Literal[True]] diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_long.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_long.pyi index c47f4528de47..9ccf2711d7d1 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_long.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_long.pyi @@ -1,6 +1,5 @@ from lib2to3 import fixer_base -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal class FixLong(fixer_base.BaseFix): BM_compatible: ClassVar[Literal[True]] diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_map.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_map.pyi index 66e311cba8a8..6e60282cf0be 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_map.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_map.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_metaclass.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_metaclass.pyi index 44626b47072d..1b1ec82032b4 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_metaclass.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_metaclass.pyi @@ -1,6 +1,5 @@ from collections.abc import Generator -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base from ..pytree import Base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_methodattrs.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_methodattrs.pyi index 9bda7992dc8b..594b5e2c95c9 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_methodattrs.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_methodattrs.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_ne.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_ne.pyi index 95dfacccf219..6ff1220b0472 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_ne.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_ne.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_next.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_next.pyi index a5757d65064a..b13914ae8c01 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_next.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_next.pyi @@ -1,6 +1,5 @@ from _typeshed import StrPath -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base from ..pytree import Node diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_nonzero.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_nonzero.pyi index adf268fdb8e2..5c37fc12ef08 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_nonzero.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_nonzero.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_numliterals.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_numliterals.pyi index 6842e42e45f0..113145e395f6 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_numliterals.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_numliterals.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_operator.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_operator.pyi index 6da150a51c0c..b9863d38347b 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_operator.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_operator.pyi @@ -1,6 +1,5 @@ from lib2to3 import fixer_base -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal def invocation(s): ... diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_paren.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_paren.pyi index c730cdc5d0b2..237df6c5ff2c 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_paren.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_paren.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_print.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_print.pyi index 2261c9489299..e9564b04ac75 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_print.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_print.pyi @@ -1,6 +1,5 @@ from _typeshed import Incomplete -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_raise.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_raise.pyi index 756a05ea3ddd..e02c3080f409 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_raise.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_raise.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_raw_input.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_raw_input.pyi index 61d6ad7676ef..d1a0eb0e0a7e 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_raw_input.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_raw_input.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_reduce.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_reduce.pyi index 4ea07fdde00b..f8ad876c21a6 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_reduce.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_reduce.pyi @@ -1,6 +1,5 @@ from lib2to3 import fixer_base -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal class FixReduce(fixer_base.BaseFix): BM_compatible: ClassVar[Literal[True]] diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_reload.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_reload.pyi index 8045ac507890..820075438eca 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_reload.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_reload.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_renames.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_renames.pyi index 2ceca053e903..6283f1ab7ce2 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_renames.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_renames.pyi @@ -1,6 +1,5 @@ from collections.abc import Generator -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_repr.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_repr.pyi index 6f3305846d18..3b192d396dd6 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_repr.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_repr.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_set_literal.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_set_literal.pyi index dd18413d6d5a..6962ff326f56 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_set_literal.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_set_literal.pyi @@ -1,6 +1,5 @@ from lib2to3 import fixer_base -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal class FixSetLiteral(fixer_base.BaseFix): BM_compatible: ClassVar[Literal[True]] diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_standarderror.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_standarderror.pyi index fd23af5a711e..ba914bcab5d6 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_standarderror.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_standarderror.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_sys_exc.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_sys_exc.pyi index 3dbcd38c4b26..0fa1a4787087 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_sys_exc.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_sys_exc.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_throw.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_throw.pyi index 50e37d44a58b..4c99855e5c37 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_throw.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_throw.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_tuple_params.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_tuple_params.pyi index 48eadf75341c..bfaa9970c996 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_tuple_params.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_tuple_params.pyi @@ -1,6 +1,5 @@ from _typeshed import Incomplete -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_types.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_types.pyi index 6ac1344b1e6c..e26dbec71a97 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_types.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_types.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_unicode.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_unicode.pyi index af63d1865f2d..80d9d8b6e656 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_unicode.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_unicode.pyi @@ -1,6 +1,5 @@ from _typeshed import StrPath -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base from ..pytree import Node diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_urllib.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_urllib.pyi index a37e63b31101..625472f609ab 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_urllib.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_urllib.pyi @@ -1,5 +1,5 @@ from collections.abc import Generator -from typing_extensions import Literal +from typing import Literal from .fix_imports import FixImports diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_ws_comma.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_ws_comma.pyi index 6231d90c65f1..4ce5cb2c4ac1 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_ws_comma.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_ws_comma.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base from ..pytree import Leaf diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_xrange.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_xrange.pyi index 89d300ef063a..71318b7660b6 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_xrange.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_xrange.pyi @@ -1,6 +1,5 @@ from _typeshed import Incomplete, StrPath -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base from ..pytree import Node diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_xreadlines.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_xreadlines.pyi index 39757155e5d9..b4794143a003 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_xreadlines.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_xreadlines.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_zip.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_zip.pyi index 0c70717aa2ac..805886ee3180 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_zip.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_zip.pyi @@ -1,5 +1,4 @@ -from typing import ClassVar -from typing_extensions import Literal +from typing import ClassVar, Literal from .. import fixer_base diff --git a/mypy/typeshed/stdlib/lib2to3/main.pyi b/mypy/typeshed/stdlib/lib2to3/main.pyi index cfcaeeaf64ee..5b7fdfca5d65 100644 --- a/mypy/typeshed/stdlib/lib2to3/main.pyi +++ b/mypy/typeshed/stdlib/lib2to3/main.pyi @@ -1,8 +1,7 @@ from _typeshed import FileDescriptorOrPath from collections.abc import Container, Iterable, Iterator, Mapping, Sequence from logging import _ExcInfoType -from typing import AnyStr -from typing_extensions import Literal +from typing import AnyStr, Literal from . import refactor as refactor diff --git a/mypy/typeshed/stdlib/lib2to3/pygram.pyi b/mypy/typeshed/stdlib/lib2to3/pygram.pyi index 2d1e90e79927..86c74b54888a 100644 --- a/mypy/typeshed/stdlib/lib2to3/pygram.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pygram.pyi @@ -1,5 +1,3 @@ -import sys - from .pgen2.grammar import Grammar class Symbols: @@ -112,6 +110,5 @@ class pattern_symbols(Symbols): python_grammar: Grammar python_grammar_no_print_statement: Grammar -if sys.version_info >= (3, 8): - python_grammar_no_print_and_exec_statement: Grammar +python_grammar_no_print_and_exec_statement: Grammar pattern_grammar: Grammar diff --git a/mypy/typeshed/stdlib/lib2to3/pytree.pyi b/mypy/typeshed/stdlib/lib2to3/pytree.pyi index d14446f38565..138333bd58af 100644 --- a/mypy/typeshed/stdlib/lib2to3/pytree.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pytree.pyi @@ -1,7 +1,8 @@ from _typeshed import Incomplete, SupportsGetItem, SupportsLenAndGetItem, Unused from abc import abstractmethod from collections.abc import Iterable, Iterator, MutableSequence -from typing_extensions import Final, Self, TypeAlias +from typing import Final +from typing_extensions import Self, TypeAlias from .fixer_base import BaseFix from .pgen2.grammar import Grammar diff --git a/mypy/typeshed/stdlib/lib2to3/refactor.pyi b/mypy/typeshed/stdlib/lib2to3/refactor.pyi index d750d9c4a6cf..a7f382540648 100644 --- a/mypy/typeshed/stdlib/lib2to3/refactor.pyi +++ b/mypy/typeshed/stdlib/lib2to3/refactor.pyi @@ -3,8 +3,7 @@ from collections.abc import Container, Generator, Iterable, Mapping from logging import Logger, _ExcInfoType from multiprocessing import JoinableQueue from multiprocessing.synchronize import Lock -from typing import Any, ClassVar, NoReturn, overload -from typing_extensions import Final +from typing import Any, ClassVar, Final, NoReturn, overload from .btm_matcher import BottomMatcher from .fixer_base import BaseFix diff --git a/mypy/typeshed/stdlib/logging/__init__.pyi b/mypy/typeshed/stdlib/logging/__init__.pyi index 5a72b1fcd799..eae2bcd3e96c 100644 --- a/mypy/typeshed/stdlib/logging/__init__.pyi +++ b/mypy/typeshed/stdlib/logging/__init__.pyi @@ -7,8 +7,8 @@ from re import Pattern from string import Template from time import struct_time from types import FrameType, TracebackType -from typing import Any, ClassVar, Generic, Protocol, TextIO, TypeVar, overload -from typing_extensions import Literal, Self, TypeAlias +from typing import Any, ClassVar, Generic, Literal, Protocol, TextIO, TypeVar, overload +from typing_extensions import Self, TypeAlias if sys.version_info >= (3, 11): from types import GenericAlias @@ -128,173 +128,94 @@ class Logger(Filterer): def getChild(self, suffix: str) -> Self: ... # see python/typing#980 if sys.version_info >= (3, 12): def getChildren(self) -> set[Logger]: ... - if sys.version_info >= (3, 8): - def debug( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - stacklevel: int = 1, - extra: Mapping[str, object] | None = None, - ) -> None: ... - def info( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - stacklevel: int = 1, - extra: Mapping[str, object] | None = None, - ) -> None: ... - def warning( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - stacklevel: int = 1, - extra: Mapping[str, object] | None = None, - ) -> None: ... - def warn( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - stacklevel: int = 1, - extra: Mapping[str, object] | None = None, - ) -> None: ... - def error( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - stacklevel: int = 1, - extra: Mapping[str, object] | None = None, - ) -> None: ... - def exception( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = True, - stack_info: bool = False, - stacklevel: int = 1, - extra: Mapping[str, object] | None = None, - ) -> None: ... - def critical( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - stacklevel: int = 1, - extra: Mapping[str, object] | None = None, - ) -> None: ... - def log( - self, - level: int, - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - stacklevel: int = 1, - extra: Mapping[str, object] | None = None, - ) -> None: ... - def _log( - self, - level: int, - msg: object, - args: _ArgsType, - exc_info: _ExcInfoType | None = None, - extra: Mapping[str, object] | None = None, - stack_info: bool = False, - stacklevel: int = 1, - ) -> None: ... # undocumented - else: - def debug( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - extra: Mapping[str, object] | None = None, - ) -> None: ... - def info( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - extra: Mapping[str, object] | None = None, - ) -> None: ... - def warning( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - extra: Mapping[str, object] | None = None, - ) -> None: ... - def warn( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - extra: Mapping[str, object] | None = None, - ) -> None: ... - def error( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - extra: Mapping[str, object] | None = None, - ) -> None: ... - def critical( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - extra: Mapping[str, object] | None = None, - ) -> None: ... - def log( - self, - level: int, - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - extra: Mapping[str, object] | None = None, - ) -> None: ... - def exception( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = True, - stack_info: bool = False, - extra: Mapping[str, object] | None = None, - ) -> None: ... - def _log( - self, - level: int, - msg: object, - args: _ArgsType, - exc_info: _ExcInfoType | None = None, - extra: Mapping[str, object] | None = None, - stack_info: bool = False, - ) -> None: ... # undocumented + + def debug( + self, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def info( + self, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def warning( + self, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def warn( + self, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def error( + self, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def exception( + self, + msg: object, + *args: object, + exc_info: _ExcInfoType = True, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def critical( + self, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def log( + self, + level: int, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def _log( + self, + level: int, + msg: object, + args: _ArgsType, + exc_info: _ExcInfoType | None = None, + extra: Mapping[str, object] | None = None, + stack_info: bool = False, + stacklevel: int = 1, + ) -> None: ... # undocumented fatal = critical def addHandler(self, hdlr: Handler) -> None: ... def removeHandler(self, hdlr: Handler) -> None: ... - if sys.version_info >= (3, 8): - def findCaller(self, stack_info: bool = False, stacklevel: int = 1) -> tuple[str, int, str, str | None]: ... - else: - def findCaller(self, stack_info: bool = False) -> tuple[str, int, str, str | None]: ... - + def findCaller(self, stack_info: bool = False, stacklevel: int = 1) -> tuple[str, int, str, str | None]: ... def handle(self, record: LogRecord) -> None: ... def makeRecord( self, @@ -366,12 +287,10 @@ class Formatter: *, defaults: Mapping[str, Any] | None = None, ) -> None: ... - elif sys.version_info >= (3, 8): + else: def __init__( self, fmt: str | None = None, datefmt: str | None = None, style: _FormatStyle = "%", validate: bool = True ) -> None: ... - else: - def __init__(self, fmt: str | None = None, datefmt: str | None = None, style: _FormatStyle = "%") -> None: ... def format(self, record: LogRecord) -> str: ... def formatTime(self, record: LogRecord, datefmt: str | None = None) -> str: ... @@ -451,310 +370,173 @@ class LoggerAdapter(Generic[_L]): def __init__(self, logger: _L, extra: Mapping[str, object]) -> None: ... def process(self, msg: Any, kwargs: MutableMapping[str, Any]) -> tuple[Any, MutableMapping[str, Any]]: ... - if sys.version_info >= (3, 8): - def debug( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - stacklevel: int = 1, - extra: Mapping[str, object] | None = None, - **kwargs: object, - ) -> None: ... - def info( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - stacklevel: int = 1, - extra: Mapping[str, object] | None = None, - **kwargs: object, - ) -> None: ... - def warning( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - stacklevel: int = 1, - extra: Mapping[str, object] | None = None, - **kwargs: object, - ) -> None: ... - def warn( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - stacklevel: int = 1, - extra: Mapping[str, object] | None = None, - **kwargs: object, - ) -> None: ... - def error( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - stacklevel: int = 1, - extra: Mapping[str, object] | None = None, - **kwargs: object, - ) -> None: ... - def exception( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = True, - stack_info: bool = False, - stacklevel: int = 1, - extra: Mapping[str, object] | None = None, - **kwargs: object, - ) -> None: ... - def critical( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - stacklevel: int = 1, - extra: Mapping[str, object] | None = None, - **kwargs: object, - ) -> None: ... - def log( - self, - level: int, - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - stacklevel: int = 1, - extra: Mapping[str, object] | None = None, - **kwargs: object, - ) -> None: ... - else: - def debug( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - extra: Mapping[str, object] | None = None, - **kwargs: object, - ) -> None: ... - def info( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - extra: Mapping[str, object] | None = None, - **kwargs: object, - ) -> None: ... - def warning( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - extra: Mapping[str, object] | None = None, - **kwargs: object, - ) -> None: ... - def warn( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - extra: Mapping[str, object] | None = None, - **kwargs: object, - ) -> None: ... - def error( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - extra: Mapping[str, object] | None = None, - **kwargs: object, - ) -> None: ... - def exception( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = True, - stack_info: bool = False, - extra: Mapping[str, object] | None = None, - **kwargs: object, - ) -> None: ... - def critical( - self, - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - extra: Mapping[str, object] | None = None, - **kwargs: object, - ) -> None: ... - def log( - self, - level: int, - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - extra: Mapping[str, object] | None = None, - **kwargs: object, - ) -> None: ... - - def isEnabledFor(self, level: int) -> bool: ... - def getEffectiveLevel(self) -> int: ... - def setLevel(self, level: _Level) -> None: ... - def hasHandlers(self) -> bool: ... - def _log( - self, - level: int, - msg: object, - args: _ArgsType, - exc_info: _ExcInfoType | None = None, - extra: Mapping[str, object] | None = None, - stack_info: bool = False, - ) -> None: ... # undocumented - @property - def name(self) -> str: ... # undocumented - if sys.version_info >= (3, 11): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... - -def getLogger(name: str | None = None) -> Logger: ... -def getLoggerClass() -> type[Logger]: ... -def getLogRecordFactory() -> Callable[..., LogRecord]: ... - -if sys.version_info >= (3, 8): def debug( + self, msg: object, *args: object, exc_info: _ExcInfoType = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None, + **kwargs: object, ) -> None: ... def info( + self, msg: object, *args: object, exc_info: _ExcInfoType = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None, + **kwargs: object, ) -> None: ... def warning( + self, msg: object, *args: object, exc_info: _ExcInfoType = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None, + **kwargs: object, ) -> None: ... def warn( + self, msg: object, *args: object, exc_info: _ExcInfoType = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None, + **kwargs: object, ) -> None: ... def error( + self, msg: object, *args: object, exc_info: _ExcInfoType = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None, - ) -> None: ... - def critical( - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - stacklevel: int = 1, - extra: Mapping[str, object] | None = None, + **kwargs: object, ) -> None: ... def exception( + self, msg: object, *args: object, exc_info: _ExcInfoType = True, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None, + **kwargs: object, ) -> None: ... - def log( - level: int, + def critical( + self, msg: object, *args: object, exc_info: _ExcInfoType = None, stack_info: bool = False, stacklevel: int = 1, extra: Mapping[str, object] | None = None, + **kwargs: object, ) -> None: ... - -else: - def debug( - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - extra: Mapping[str, object] | None = None, - ) -> None: ... - def info( - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - extra: Mapping[str, object] | None = None, - ) -> None: ... - def warning( - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - extra: Mapping[str, object] | None = None, - ) -> None: ... - def warn( - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - extra: Mapping[str, object] | None = None, - ) -> None: ... - def error( - msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, - extra: Mapping[str, object] | None = None, - ) -> None: ... - def critical( + def log( + self, + level: int, msg: object, *args: object, exc_info: _ExcInfoType = None, stack_info: bool = False, + stacklevel: int = 1, extra: Mapping[str, object] | None = None, + **kwargs: object, ) -> None: ... - def exception( - msg: object, - *args: object, - exc_info: _ExcInfoType = True, - stack_info: bool = False, - extra: Mapping[str, object] | None = None, - ) -> None: ... - def log( + def isEnabledFor(self, level: int) -> bool: ... + def getEffectiveLevel(self) -> int: ... + def setLevel(self, level: _Level) -> None: ... + def hasHandlers(self) -> bool: ... + def _log( + self, level: int, msg: object, - *args: object, - exc_info: _ExcInfoType = None, - stack_info: bool = False, + args: _ArgsType, + exc_info: _ExcInfoType | None = None, extra: Mapping[str, object] | None = None, - ) -> None: ... + stack_info: bool = False, + ) -> None: ... # undocumented + @property + def name(self) -> str: ... # undocumented + if sys.version_info >= (3, 11): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... + +def getLogger(name: str | None = None) -> Logger: ... +def getLoggerClass() -> type[Logger]: ... +def getLogRecordFactory() -> Callable[..., LogRecord]: ... +def debug( + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, +) -> None: ... +def info( + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, +) -> None: ... +def warning( + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, +) -> None: ... +def warn( + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, +) -> None: ... +def error( + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, +) -> None: ... +def critical( + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, +) -> None: ... +def exception( + msg: object, + *args: object, + exc_info: _ExcInfoType = True, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, +) -> None: ... +def log( + level: int, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, +) -> None: ... fatal = critical @@ -783,20 +565,6 @@ if sys.version_info >= (3, 9): errors: str | None = ..., ) -> None: ... -elif sys.version_info >= (3, 8): - def basicConfig( - *, - filename: StrPath | None = ..., - filemode: str = ..., - format: str = ..., - datefmt: str | None = ..., - style: _FormatStyle = ..., - level: _Level | None = ..., - stream: SupportsWrite[str] | None = ..., - handlers: Iterable[Handler] | None = ..., - force: bool = ..., - ) -> None: ... - else: def basicConfig( *, @@ -808,6 +576,7 @@ else: level: _Level | None = ..., stream: SupportsWrite[str] | None = ..., handlers: Iterable[Handler] | None = ..., + force: bool = ..., ) -> None: ... def shutdown(handlerList: Sequence[Any] = ...) -> None: ... # handlerList is undocumented @@ -863,8 +632,7 @@ class PercentStyle: # undocumented default_format: str asctime_format: str asctime_search: str - if sys.version_info >= (3, 8): - validation_pattern: Pattern[str] + validation_pattern: Pattern[str] _fmt: str if sys.version_info >= (3, 10): def __init__(self, fmt: str, *, defaults: Mapping[str, Any] | None = None) -> None: ... @@ -872,9 +640,7 @@ class PercentStyle: # undocumented def __init__(self, fmt: str) -> None: ... def usesTime(self) -> bool: ... - if sys.version_info >= (3, 8): - def validate(self) -> None: ... - + def validate(self) -> None: ... def format(self, record: Any) -> str: ... class StrFormatStyle(PercentStyle): # undocumented diff --git a/mypy/typeshed/stdlib/logging/config.pyi b/mypy/typeshed/stdlib/logging/config.pyi index 0a61e5b16870..7a26846addbb 100644 --- a/mypy/typeshed/stdlib/logging/config.pyi +++ b/mypy/typeshed/stdlib/logging/config.pyi @@ -4,8 +4,8 @@ from collections.abc import Callable, Hashable, Iterable, Sequence from configparser import RawConfigParser from re import Pattern from threading import Thread -from typing import IO, Any, overload -from typing_extensions import Literal, Required, SupportsIndex, TypeAlias, TypedDict +from typing import IO, Any, Literal, SupportsIndex, TypedDict, overload +from typing_extensions import Required, TypeAlias from . import Filter, Filterer, Formatter, Handler, Logger, _FilterType, _FormatStyle, _Level @@ -28,16 +28,9 @@ else: class _LoggerConfiguration(_RootLoggerConfiguration, TypedDict, total=False): propagate: bool -if sys.version_info >= (3, 8): - _FormatterConfigurationTypedDict = TypedDict( - "_FormatterConfigurationTypedDict", {"class": str, "format": str, "datefmt": str, "style": _FormatStyle}, total=False - ) -else: - _FormatterConfigurationTypedDict = TypedDict( - "_FormatterConfigurationTypedDict", - {"class": str, "format": str, "datefmt": str, "style": _FormatStyle, "validate": bool}, - total=False, - ) +_FormatterConfigurationTypedDict = TypedDict( + "_FormatterConfigurationTypedDict", {"class": str, "format": str, "datefmt": str, "style": _FormatStyle}, total=False +) class _FilterConfigurationTypedDict(TypedDict): name: str diff --git a/mypy/typeshed/stdlib/lzma.pyi b/mypy/typeshed/stdlib/lzma.pyi index be61cac08139..05248ee0e710 100644 --- a/mypy/typeshed/stdlib/lzma.pyi +++ b/mypy/typeshed/stdlib/lzma.pyi @@ -1,8 +1,8 @@ from _compression import BaseStream from _typeshed import ReadableBuffer, StrOrBytesPath from collections.abc import Mapping, Sequence -from typing import IO, Any, TextIO, overload -from typing_extensions import Literal, Self, TypeAlias, final +from typing import IO, Any, Literal, TextIO, final, overload +from typing_extensions import Self, TypeAlias __all__ = [ "CHECK_NONE", diff --git a/mypy/typeshed/stdlib/macpath.pyi b/mypy/typeshed/stdlib/macpath.pyi deleted file mode 100644 index 37821f44b200..000000000000 --- a/mypy/typeshed/stdlib/macpath.pyi +++ /dev/null @@ -1,104 +0,0 @@ -from _typeshed import BytesPath, StrOrBytesPath, StrPath -from genericpath import ( - commonprefix as commonprefix, - exists as exists, - getatime as getatime, - getctime as getctime, - getmtime as getmtime, - getsize as getsize, - isdir as isdir, - isfile as isfile, - samefile as samefile, - sameopenfile as sameopenfile, - samestat as samestat, -) -from os import PathLike - -# Re-export common definitions from posixpath to reduce duplication -from posixpath import ( - abspath as abspath, - curdir as curdir, - defpath as defpath, - devnull as devnull, - expanduser as expanduser, - expandvars as expandvars, - extsep as extsep, - isabs as isabs, - lexists as lexists, - pardir as pardir, - pathsep as pathsep, - sep as sep, - splitdrive as splitdrive, - splitext as splitext, - supports_unicode_filenames as supports_unicode_filenames, -) -from typing import AnyStr, overload - -__all__ = [ - "normcase", - "isabs", - "join", - "splitdrive", - "split", - "splitext", - "basename", - "dirname", - "commonprefix", - "getsize", - "getmtime", - "getatime", - "getctime", - "islink", - "exists", - "lexists", - "isdir", - "isfile", - "expanduser", - "expandvars", - "normpath", - "abspath", - "curdir", - "pardir", - "sep", - "pathsep", - "defpath", - "altsep", - "extsep", - "devnull", - "realpath", - "supports_unicode_filenames", -] - -altsep: str | None - -@overload -def basename(s: PathLike[AnyStr]) -> AnyStr: ... -@overload -def basename(s: AnyStr) -> AnyStr: ... -@overload -def dirname(s: PathLike[AnyStr]) -> AnyStr: ... -@overload -def dirname(s: AnyStr) -> AnyStr: ... -@overload -def normcase(path: PathLike[AnyStr]) -> AnyStr: ... -@overload -def normcase(path: AnyStr) -> AnyStr: ... -@overload -def normpath(s: PathLike[AnyStr]) -> AnyStr: ... -@overload -def normpath(s: AnyStr) -> AnyStr: ... -@overload -def realpath(path: PathLike[AnyStr]) -> AnyStr: ... -@overload -def realpath(path: AnyStr) -> AnyStr: ... -def islink(s: StrOrBytesPath) -> bool: ... - -# Mypy complains that the signatures overlap, but things seem to behave correctly anyway. -@overload -def join(s: StrPath, *paths: StrPath) -> str: ... -@overload -def join(s: BytesPath, *paths: BytesPath) -> bytes: ... -@overload -def split(s: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr]: ... -@overload -def split(s: AnyStr) -> tuple[AnyStr, AnyStr]: ... diff --git a/mypy/typeshed/stdlib/mailbox.pyi b/mypy/typeshed/stdlib/mailbox.pyi index 8053fad88ea5..1059bfe917e8 100644 --- a/mypy/typeshed/stdlib/mailbox.pyi +++ b/mypy/typeshed/stdlib/mailbox.pyi @@ -5,8 +5,8 @@ from _typeshed import StrPath, SupportsNoArgReadline, SupportsRead from abc import ABCMeta, abstractmethod from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence from types import TracebackType -from typing import IO, Any, AnyStr, Generic, Protocol, TypeVar, overload -from typing_extensions import Literal, Self, TypeAlias +from typing import IO, Any, AnyStr, Generic, Literal, Protocol, TypeVar, overload +from typing_extensions import Self, TypeAlias if sys.version_info >= (3, 9): from types import GenericAlias diff --git a/mypy/typeshed/stdlib/math.pyi b/mypy/typeshed/stdlib/math.pyi index 73b53a713301..ee0693912a8b 100644 --- a/mypy/typeshed/stdlib/math.pyi +++ b/mypy/typeshed/stdlib/math.pyi @@ -1,15 +1,12 @@ import sys from collections.abc import Iterable -from typing import Protocol, SupportsFloat, TypeVar, overload -from typing_extensions import SupportsIndex, TypeAlias +from typing import Protocol, SupportsFloat, SupportsIndex, TypeVar, overload +from typing_extensions import TypeAlias _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) -if sys.version_info >= (3, 8): - _SupportsFloatOrIndex: TypeAlias = SupportsFloat | SupportsIndex -else: - _SupportsFloatOrIndex: TypeAlias = SupportsFloat +_SupportsFloatOrIndex: TypeAlias = SupportsFloat | SupportsIndex e: float pi: float @@ -35,18 +32,12 @@ class _SupportsCeil(Protocol[_T_co]): def ceil(__x: _SupportsCeil[_T]) -> _T: ... @overload def ceil(__x: _SupportsFloatOrIndex) -> int: ... - -if sys.version_info >= (3, 8): - def comb(__n: SupportsIndex, __k: SupportsIndex) -> int: ... - +def comb(__n: SupportsIndex, __k: SupportsIndex) -> int: ... def copysign(__x: _SupportsFloatOrIndex, __y: _SupportsFloatOrIndex) -> float: ... def cos(__x: _SupportsFloatOrIndex) -> float: ... def cosh(__x: _SupportsFloatOrIndex) -> float: ... def degrees(__x: _SupportsFloatOrIndex) -> float: ... - -if sys.version_info >= (3, 8): - def dist(__p: Iterable[_SupportsFloatOrIndex], __q: Iterable[_SupportsFloatOrIndex]) -> float: ... - +def dist(__p: Iterable[_SupportsFloatOrIndex], __q: Iterable[_SupportsFloatOrIndex]) -> float: ... def erf(__x: _SupportsFloatOrIndex) -> float: ... def erfc(__x: _SupportsFloatOrIndex) -> float: ... def exp(__x: _SupportsFloatOrIndex) -> float: ... @@ -56,12 +47,7 @@ if sys.version_info >= (3, 11): def expm1(__x: _SupportsFloatOrIndex) -> float: ... def fabs(__x: _SupportsFloatOrIndex) -> float: ... - -if sys.version_info >= (3, 8): - def factorial(__x: SupportsIndex) -> int: ... - -else: - def factorial(__x: int) -> int: ... +def factorial(__x: SupportsIndex) -> int: ... class _SupportsFloor(Protocol[_T_co]): def __floor__(self) -> _T_co: ... @@ -81,12 +67,7 @@ if sys.version_info >= (3, 9): else: def gcd(__x: SupportsIndex, __y: SupportsIndex) -> int: ... -if sys.version_info >= (3, 8): - def hypot(*coordinates: _SupportsFloatOrIndex) -> float: ... - -else: - def hypot(__x: _SupportsFloatOrIndex, __y: _SupportsFloatOrIndex) -> float: ... - +def hypot(*coordinates: _SupportsFloatOrIndex) -> float: ... def isclose( a: _SupportsFloatOrIndex, b: _SupportsFloatOrIndex, @@ -97,9 +78,7 @@ def isclose( def isinf(__x: _SupportsFloatOrIndex) -> bool: ... def isfinite(__x: _SupportsFloatOrIndex) -> bool: ... def isnan(__x: _SupportsFloatOrIndex) -> bool: ... - -if sys.version_info >= (3, 8): - def isqrt(__n: SupportsIndex) -> int: ... +def isqrt(__n: SupportsIndex) -> int: ... if sys.version_info >= (3, 9): def lcm(*integers: SupportsIndex) -> int: ... @@ -118,17 +97,12 @@ if sys.version_info >= (3, 12): elif sys.version_info >= (3, 9): def nextafter(__x: _SupportsFloatOrIndex, __y: _SupportsFloatOrIndex) -> float: ... -if sys.version_info >= (3, 8): - def perm(__n: SupportsIndex, __k: SupportsIndex | None = None) -> int: ... - +def perm(__n: SupportsIndex, __k: SupportsIndex | None = None) -> int: ... def pow(__x: _SupportsFloatOrIndex, __y: _SupportsFloatOrIndex) -> float: ... - -if sys.version_info >= (3, 8): - @overload - def prod(__iterable: Iterable[SupportsIndex], *, start: SupportsIndex = 1) -> int: ... # type: ignore[overload-overlap] - @overload - def prod(__iterable: Iterable[_SupportsFloatOrIndex], *, start: _SupportsFloatOrIndex = 1) -> float: ... - +@overload +def prod(__iterable: Iterable[SupportsIndex], *, start: SupportsIndex = 1) -> int: ... # type: ignore[overload-overlap] +@overload +def prod(__iterable: Iterable[_SupportsFloatOrIndex], *, start: _SupportsFloatOrIndex = 1) -> float: ... def radians(__x: _SupportsFloatOrIndex) -> float: ... def remainder(__x: _SupportsFloatOrIndex, __y: _SupportsFloatOrIndex) -> float: ... def sin(__x: _SupportsFloatOrIndex) -> float: ... diff --git a/mypy/typeshed/stdlib/mimetypes.pyi b/mypy/typeshed/stdlib/mimetypes.pyi index 532cc5e3ce39..e74b214d3ff1 100644 --- a/mypy/typeshed/stdlib/mimetypes.pyi +++ b/mypy/typeshed/stdlib/mimetypes.pyi @@ -1,4 +1,3 @@ -import sys from _typeshed import StrPath from collections.abc import Sequence from typing import IO @@ -19,12 +18,7 @@ __all__ = [ "common_types", ] -if sys.version_info >= (3, 8): - def guess_type(url: StrPath, strict: bool = True) -> tuple[str | None, str | None]: ... - -else: - def guess_type(url: str, strict: bool = True) -> tuple[str | None, str | None]: ... - +def guess_type(url: StrPath, strict: bool = True) -> tuple[str | None, str | None]: ... def guess_all_extensions(type: str, strict: bool = True) -> list[str]: ... def guess_extension(type: str, strict: bool = True) -> str | None: ... def init(files: Sequence[str] | None = None) -> None: ... @@ -45,11 +39,7 @@ class MimeTypes: types_map_inv: tuple[dict[str, str], dict[str, str]] def __init__(self, filenames: tuple[str, ...] = (), strict: bool = True) -> None: ... def guess_extension(self, type: str, strict: bool = True) -> str | None: ... - if sys.version_info >= (3, 8): - def guess_type(self, url: StrPath, strict: bool = True) -> tuple[str | None, str | None]: ... - else: - def guess_type(self, url: str, strict: bool = True) -> tuple[str | None, str | None]: ... - + def guess_type(self, url: StrPath, strict: bool = True) -> tuple[str | None, str | None]: ... def guess_all_extensions(self, type: str, strict: bool = True) -> list[str]: ... def read(self, filename: str, strict: bool = True) -> None: ... def readfp(self, fp: IO[str], strict: bool = True) -> None: ... diff --git a/mypy/typeshed/stdlib/mmap.pyi b/mypy/typeshed/stdlib/mmap.pyi index 9a213a8b8cf0..6bbb797f054d 100644 --- a/mypy/typeshed/stdlib/mmap.pyi +++ b/mypy/typeshed/stdlib/mmap.pyi @@ -39,11 +39,7 @@ class mmap(Iterable[int], Sized): ) -> None: ... def close(self) -> None: ... - if sys.version_info >= (3, 8): - def flush(self, offset: int = ..., size: int = ...) -> None: ... - else: - def flush(self, offset: int = ..., size: int = ...) -> int: ... - + def flush(self, offset: int = ..., size: int = ...) -> None: ... def move(self, dest: int, src: int, count: int) -> None: ... def read_byte(self) -> int: ... def readline(self) -> bytes: ... @@ -54,7 +50,7 @@ class mmap(Iterable[int], Sized): def write_byte(self, byte: int) -> None: ... def __len__(self) -> int: ... closed: bool - if sys.version_info >= (3, 8) and sys.platform != "win32": + if sys.platform != "win32": def madvise(self, option: int, start: int = ..., length: int = ...) -> None: ... def find(self, sub: ReadableBuffer, start: int = ..., stop: int = ...) -> int: ... @@ -81,7 +77,7 @@ class mmap(Iterable[int], Sized): def __buffer__(self, __flags: int) -> memoryview: ... def __release_buffer__(self, __buffer: memoryview) -> None: ... -if sys.version_info >= (3, 8) and sys.platform != "win32": +if sys.platform != "win32": MADV_NORMAL: int MADV_RANDOM: int MADV_SEQUENTIAL: int @@ -89,28 +85,28 @@ if sys.version_info >= (3, 8) and sys.platform != "win32": MADV_DONTNEED: int MADV_FREE: int - if sys.platform == "linux": - MADV_REMOVE: int - MADV_DONTFORK: int - MADV_DOFORK: int - MADV_HWPOISON: int - MADV_MERGEABLE: int - MADV_UNMERGEABLE: int - # Seems like this constant is not defined in glibc. - # See https://github.com/python/typeshed/pull/5360 for details - # MADV_SOFT_OFFLINE: int - MADV_HUGEPAGE: int - MADV_NOHUGEPAGE: int - MADV_DONTDUMP: int - MADV_DODUMP: int +if sys.platform == "linux": + MADV_REMOVE: int + MADV_DONTFORK: int + MADV_DOFORK: int + MADV_HWPOISON: int + MADV_MERGEABLE: int + MADV_UNMERGEABLE: int + # Seems like this constant is not defined in glibc. + # See https://github.com/python/typeshed/pull/5360 for details + # MADV_SOFT_OFFLINE: int + MADV_HUGEPAGE: int + MADV_NOHUGEPAGE: int + MADV_DONTDUMP: int + MADV_DODUMP: int - # This Values are defined for FreeBSD but type checkers do not support conditions for these - if sys.platform != "linux" and sys.platform != "darwin": - MADV_NOSYNC: int - MADV_AUTOSYNC: int - MADV_NOCORE: int - MADV_CORE: int - MADV_PROTECT: int +# This Values are defined for FreeBSD but type checkers do not support conditions for these +if sys.platform != "linux" and sys.platform != "darwin" and sys.platform != "win32": + MADV_NOSYNC: int + MADV_AUTOSYNC: int + MADV_NOCORE: int + MADV_CORE: int + MADV_PROTECT: int if sys.version_info >= (3, 10) and sys.platform == "darwin": MADV_FREE_REUSABLE: int diff --git a/mypy/typeshed/stdlib/modulefinder.pyi b/mypy/typeshed/stdlib/modulefinder.pyi index 06bb50d26286..132cac5f1878 100644 --- a/mypy/typeshed/stdlib/modulefinder.pyi +++ b/mypy/typeshed/stdlib/modulefinder.pyi @@ -31,23 +31,13 @@ class ModuleFinder: excludes: Container[str] # undocumented replace_paths: Sequence[tuple[str, str]] # undocumented - if sys.version_info >= (3, 8): - def __init__( - self, - path: list[str] | None = None, - debug: int = 0, - excludes: Container[str] | None = None, - replace_paths: Sequence[tuple[str, str]] | None = None, - ) -> None: ... - else: - def __init__( - self, - path: list[str] | None = None, - debug: int = 0, - excludes: Container[str] = [], - replace_paths: Sequence[tuple[str, str]] = [], - ) -> None: ... - + def __init__( + self, + path: list[str] | None = None, + debug: int = 0, + excludes: Container[str] | None = None, + replace_paths: Sequence[tuple[str, str]] | None = None, + ) -> None: ... def msg(self, level: int, str: str, *args: Any) -> None: ... # undocumented def msgin(self, *args: Any) -> None: ... # undocumented def msgout(self, *args: Any) -> None: ... # undocumented diff --git a/mypy/typeshed/stdlib/msilib/__init__.pyi b/mypy/typeshed/stdlib/msilib/__init__.pyi index 9f7367d152ba..106805dab931 100644 --- a/mypy/typeshed/stdlib/msilib/__init__.pyi +++ b/mypy/typeshed/stdlib/msilib/__init__.pyi @@ -1,8 +1,7 @@ import sys from collections.abc import Container, Iterable, Sequence from types import ModuleType -from typing import Any -from typing_extensions import Literal +from typing import Any, Literal if sys.platform == "win32": from _msi import * diff --git a/mypy/typeshed/stdlib/msvcrt.pyi b/mypy/typeshed/stdlib/msvcrt.pyi index 768edbc18ab3..bfd7ec62a9be 100644 --- a/mypy/typeshed/stdlib/msvcrt.pyi +++ b/mypy/typeshed/stdlib/msvcrt.pyi @@ -1,5 +1,5 @@ import sys -from typing_extensions import Final, Literal +from typing import Final, Literal # This module is only available on Windows if sys.platform == "win32": diff --git a/mypy/typeshed/stdlib/multiprocessing/__init__.pyi b/mypy/typeshed/stdlib/multiprocessing/__init__.pyi index 186bd54a021d..2bd6e2883ddb 100644 --- a/mypy/typeshed/stdlib/multiprocessing/__init__.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/__init__.pyi @@ -1,4 +1,3 @@ -import sys from multiprocessing import context, reduction as reducer from multiprocessing.context import ( AuthenticationError as AuthenticationError, @@ -7,7 +6,11 @@ from multiprocessing.context import ( ProcessError as ProcessError, TimeoutError as TimeoutError, ) -from multiprocessing.process import active_children as active_children, current_process as current_process +from multiprocessing.process import ( + active_children as active_children, + current_process as current_process, + parent_process as parent_process, +) # These are technically functions that return instances of these Queue classes. # The stub here doesn't reflect reality exactly -- @@ -19,9 +22,6 @@ from multiprocessing.process import active_children as active_children, current_ from multiprocessing.queues import JoinableQueue as JoinableQueue, Queue as Queue, SimpleQueue as SimpleQueue from multiprocessing.spawn import freeze_support as freeze_support -if sys.version_info >= (3, 8): - from multiprocessing.process import parent_process as parent_process - __all__ = [ "Array", "AuthenticationError", @@ -55,15 +55,13 @@ __all__ = [ "get_logger", "get_start_method", "log_to_stderr", + "parent_process", "reducer", "set_executable", "set_forkserver_preload", "set_start_method", ] -if sys.version_info >= (3, 8): - __all__ += ["parent_process"] - # These functions (really bound methods) # are all autogenerated at runtime here: https://github.com/python/cpython/blob/600c65c094b0b48704d8ec2416930648052ba715/Lib/multiprocessing/__init__.py#L23 RawValue = context._default_context.RawValue diff --git a/mypy/typeshed/stdlib/multiprocessing/connection.pyi b/mypy/typeshed/stdlib/multiprocessing/connection.pyi index 333b8820d84d..7045a81b85be 100644 --- a/mypy/typeshed/stdlib/multiprocessing/connection.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/connection.pyi @@ -3,8 +3,8 @@ import sys import types from _typeshed import ReadableBuffer from collections.abc import Iterable -from typing import Any -from typing_extensions import Self, SupportsIndex, TypeAlias +from typing import Any, SupportsIndex +from typing_extensions import Self, TypeAlias __all__ = ["Client", "Listener", "Pipe", "wait"] diff --git a/mypy/typeshed/stdlib/multiprocessing/context.pyi b/mypy/typeshed/stdlib/multiprocessing/context.pyi index fe3b98024548..1cc8d03ea436 100644 --- a/mypy/typeshed/stdlib/multiprocessing/context.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/context.pyi @@ -8,18 +8,15 @@ from multiprocessing.managers import SyncManager from multiprocessing.pool import Pool as _Pool from multiprocessing.process import BaseProcess from multiprocessing.sharedctypes import SynchronizedArray, SynchronizedBase -from typing import Any, ClassVar, TypeVar, overload -from typing_extensions import Literal, TypeAlias +from typing import Any, ClassVar, Literal, TypeVar, overload +from typing_extensions import TypeAlias if sys.platform != "win32": from multiprocessing.connection import Connection else: from multiprocessing.connection import PipeConnection -if sys.version_info >= (3, 8): - __all__ = () -else: - __all__: list[str] = [] +__all__ = () _LockLike: TypeAlias = synchronize.Lock | synchronize.RLock _CT = TypeVar("_CT", bound=_CData) @@ -39,10 +36,8 @@ class BaseContext: # multiprocessing.*, so the signatures should be identical (modulo self). @staticmethod def current_process() -> BaseProcess: ... - if sys.version_info >= (3, 8): - @staticmethod - def parent_process() -> BaseProcess | None: ... - + @staticmethod + def parent_process() -> BaseProcess | None: ... @staticmethod def active_children() -> list[BaseProcess]: ... def cpu_count(self) -> int: ... @@ -151,8 +146,6 @@ class DefaultContext(BaseContext): def __init__(self, context: BaseContext) -> None: ... def get_start_method(self, allow_none: bool = False) -> str: ... def get_all_start_methods(self) -> list[str]: ... - if sys.version_info < (3, 8): - __all__: ClassVar[list[str]] _default_context: DefaultContext diff --git a/mypy/typeshed/stdlib/multiprocessing/dummy/__init__.pyi b/mypy/typeshed/stdlib/multiprocessing/dummy/__init__.pyi index 967b57ded6c8..804a56e9cbcf 100644 --- a/mypy/typeshed/stdlib/multiprocessing/dummy/__init__.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/dummy/__init__.pyi @@ -12,8 +12,7 @@ from threading import ( RLock as RLock, Semaphore as Semaphore, ) -from typing import Any -from typing_extensions import Literal +from typing import Any, Literal from .connection import Pipe as Pipe diff --git a/mypy/typeshed/stdlib/multiprocessing/managers.pyi b/mypy/typeshed/stdlib/multiprocessing/managers.pyi index c0ef0a3609d0..eb3ac29b1449 100644 --- a/mypy/typeshed/stdlib/multiprocessing/managers.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/managers.pyi @@ -4,19 +4,14 @@ import threading from _typeshed import SupportsKeysAndGetItem, SupportsRichComparison, SupportsRichComparisonT from collections.abc import Callable, Iterable, Iterator, Mapping, MutableMapping, MutableSequence, Sequence from types import TracebackType -from typing import Any, AnyStr, ClassVar, Generic, TypeVar, overload -from typing_extensions import Self, SupportsIndex, TypeAlias +from typing import Any, AnyStr, ClassVar, Generic, SupportsIndex, TypeVar, overload +from typing_extensions import Self, TypeAlias from .connection import Connection from .context import BaseContext +from .shared_memory import _SLT, ShareableList as _ShareableList, SharedMemory as _SharedMemory -if sys.version_info >= (3, 8): - from .shared_memory import _SLT, ShareableList as _ShareableList, SharedMemory as _SharedMemory - - __all__ = ["BaseManager", "SyncManager", "BaseProxy", "Token", "SharedMemoryManager"] - -else: - __all__ = ["BaseManager", "SyncManager", "BaseProxy", "Token"] +__all__ = ["BaseManager", "SyncManager", "BaseProxy", "Token", "SharedMemoryManager"] if sys.version_info >= (3, 9): from types import GenericAlias @@ -208,12 +203,10 @@ class SyncManager(BaseManager): def list(self) -> ListProxy[Any]: ... class RemoteError(Exception): ... +class SharedMemoryServer(Server): ... -if sys.version_info >= (3, 8): - class SharedMemoryServer(Server): ... - - class SharedMemoryManager(BaseManager): - def get_server(self) -> SharedMemoryServer: ... - def SharedMemory(self, size: int) -> _SharedMemory: ... - def ShareableList(self, sequence: Iterable[_SLT] | None) -> _ShareableList[_SLT]: ... - def __del__(self) -> None: ... +class SharedMemoryManager(BaseManager): + def get_server(self) -> SharedMemoryServer: ... + def SharedMemory(self, size: int) -> _SharedMemory: ... + def ShareableList(self, sequence: Iterable[_SLT] | None) -> _ShareableList[_SLT]: ... + def __del__(self) -> None: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/pool.pyi b/mypy/typeshed/stdlib/multiprocessing/pool.pyi index 5ad4bfe93fe9..465c8e08c134 100644 --- a/mypy/typeshed/stdlib/multiprocessing/pool.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/pool.pyi @@ -1,8 +1,8 @@ import sys from collections.abc import Callable, Iterable, Iterator, Mapping from types import TracebackType -from typing import Any, Generic, TypeVar -from typing_extensions import Literal, Self +from typing import Any, Generic, Literal, TypeVar +from typing_extensions import Self if sys.version_info >= (3, 9): from types import GenericAlias @@ -13,18 +13,9 @@ _S = TypeVar("_S") _T = TypeVar("_T") class ApplyResult(Generic[_T]): - if sys.version_info >= (3, 8): - def __init__( - self, pool: Pool, callback: Callable[[_T], object] | None, error_callback: Callable[[BaseException], object] | None - ) -> None: ... - else: - def __init__( - self, - cache: dict[int, ApplyResult[Any]], - callback: Callable[[_T], object] | None, - error_callback: Callable[[BaseException], object] | None, - ) -> None: ... - + def __init__( + self, pool: Pool, callback: Callable[[_T], object] | None, error_callback: Callable[[BaseException], object] | None + ) -> None: ... def get(self, timeout: float | None = None) -> _T: ... def wait(self, timeout: float | None = None) -> None: ... def ready(self) -> bool: ... @@ -36,31 +27,17 @@ class ApplyResult(Generic[_T]): AsyncResult = ApplyResult class MapResult(ApplyResult[list[_T]]): - if sys.version_info >= (3, 8): - def __init__( - self, - pool: Pool, - chunksize: int, - length: int, - callback: Callable[[list[_T]], object] | None, - error_callback: Callable[[BaseException], object] | None, - ) -> None: ... - else: - def __init__( - self, - cache: dict[int, ApplyResult[Any]], - chunksize: int, - length: int, - callback: Callable[[list[_T]], object] | None, - error_callback: Callable[[BaseException], object] | None, - ) -> None: ... + def __init__( + self, + pool: Pool, + chunksize: int, + length: int, + callback: Callable[[list[_T]], object] | None, + error_callback: Callable[[BaseException], object] | None, + ) -> None: ... class IMapIterator(Iterator[_T]): - if sys.version_info >= (3, 8): - def __init__(self, pool: Pool) -> None: ... - else: - def __init__(self, cache: dict[int, IMapIterator[Any]]) -> None: ... - + def __init__(self, pool: Pool) -> None: ... def __iter__(self) -> Self: ... def next(self, timeout: float | None = None) -> _T: ... def __next__(self, timeout: float | None = None) -> _T: ... @@ -120,12 +97,7 @@ class ThreadPool(Pool): ) -> None: ... # undocumented -if sys.version_info >= (3, 8): - INIT: Literal["INIT"] - RUN: Literal["RUN"] - CLOSE: Literal["CLOSE"] - TERMINATE: Literal["TERMINATE"] -else: - RUN: Literal[0] - CLOSE: Literal[1] - TERMINATE: Literal[2] +INIT: Literal["INIT"] +RUN: Literal["RUN"] +CLOSE: Literal["CLOSE"] +TERMINATE: Literal["TERMINATE"] diff --git a/mypy/typeshed/stdlib/multiprocessing/process.pyi b/mypy/typeshed/stdlib/multiprocessing/process.pyi index 9863013fc05f..4d129b27b0e8 100644 --- a/mypy/typeshed/stdlib/multiprocessing/process.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/process.pyi @@ -1,11 +1,7 @@ -import sys from collections.abc import Callable, Iterable, Mapping from typing import Any -if sys.version_info >= (3, 8): - __all__ = ["BaseProcess", "current_process", "active_children", "parent_process"] -else: - __all__ = ["BaseProcess", "current_process", "active_children"] +__all__ = ["BaseProcess", "current_process", "active_children", "parent_process"] class BaseProcess: name: str @@ -40,6 +36,4 @@ class BaseProcess: def current_process() -> BaseProcess: ... def active_children() -> list[BaseProcess]: ... - -if sys.version_info >= (3, 8): - def parent_process() -> BaseProcess | None: ... +def parent_process() -> BaseProcess | None: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/reduction.pyi b/mypy/typeshed/stdlib/multiprocessing/reduction.pyi index e5a8cde8f849..ad80169b463c 100644 --- a/mypy/typeshed/stdlib/multiprocessing/reduction.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/reduction.pyi @@ -8,8 +8,7 @@ from copyreg import _DispatchTableType from multiprocessing import connection from pickle import _ReducedType from socket import socket -from typing import Any -from typing_extensions import Literal +from typing import Any, Literal if sys.platform == "win32": __all__ = ["send_handle", "recv_handle", "ForkingPickler", "register", "dump", "DupHandle", "duplicate", "steal_handle"] @@ -32,13 +31,9 @@ register = ForkingPickler.register def dump(obj: Any, file: SupportsWrite[bytes], protocol: int | None = None) -> None: ... if sys.platform == "win32": - if sys.version_info >= (3, 8): - def duplicate( - handle: int, target_process: int | None = None, inheritable: bool = False, *, source_process: int | None = None - ) -> int: ... - else: - def duplicate(handle: int, target_process: int | None = None, inheritable: bool = False) -> int: ... - + def duplicate( + handle: int, target_process: int | None = None, inheritable: bool = False, *, source_process: int | None = None + ) -> int: ... def steal_handle(source_pid: int, handle: int) -> int: ... def send_handle(conn: connection.PipeConnection, handle: int, destination_pid: int) -> None: ... def recv_handle(conn: connection.PipeConnection) -> int: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/sharedctypes.pyi b/mypy/typeshed/stdlib/multiprocessing/sharedctypes.pyi index 636d58842158..3979f14cf636 100644 --- a/mypy/typeshed/stdlib/multiprocessing/sharedctypes.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/sharedctypes.pyi @@ -4,8 +4,7 @@ from ctypes import _CData, _SimpleCData, c_char from multiprocessing.context import BaseContext from multiprocessing.synchronize import _LockLike from types import TracebackType -from typing import Any, Generic, Protocol, TypeVar, overload -from typing_extensions import Literal +from typing import Any, Generic, Literal, Protocol, TypeVar, overload __all__ = ["RawValue", "RawArray", "Value", "Array", "copy", "synchronized"] diff --git a/mypy/typeshed/stdlib/nntplib.pyi b/mypy/typeshed/stdlib/nntplib.pyi index f948c1430c90..969c657e9aab 100644 --- a/mypy/typeshed/stdlib/nntplib.pyi +++ b/mypy/typeshed/stdlib/nntplib.pyi @@ -5,8 +5,8 @@ import sys from _typeshed import Unused from builtins import list as _list # conflicts with a method named "list" from collections.abc import Iterable -from typing import IO, Any, NamedTuple -from typing_extensions import Literal, Self, TypeAlias +from typing import IO, Any, Literal, NamedTuple +from typing_extensions import Self, TypeAlias __all__ = [ "NNTP", diff --git a/mypy/typeshed/stdlib/ntpath.pyi b/mypy/typeshed/stdlib/ntpath.pyi index 1a58b52de050..bfa880ee03a8 100644 --- a/mypy/typeshed/stdlib/ntpath.pyi +++ b/mypy/typeshed/stdlib/ntpath.pyi @@ -42,11 +42,11 @@ from posixpath import ( splitext as splitext, supports_unicode_filenames as supports_unicode_filenames, ) +from typing import AnyStr, overload +from typing_extensions import LiteralString if sys.version_info >= (3, 12): from posixpath import isjunction as isjunction, splitroot as splitroot -from typing import AnyStr, overload -from typing_extensions import LiteralString __all__ = [ "normcase", diff --git a/mypy/typeshed/stdlib/numbers.pyi b/mypy/typeshed/stdlib/numbers.pyi index 55f21041ae44..c2a0301d5636 100644 --- a/mypy/typeshed/stdlib/numbers.pyi +++ b/mypy/typeshed/stdlib/numbers.pyi @@ -1,8 +1,9 @@ # Note: these stubs are incomplete. The more complex type # signatures are currently omitted. +from _typeshed import Incomplete from abc import ABCMeta, abstractmethod -from typing import Any, SupportsFloat, overload +from typing import SupportsFloat, overload __all__ = ["Number", "Complex", "Real", "Rational", "Integral"] @@ -16,36 +17,36 @@ class Complex(Number): def __bool__(self) -> bool: ... @property @abstractmethod - def real(self) -> Any: ... + def real(self): ... @property @abstractmethod - def imag(self) -> Any: ... + def imag(self): ... @abstractmethod - def __add__(self, other: Any) -> Any: ... + def __add__(self, other): ... @abstractmethod - def __radd__(self, other: Any) -> Any: ... + def __radd__(self, other): ... @abstractmethod - def __neg__(self) -> Any: ... + def __neg__(self): ... @abstractmethod - def __pos__(self) -> Any: ... - def __sub__(self, other: Any) -> Any: ... - def __rsub__(self, other: Any) -> Any: ... + def __pos__(self): ... + def __sub__(self, other): ... + def __rsub__(self, other): ... @abstractmethod - def __mul__(self, other: Any) -> Any: ... + def __mul__(self, other): ... @abstractmethod - def __rmul__(self, other: Any) -> Any: ... + def __rmul__(self, other): ... @abstractmethod - def __truediv__(self, other: Any) -> Any: ... + def __truediv__(self, other): ... @abstractmethod - def __rtruediv__(self, other: Any) -> Any: ... + def __rtruediv__(self, other): ... @abstractmethod - def __pow__(self, exponent: Any) -> Any: ... + def __pow__(self, exponent): ... @abstractmethod - def __rpow__(self, base: Any) -> Any: ... + def __rpow__(self, base): ... @abstractmethod def __abs__(self) -> Real: ... @abstractmethod - def conjugate(self) -> Any: ... + def conjugate(self): ... @abstractmethod def __eq__(self, other: object) -> bool: ... @@ -63,27 +64,27 @@ class Real(Complex, SupportsFloat): def __round__(self, ndigits: None = None) -> int: ... @abstractmethod @overload - def __round__(self, ndigits: int) -> Any: ... - def __divmod__(self, other: Any) -> Any: ... - def __rdivmod__(self, other: Any) -> Any: ... + def __round__(self, ndigits: int): ... + def __divmod__(self, other): ... + def __rdivmod__(self, other): ... @abstractmethod - def __floordiv__(self, other: Any) -> int: ... + def __floordiv__(self, other) -> int: ... @abstractmethod - def __rfloordiv__(self, other: Any) -> int: ... + def __rfloordiv__(self, other) -> int: ... @abstractmethod - def __mod__(self, other: Any) -> Any: ... + def __mod__(self, other): ... @abstractmethod - def __rmod__(self, other: Any) -> Any: ... + def __rmod__(self, other): ... @abstractmethod - def __lt__(self, other: Any) -> bool: ... + def __lt__(self, other) -> bool: ... @abstractmethod - def __le__(self, other: Any) -> bool: ... + def __le__(self, other) -> bool: ... def __complex__(self) -> complex: ... @property - def real(self) -> Any: ... + def real(self): ... @property - def imag(self) -> Any: ... - def conjugate(self) -> Any: ... + def imag(self): ... + def conjugate(self): ... class Rational(Real): @property @@ -99,29 +100,29 @@ class Integral(Rational): def __int__(self) -> int: ... def __index__(self) -> int: ... @abstractmethod - def __pow__(self, exponent: Any, modulus: Any | None = None) -> Any: ... + def __pow__(self, exponent, modulus: Incomplete | None = None): ... @abstractmethod - def __lshift__(self, other: Any) -> Any: ... + def __lshift__(self, other): ... @abstractmethod - def __rlshift__(self, other: Any) -> Any: ... + def __rlshift__(self, other): ... @abstractmethod - def __rshift__(self, other: Any) -> Any: ... + def __rshift__(self, other): ... @abstractmethod - def __rrshift__(self, other: Any) -> Any: ... + def __rrshift__(self, other): ... @abstractmethod - def __and__(self, other: Any) -> Any: ... + def __and__(self, other): ... @abstractmethod - def __rand__(self, other: Any) -> Any: ... + def __rand__(self, other): ... @abstractmethod - def __xor__(self, other: Any) -> Any: ... + def __xor__(self, other): ... @abstractmethod - def __rxor__(self, other: Any) -> Any: ... + def __rxor__(self, other): ... @abstractmethod - def __or__(self, other: Any) -> Any: ... + def __or__(self, other): ... @abstractmethod - def __ror__(self, other: Any) -> Any: ... + def __ror__(self, other): ... @abstractmethod - def __invert__(self) -> Any: ... + def __invert__(self): ... def __float__(self) -> float: ... @property def numerator(self) -> int: ... diff --git a/mypy/typeshed/stdlib/opcode.pyi b/mypy/typeshed/stdlib/opcode.pyi index f852489ffacf..02da0c9f954a 100644 --- a/mypy/typeshed/stdlib/opcode.pyi +++ b/mypy/typeshed/stdlib/opcode.pyi @@ -1,5 +1,5 @@ import sys -from typing_extensions import Literal +from typing import Literal __all__ = [ "cmp_op", @@ -56,8 +56,4 @@ opmap: dict[str, int] HAVE_ARGUMENT: Literal[90] EXTENDED_ARG: Literal[144] -if sys.version_info >= (3, 8): - def stack_effect(__opcode: int, __oparg: int | None = None, *, jump: bool | None = None) -> int: ... - -else: - def stack_effect(__opcode: int, __oparg: int | None = None) -> int: ... +def stack_effect(__opcode: int, __oparg: int | None = None, *, jump: bool | None = None) -> int: ... diff --git a/mypy/typeshed/stdlib/os/__init__.pyi b/mypy/typeshed/stdlib/os/__init__.pyi index e92dd7a095d6..3b277460d8f6 100644 --- a/mypy/typeshed/stdlib/os/__init__.pyi +++ b/mypy/typeshed/stdlib/os/__init__.pyi @@ -25,17 +25,28 @@ from collections.abc import Callable, Iterable, Iterator, Mapping, MutableMappin from contextlib import AbstractContextManager from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper as _TextIOWrapper from subprocess import Popen -from typing import IO, Any, AnyStr, BinaryIO, Generic, NoReturn, Protocol, TypeVar, overload, runtime_checkable -from typing_extensions import Final, Literal, Self, TypeAlias, Unpack, final +from typing import ( + IO, + Any, + AnyStr, + BinaryIO, + Final, + Generic, + Literal, + NoReturn, + Protocol, + TypeVar, + final, + overload, + runtime_checkable, +) +from typing_extensions import Self, TypeAlias, Unpack from . import path as _path if sys.version_info >= (3, 9): from types import GenericAlias -if sys.platform != "win32": - from resource import struct_rusage - # This unnecessary alias is to work around various errors path = _path @@ -361,9 +372,8 @@ class stat_result(structseq[float], tuple[int, int, int, int, int, int, int, flo if sys.platform == "win32": @property def st_file_attributes(self) -> int: ... - if sys.version_info >= (3, 8): - @property - def st_reparse_tag(self) -> int: ... + @property + def st_reparse_tag(self) -> int: ... if sys.version_info >= (3, 12): @property def st_birthtime(self) -> float: ... # time of file creation in seconds @@ -965,6 +975,8 @@ else: def waitid(__idtype: int, __ident: int, __options: int) -> waitid_result | None: ... + from resource import struct_rusage + def wait3(options: int) -> tuple[int, int, struct_rusage]: ... def wait4(pid: int, options: int) -> tuple[int, int, struct_rusage]: ... def WCOREDUMP(__status: int) -> bool: ... @@ -975,36 +987,35 @@ else: def WEXITSTATUS(status: int) -> int: ... def WSTOPSIG(status: int) -> int: ... def WTERMSIG(status: int) -> int: ... - if sys.version_info >= (3, 8): - def posix_spawn( - __path: StrOrBytesPath, - __argv: _ExecVArgs, - __env: _ExecEnv, - *, - file_actions: Sequence[tuple[Any, ...]] | None = ..., - setpgroup: int | None = ..., - resetids: bool = ..., - setsid: bool = ..., - setsigmask: Iterable[int] = ..., - setsigdef: Iterable[int] = ..., - scheduler: tuple[Any, sched_param] | None = ..., - ) -> int: ... - def posix_spawnp( - __path: StrOrBytesPath, - __argv: _ExecVArgs, - __env: _ExecEnv, - *, - file_actions: Sequence[tuple[Any, ...]] | None = ..., - setpgroup: int | None = ..., - resetids: bool = ..., - setsid: bool = ..., - setsigmask: Iterable[int] = ..., - setsigdef: Iterable[int] = ..., - scheduler: tuple[Any, sched_param] | None = ..., - ) -> int: ... - POSIX_SPAWN_OPEN: int - POSIX_SPAWN_CLOSE: int - POSIX_SPAWN_DUP2: int + def posix_spawn( + __path: StrOrBytesPath, + __argv: _ExecVArgs, + __env: _ExecEnv, + *, + file_actions: Sequence[tuple[Any, ...]] | None = ..., + setpgroup: int | None = ..., + resetids: bool = ..., + setsid: bool = ..., + setsigmask: Iterable[int] = ..., + setsigdef: Iterable[int] = ..., + scheduler: tuple[Any, sched_param] | None = ..., + ) -> int: ... + def posix_spawnp( + __path: StrOrBytesPath, + __argv: _ExecVArgs, + __env: _ExecEnv, + *, + file_actions: Sequence[tuple[Any, ...]] | None = ..., + setpgroup: int | None = ..., + resetids: bool = ..., + setsid: bool = ..., + setsigmask: Iterable[int] = ..., + setsigdef: Iterable[int] = ..., + scheduler: tuple[Any, sched_param] | None = ..., + ) -> int: ... + POSIX_SPAWN_OPEN: int + POSIX_SPAWN_CLOSE: int + POSIX_SPAWN_DUP2: int if sys.platform != "win32": @final @@ -1048,38 +1059,36 @@ if sys.platform != "win32": after_in_child: Callable[..., Any] | None = ..., ) -> None: ... -if sys.version_info >= (3, 8): - if sys.platform == "win32": - class _AddedDllDirectory: - path: str | None - def __init__(self, path: str | None, cookie: _T, remove_dll_directory: Callable[[_T], object]) -> None: ... - def close(self) -> None: ... - def __enter__(self) -> Self: ... - def __exit__(self, *args: Unused) -> None: ... - - def add_dll_directory(path: str) -> _AddedDllDirectory: ... - if sys.platform == "linux": - MFD_CLOEXEC: int - MFD_ALLOW_SEALING: int - MFD_HUGETLB: int - MFD_HUGE_SHIFT: int - MFD_HUGE_MASK: int - MFD_HUGE_64KB: int - MFD_HUGE_512KB: int - MFD_HUGE_1MB: int - MFD_HUGE_2MB: int - MFD_HUGE_8MB: int - MFD_HUGE_16MB: int - MFD_HUGE_32MB: int - MFD_HUGE_256MB: int - MFD_HUGE_512MB: int - MFD_HUGE_1GB: int - MFD_HUGE_2GB: int - MFD_HUGE_16GB: int - def memfd_create(name: str, flags: int = ...) -> int: ... - def copy_file_range( - src: int, dst: int, count: int, offset_src: int | None = ..., offset_dst: int | None = ... - ) -> int: ... +if sys.platform == "win32": + class _AddedDllDirectory: + path: str | None + def __init__(self, path: str | None, cookie: _T, remove_dll_directory: Callable[[_T], object]) -> None: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... + + def add_dll_directory(path: str) -> _AddedDllDirectory: ... + +if sys.platform == "linux": + MFD_CLOEXEC: int + MFD_ALLOW_SEALING: int + MFD_HUGETLB: int + MFD_HUGE_SHIFT: int + MFD_HUGE_MASK: int + MFD_HUGE_64KB: int + MFD_HUGE_512KB: int + MFD_HUGE_1MB: int + MFD_HUGE_2MB: int + MFD_HUGE_8MB: int + MFD_HUGE_16MB: int + MFD_HUGE_32MB: int + MFD_HUGE_256MB: int + MFD_HUGE_512MB: int + MFD_HUGE_1GB: int + MFD_HUGE_2GB: int + MFD_HUGE_16GB: int + def memfd_create(name: str, flags: int = ...) -> int: ... + def copy_file_range(src: int, dst: int, count: int, offset_src: int | None = ..., offset_dst: int | None = ...) -> int: ... if sys.version_info >= (3, 9): def waitstatus_to_exitcode(status: int) -> int: ... diff --git a/mypy/typeshed/stdlib/ossaudiodev.pyi b/mypy/typeshed/stdlib/ossaudiodev.pyi index d956a89729fd..b9ee3edab033 100644 --- a/mypy/typeshed/stdlib/ossaudiodev.pyi +++ b/mypy/typeshed/stdlib/ossaudiodev.pyi @@ -1,6 +1,5 @@ import sys -from typing import Any, overload -from typing_extensions import Literal +from typing import Any, Literal, overload if sys.platform != "win32" and sys.platform != "darwin": AFMT_AC3: int diff --git a/mypy/typeshed/stdlib/parser.pyi b/mypy/typeshed/stdlib/parser.pyi index cce8594eac58..bafc8015fed9 100644 --- a/mypy/typeshed/stdlib/parser.pyi +++ b/mypy/typeshed/stdlib/parser.pyi @@ -1,8 +1,7 @@ from _typeshed import StrOrBytesPath from collections.abc import Sequence from types import CodeType -from typing import Any -from typing_extensions import final +from typing import Any, final def expr(source: str) -> STType: ... def suite(source: str) -> STType: ... diff --git a/mypy/typeshed/stdlib/pathlib.pyi b/mypy/typeshed/stdlib/pathlib.pyi index 10ffa4a778e8..c3b0b7ad6337 100644 --- a/mypy/typeshed/stdlib/pathlib.pyi +++ b/mypy/typeshed/stdlib/pathlib.pyi @@ -14,8 +14,8 @@ from collections.abc import Callable, Generator, Iterator, Sequence from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper from os import PathLike, stat_result from types import TracebackType -from typing import IO, Any, BinaryIO, overload -from typing_extensions import Literal, Self +from typing import IO, Any, BinaryIO, Literal, overload +from typing_extensions import Self if sys.version_info >= (3, 9): from types import GenericAlias @@ -196,13 +196,9 @@ class Path(PurePath): if sys.version_info >= (3, 9): def readlink(self) -> Self: ... - if sys.version_info >= (3, 8): - def rename(self, target: str | PurePath) -> Self: ... - def replace(self, target: str | PurePath) -> Self: ... - else: - def rename(self, target: str | PurePath) -> None: ... - def replace(self, target: str | PurePath) -> None: ... + def rename(self, target: str | PurePath) -> Self: ... + def replace(self, target: str | PurePath) -> Self: ... def resolve(self, strict: bool = False) -> Self: ... def rmdir(self) -> None: ... def symlink_to(self, target: StrOrBytesPath, target_is_directory: bool = False) -> None: ... @@ -210,11 +206,7 @@ class Path(PurePath): def hardlink_to(self, target: StrOrBytesPath) -> None: ... def touch(self, mode: int = 0o666, exist_ok: bool = True) -> None: ... - if sys.version_info >= (3, 8): - def unlink(self, missing_ok: bool = False) -> None: ... - else: - def unlink(self) -> None: ... - + def unlink(self, missing_ok: bool = False) -> None: ... @classmethod def home(cls) -> Self: ... def absolute(self) -> Self: ... @@ -229,7 +221,7 @@ class Path(PurePath): ) -> int: ... else: def write_text(self, data: str, encoding: str | None = None, errors: str | None = None) -> int: ... - if sys.version_info >= (3, 8) and sys.version_info < (3, 12): + if sys.version_info < (3, 12): def link_to(self, target: StrOrBytesPath) -> None: ... if sys.version_info >= (3, 12): def walk( diff --git a/mypy/typeshed/stdlib/pickle.pyi b/mypy/typeshed/stdlib/pickle.pyi index cf3995d74f5d..0a4d439976ff 100644 --- a/mypy/typeshed/stdlib/pickle.pyi +++ b/mypy/typeshed/stdlib/pickle.pyi @@ -1,10 +1,10 @@ -import sys from _typeshed import ReadableBuffer, SupportsWrite from collections.abc import Callable, Iterable, Iterator, Mapping -from typing import Any, ClassVar, Protocol, SupportsBytes -from typing_extensions import SupportsIndex, TypeAlias, final +from typing import Any, ClassVar, Protocol, SupportsBytes, SupportsIndex, final +from typing_extensions import TypeAlias __all__ = [ + "PickleBuffer", "PickleError", "PicklingError", "UnpicklingError", @@ -30,6 +30,7 @@ __all__ = [ "BINUNICODE", "BINUNICODE8", "BUILD", + "BYTEARRAY8", "DEFAULT_PROTOCOL", "DICT", "DUP", @@ -61,6 +62,7 @@ __all__ = [ "NEWOBJ", "NEWOBJ_EX", "NEWTRUE", + "NEXT_BUFFER", "NONE", "OBJ", "PERSID", @@ -68,6 +70,7 @@ __all__ = [ "POP_MARK", "PROTO", "PUT", + "READONLY_BUFFER", "REDUCE", "SETITEM", "SETITEMS", @@ -85,9 +88,6 @@ __all__ = [ "UNICODE", ] -if sys.version_info >= (3, 8): - __all__ += ["BYTEARRAY8", "NEXT_BUFFER", "PickleBuffer", "READONLY_BUFFER"] - HIGHEST_PROTOCOL: int DEFAULT_PROTOCOL: int @@ -97,48 +97,43 @@ class _ReadableFileobj(Protocol): def read(self, __n: int) -> bytes: ... def readline(self) -> bytes: ... -if sys.version_info >= (3, 8): - @final - class PickleBuffer: - def __init__(self, buffer: ReadableBuffer) -> None: ... - def raw(self) -> memoryview: ... - def release(self) -> None: ... - def __buffer__(self, __flags: int) -> memoryview: ... - def __release_buffer__(self, __buffer: memoryview) -> None: ... - _BufferCallback: TypeAlias = Callable[[PickleBuffer], Any] | None - def dump( - obj: Any, - file: SupportsWrite[bytes], - protocol: int | None = None, - *, - fix_imports: bool = True, - buffer_callback: _BufferCallback = None, - ) -> None: ... - def dumps( - obj: Any, protocol: int | None = None, *, fix_imports: bool = True, buffer_callback: _BufferCallback = None - ) -> bytes: ... - def load( - file: _ReadableFileobj, - *, - fix_imports: bool = True, - encoding: str = "ASCII", - errors: str = "strict", - buffers: Iterable[Any] | None = (), - ) -> Any: ... - def loads( - __data: ReadableBuffer, - *, - fix_imports: bool = True, - encoding: str = "ASCII", - errors: str = "strict", - buffers: Iterable[Any] | None = (), - ) -> Any: ... +@final +class PickleBuffer: + def __init__(self, buffer: ReadableBuffer) -> None: ... + def raw(self) -> memoryview: ... + def release(self) -> None: ... + def __buffer__(self, __flags: int) -> memoryview: ... + def __release_buffer__(self, __buffer: memoryview) -> None: ... + +_BufferCallback: TypeAlias = Callable[[PickleBuffer], Any] | None -else: - def dump(obj: Any, file: SupportsWrite[bytes], protocol: int | None = None, *, fix_imports: bool = True) -> None: ... - def dumps(obj: Any, protocol: int | None = None, *, fix_imports: bool = True) -> bytes: ... - def load(file: _ReadableFileobj, *, fix_imports: bool = True, encoding: str = "ASCII", errors: str = "strict") -> Any: ... - def loads(data: ReadableBuffer, *, fix_imports: bool = True, encoding: str = "ASCII", errors: str = "strict") -> Any: ... +def dump( + obj: Any, + file: SupportsWrite[bytes], + protocol: int | None = None, + *, + fix_imports: bool = True, + buffer_callback: _BufferCallback = None, +) -> None: ... +def dumps( + obj: Any, protocol: int | None = None, *, fix_imports: bool = True, buffer_callback: _BufferCallback = None +) -> bytes: ... +def load( + file: _ReadableFileobj, + *, + fix_imports: bool = True, + encoding: str = "ASCII", + errors: str = "strict", + buffers: Iterable[Any] | None = (), +) -> Any: ... +def loads( + __data: ReadableBuffer, + *, + fix_imports: bool = True, + encoding: str = "ASCII", + errors: str = "strict", + buffers: Iterable[Any] | None = (), +) -> Any: ... class PickleError(Exception): ... class PicklingError(PickleError): ... @@ -158,19 +153,15 @@ class Pickler: bin: bool # undocumented dispatch: ClassVar[dict[type, Callable[[Unpickler, Any], None]]] # undocumented, _Pickler only - if sys.version_info >= (3, 8): - def __init__( - self, - file: SupportsWrite[bytes], - protocol: int | None = ..., - *, - fix_imports: bool = ..., - buffer_callback: _BufferCallback = ..., - ) -> None: ... - def reducer_override(self, obj: Any) -> Any: ... - else: - def __init__(self, file: SupportsWrite[bytes], protocol: int | None = ..., *, fix_imports: bool = ...) -> None: ... - + def __init__( + self, + file: SupportsWrite[bytes], + protocol: int | None = ..., + *, + fix_imports: bool = ..., + buffer_callback: _BufferCallback = ..., + ) -> None: ... + def reducer_override(self, obj: Any) -> Any: ... def dump(self, __obj: Any) -> None: ... def clear_memo(self) -> None: ... def persistent_id(self, obj: Any) -> Any: ... @@ -178,21 +169,15 @@ class Pickler: class Unpickler: dispatch: ClassVar[dict[int, Callable[[Unpickler], None]]] # undocumented, _Unpickler only - if sys.version_info >= (3, 8): - def __init__( - self, - file: _ReadableFileobj, - *, - fix_imports: bool = ..., - encoding: str = ..., - errors: str = ..., - buffers: Iterable[Any] | None = ..., - ) -> None: ... - else: - def __init__( - self, file: _ReadableFileobj, *, fix_imports: bool = ..., encoding: str = ..., errors: str = ... - ) -> None: ... - + def __init__( + self, + file: _ReadableFileobj, + *, + fix_imports: bool = ..., + encoding: str = ..., + errors: str = ..., + buffers: Iterable[Any] | None = ..., + ) -> None: ... def load(self) -> Any: ... def find_class(self, __module_name: str, __global_name: str) -> Any: ... def persistent_load(self, pid: Any) -> Any: ... @@ -272,11 +257,10 @@ STACK_GLOBAL: bytes MEMOIZE: bytes FRAME: bytes -if sys.version_info >= (3, 8): - # Protocol 5 - BYTEARRAY8: bytes - NEXT_BUFFER: bytes - READONLY_BUFFER: bytes +# protocol 5 +BYTEARRAY8: bytes +NEXT_BUFFER: bytes +READONLY_BUFFER: bytes def encode_long(x: int) -> bytes: ... # undocumented def decode_long(data: Iterable[SupportsIndex] | SupportsBytes | ReadableBuffer) -> int: ... # undocumented diff --git a/mypy/typeshed/stdlib/platform.pyi b/mypy/typeshed/stdlib/platform.pyi index 483d6c454c2e..f0e6d4123e1d 100644 --- a/mypy/typeshed/stdlib/platform.pyi +++ b/mypy/typeshed/stdlib/platform.pyi @@ -1,37 +1,10 @@ import sys - -if sys.version_info < (3, 8): - import os - - DEV_NULL = os.devnull from typing import NamedTuple -if sys.version_info >= (3, 8): - def libc_ver(executable: str | None = None, lib: str = "", version: str = "", chunksize: int = 16384) -> tuple[str, str]: ... - -else: - def libc_ver( - executable: str = sys.executable, lib: str = "", version: str = "", chunksize: int = 16384 - ) -> tuple[str, str]: ... - -if sys.version_info < (3, 8): - def linux_distribution( - distname: str = "", - version: str = "", - id: str = "", - supported_dists: tuple[str, ...] = ..., - full_distribution_name: bool = ..., - ) -> tuple[str, str, str]: ... - def dist( - distname: str = "", version: str = "", id: str = "", supported_dists: tuple[str, ...] = ... - ) -> tuple[str, str, str]: ... - +def libc_ver(executable: str | None = None, lib: str = "", version: str = "", chunksize: int = 16384) -> tuple[str, str]: ... def win32_ver(release: str = "", version: str = "", csd: str = "", ptype: str = "") -> tuple[str, str, str, str]: ... - -if sys.version_info >= (3, 8): - def win32_edition() -> str: ... - def win32_is_iot() -> bool: ... - +def win32_edition() -> str: ... +def win32_is_iot() -> bool: ... def mac_ver( release: str = "", versioninfo: tuple[str, str, str] = ("", "", ""), machine: str = "" ) -> tuple[str, tuple[str, str, str], str]: ... diff --git a/mypy/typeshed/stdlib/plistlib.pyi b/mypy/typeshed/stdlib/plistlib.pyi index bd5525484514..f7912a784987 100644 --- a/mypy/typeshed/stdlib/plistlib.pyi +++ b/mypy/typeshed/stdlib/plistlib.pyi @@ -6,39 +6,9 @@ from enum import Enum from typing import IO, Any from typing_extensions import Self -if sys.version_info >= (3, 9): - __all__ = ["InvalidFileException", "FMT_XML", "FMT_BINARY", "load", "dump", "loads", "dumps", "UID"] -elif sys.version_info >= (3, 8): - __all__ = [ - "readPlist", - "writePlist", - "readPlistFromBytes", - "writePlistToBytes", - "Data", - "InvalidFileException", - "FMT_XML", - "FMT_BINARY", - "load", - "dump", - "loads", - "dumps", - "UID", - ] -else: - __all__ = [ - "readPlist", - "writePlist", - "readPlistFromBytes", - "writePlistToBytes", - "Data", - "InvalidFileException", - "FMT_XML", - "FMT_BINARY", - "load", - "dump", - "loads", - "dumps", - ] +__all__ = ["InvalidFileException", "FMT_XML", "FMT_BINARY", "load", "dump", "loads", "dumps", "UID"] +if sys.version_info < (3, 9): + __all__ += ["readPlist", "writePlist", "readPlistFromBytes", "writePlistToBytes", "Data"] class PlistFormat(Enum): FMT_XML: int @@ -46,8 +16,23 @@ class PlistFormat(Enum): FMT_XML = PlistFormat.FMT_XML FMT_BINARY = PlistFormat.FMT_BINARY +if sys.version_info >= (3, 13): + def load( + fp: IO[bytes], + *, + fmt: PlistFormat | None = None, + dict_type: type[MutableMapping[str, Any]] = ..., + aware_datetime: bool = False, + ) -> Any: ... + def loads( + value: ReadableBuffer | str, + *, + fmt: PlistFormat | None = None, + dict_type: type[MutableMapping[str, Any]] = ..., + aware_datetime: bool = False, + ) -> Any: ... -if sys.version_info >= (3, 9): +elif sys.version_info >= (3, 9): def load(fp: IO[bytes], *, fmt: PlistFormat | None = None, dict_type: type[MutableMapping[str, Any]] = ...) -> Any: ... def loads( value: ReadableBuffer, *, fmt: PlistFormat | None = None, dict_type: type[MutableMapping[str, Any]] = ... @@ -69,21 +54,41 @@ else: dict_type: type[MutableMapping[str, Any]] = ..., ) -> Any: ... -def dump( - value: Mapping[str, Any] | list[Any] | tuple[Any, ...] | str | bool | float | bytes | bytearray | datetime, - fp: IO[bytes], - *, - fmt: PlistFormat = ..., - sort_keys: bool = True, - skipkeys: bool = False, -) -> None: ... -def dumps( - value: Mapping[str, Any] | list[Any] | tuple[Any, ...] | str | bool | float | bytes | bytearray | datetime, - *, - fmt: PlistFormat = ..., - skipkeys: bool = False, - sort_keys: bool = True, -) -> bytes: ... +if sys.version_info >= (3, 13): + def dump( + value: Mapping[str, Any] | list[Any] | tuple[Any, ...] | str | bool | float | bytes | bytearray | datetime, + fp: IO[bytes], + *, + fmt: PlistFormat = ..., + sort_keys: bool = True, + skipkeys: bool = False, + aware_datetime: bool = False, + ) -> None: ... + def dumps( + value: Mapping[str, Any] | list[Any] | tuple[Any, ...] | str | bool | float | bytes | bytearray | datetime, + *, + fmt: PlistFormat = ..., + skipkeys: bool = False, + sort_keys: bool = True, + aware_datetime: bool = False, + ) -> bytes: ... + +else: + def dump( + value: Mapping[str, Any] | list[Any] | tuple[Any, ...] | str | bool | float | bytes | bytearray | datetime, + fp: IO[bytes], + *, + fmt: PlistFormat = ..., + sort_keys: bool = True, + skipkeys: bool = False, + ) -> None: ... + def dumps( + value: Mapping[str, Any] | list[Any] | tuple[Any, ...] | str | bool | float | bytes | bytearray | datetime, + *, + fmt: PlistFormat = ..., + skipkeys: bool = False, + sort_keys: bool = True, + ) -> bytes: ... if sys.version_info < (3, 9): def readPlist(pathOrFile: str | IO[bytes]) -> Any: ... @@ -96,14 +101,13 @@ if sys.version_info < (3, 9): data: bytes def __init__(self, data: bytes) -> None: ... -if sys.version_info >= (3, 8): - class UID: - data: int - def __init__(self, data: int) -> None: ... - def __index__(self) -> int: ... - def __reduce__(self) -> tuple[type[Self], tuple[int]]: ... - def __hash__(self) -> int: ... - def __eq__(self, other: object) -> bool: ... +class UID: + data: int + def __init__(self, data: int) -> None: ... + def __index__(self) -> int: ... + def __reduce__(self) -> tuple[type[Self], tuple[int]]: ... + def __hash__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... class InvalidFileException(ValueError): def __init__(self, message: str = "Invalid file") -> None: ... diff --git a/mypy/typeshed/stdlib/poplib.pyi b/mypy/typeshed/stdlib/poplib.pyi index 808e7e5222af..12f1d16a0d6f 100644 --- a/mypy/typeshed/stdlib/poplib.pyi +++ b/mypy/typeshed/stdlib/poplib.pyi @@ -3,8 +3,8 @@ import ssl import sys from builtins import list as _list # conflicts with a method named "list" from re import Pattern -from typing import Any, BinaryIO, NoReturn, overload -from typing_extensions import Literal, TypeAlias +from typing import Any, BinaryIO, Literal, NoReturn, overload +from typing_extensions import TypeAlias __all__ = ["POP3", "error_proto", "POP3_SSL"] diff --git a/mypy/typeshed/stdlib/posix.pyi b/mypy/typeshed/stdlib/posix.pyi index 81cc93c5aa66..6cba003bbd5f 100644 --- a/mypy/typeshed/stdlib/posix.pyi +++ b/mypy/typeshed/stdlib/posix.pyi @@ -51,6 +51,9 @@ if sys.platform != "win32": P_ALL as P_ALL, P_PGID as P_PGID, P_PID as P_PID, + POSIX_SPAWN_CLOSE as POSIX_SPAWN_CLOSE, + POSIX_SPAWN_DUP2 as POSIX_SPAWN_DUP2, + POSIX_SPAWN_OPEN as POSIX_SPAWN_OPEN, PRIO_PGRP as PRIO_PGRP, PRIO_PROCESS as PRIO_PROCESS, PRIO_USER as PRIO_USER, @@ -161,12 +164,17 @@ if sys.platform != "win32": pathconf as pathconf, pathconf_names as pathconf_names, pipe as pipe, + posix_spawn as posix_spawn, + posix_spawnp as posix_spawnp, pread as pread, + preadv as preadv, putenv as putenv, pwrite as pwrite, + pwritev as pwritev, read as read, readlink as readlink, readv as readv, + register_at_fork as register_at_fork, remove as remove, rename as rename, replace as replace, @@ -222,48 +230,28 @@ if sys.platform != "win32": writev as writev, ) - if sys.platform != "darwin": - from os import EX_NOTFOUND as EX_NOTFOUND + if sys.version_info >= (3, 9): + from os import CLD_KILLED as CLD_KILLED, CLD_STOPPED as CLD_STOPPED, waitstatus_to_exitcode as waitstatus_to_exitcode - if sys.platform == "linux": - from os import ( - GRND_NONBLOCK as GRND_NONBLOCK, - GRND_RANDOM as GRND_RANDOM, - RTLD_DEEPBIND as RTLD_DEEPBIND, - XATTR_CREATE as XATTR_CREATE, - XATTR_REPLACE as XATTR_REPLACE, - XATTR_SIZE_MAX as XATTR_SIZE_MAX, - getrandom as getrandom, - getxattr as getxattr, - listxattr as listxattr, - removexattr as removexattr, - setxattr as setxattr, - ) + if sys.version_info >= (3, 11): + from os import login_tty as login_tty - if sys.version_info >= (3, 10): - from os import ( - EFD_CLOEXEC as EFD_CLOEXEC, - EFD_NONBLOCK as EFD_NONBLOCK, - EFD_SEMAPHORE as EFD_SEMAPHORE, - SPLICE_F_MORE as SPLICE_F_MORE, - SPLICE_F_MOVE as SPLICE_F_MOVE, - SPLICE_F_NONBLOCK as SPLICE_F_NONBLOCK, - eventfd as eventfd, - eventfd_read as eventfd_read, - eventfd_write as eventfd_write, - splice as splice, - ) - else: + if sys.platform != "linux": from os import chflags as chflags, lchflags as lchflags, lchmod as lchmod if sys.platform != "darwin": from os import ( + EX_NOTFOUND as EX_NOTFOUND, POSIX_FADV_DONTNEED as POSIX_FADV_DONTNEED, POSIX_FADV_NOREUSE as POSIX_FADV_NOREUSE, POSIX_FADV_NORMAL as POSIX_FADV_NORMAL, POSIX_FADV_RANDOM as POSIX_FADV_RANDOM, POSIX_FADV_SEQUENTIAL as POSIX_FADV_SEQUENTIAL, POSIX_FADV_WILLNEED as POSIX_FADV_WILLNEED, + RWF_DSYNC as RWF_DSYNC, + RWF_HIPRI as RWF_HIPRI, + RWF_NOWAIT as RWF_NOWAIT, + RWF_SYNC as RWF_SYNC, fdatasync as fdatasync, getresgid as getresgid, getresuid as getresuid, @@ -286,78 +274,85 @@ if sys.platform != "win32": if sys.version_info >= (3, 10): from os import RWF_APPEND as RWF_APPEND - if sys.version_info >= (3, 11): - from os import login_tty as login_tty - - if sys.version_info >= (3, 9): - from os import CLD_KILLED as CLD_KILLED, CLD_STOPPED as CLD_STOPPED, waitstatus_to_exitcode as waitstatus_to_exitcode - - if sys.platform == "linux": - from os import P_PIDFD as P_PIDFD, pidfd_open as pidfd_open - - if sys.version_info >= (3, 8): + if sys.platform == "linux": from os import ( - POSIX_SPAWN_CLOSE as POSIX_SPAWN_CLOSE, - POSIX_SPAWN_DUP2 as POSIX_SPAWN_DUP2, - POSIX_SPAWN_OPEN as POSIX_SPAWN_OPEN, - posix_spawn as posix_spawn, - posix_spawnp as posix_spawnp, + GRND_NONBLOCK as GRND_NONBLOCK, + GRND_RANDOM as GRND_RANDOM, + MFD_ALLOW_SEALING as MFD_ALLOW_SEALING, + MFD_CLOEXEC as MFD_CLOEXEC, + MFD_HUGE_1GB as MFD_HUGE_1GB, + MFD_HUGE_1MB as MFD_HUGE_1MB, + MFD_HUGE_2GB as MFD_HUGE_2GB, + MFD_HUGE_2MB as MFD_HUGE_2MB, + MFD_HUGE_8MB as MFD_HUGE_8MB, + MFD_HUGE_16GB as MFD_HUGE_16GB, + MFD_HUGE_16MB as MFD_HUGE_16MB, + MFD_HUGE_32MB as MFD_HUGE_32MB, + MFD_HUGE_64KB as MFD_HUGE_64KB, + MFD_HUGE_256MB as MFD_HUGE_256MB, + MFD_HUGE_512KB as MFD_HUGE_512KB, + MFD_HUGE_512MB as MFD_HUGE_512MB, + MFD_HUGE_MASK as MFD_HUGE_MASK, + MFD_HUGE_SHIFT as MFD_HUGE_SHIFT, + MFD_HUGETLB as MFD_HUGETLB, + RTLD_DEEPBIND as RTLD_DEEPBIND, + XATTR_CREATE as XATTR_CREATE, + XATTR_REPLACE as XATTR_REPLACE, + XATTR_SIZE_MAX as XATTR_SIZE_MAX, + copy_file_range as copy_file_range, + getrandom as getrandom, + getxattr as getxattr, + listxattr as listxattr, + memfd_create as memfd_create, + removexattr as removexattr, + setxattr as setxattr, ) - if sys.platform == "linux": + if sys.version_info >= (3, 9): + from os import P_PIDFD as P_PIDFD, pidfd_open as pidfd_open + + if sys.version_info >= (3, 10): from os import ( - MFD_ALLOW_SEALING as MFD_ALLOW_SEALING, - MFD_CLOEXEC as MFD_CLOEXEC, - MFD_HUGE_1GB as MFD_HUGE_1GB, - MFD_HUGE_1MB as MFD_HUGE_1MB, - MFD_HUGE_2GB as MFD_HUGE_2GB, - MFD_HUGE_2MB as MFD_HUGE_2MB, - MFD_HUGE_8MB as MFD_HUGE_8MB, - MFD_HUGE_16GB as MFD_HUGE_16GB, - MFD_HUGE_16MB as MFD_HUGE_16MB, - MFD_HUGE_32MB as MFD_HUGE_32MB, - MFD_HUGE_64KB as MFD_HUGE_64KB, - MFD_HUGE_256MB as MFD_HUGE_256MB, - MFD_HUGE_512KB as MFD_HUGE_512KB, - MFD_HUGE_512MB as MFD_HUGE_512MB, - MFD_HUGE_MASK as MFD_HUGE_MASK, - MFD_HUGE_SHIFT as MFD_HUGE_SHIFT, - MFD_HUGETLB as MFD_HUGETLB, - copy_file_range as copy_file_range, - memfd_create as memfd_create, + EFD_CLOEXEC as EFD_CLOEXEC, + EFD_NONBLOCK as EFD_NONBLOCK, + EFD_SEMAPHORE as EFD_SEMAPHORE, + SPLICE_F_MORE as SPLICE_F_MORE, + SPLICE_F_MOVE as SPLICE_F_MOVE, + SPLICE_F_NONBLOCK as SPLICE_F_NONBLOCK, + eventfd as eventfd, + eventfd_read as eventfd_read, + eventfd_write as eventfd_write, + splice as splice, ) - from os import preadv as preadv, pwritev as pwritev, register_at_fork as register_at_fork - - if sys.platform != "darwin": - from os import RWF_DSYNC as RWF_DSYNC, RWF_HIPRI as RWF_HIPRI, RWF_NOWAIT as RWF_NOWAIT, RWF_SYNC as RWF_SYNC - if sys.version_info >= (3, 12) and sys.platform == "linux": - from os import ( - CLONE_FILES as CLONE_FILES, - CLONE_FS as CLONE_FS, - CLONE_NEWCGROUP as CLONE_NEWCGROUP, - CLONE_NEWIPC as CLONE_NEWIPC, - CLONE_NEWNET as CLONE_NEWNET, - CLONE_NEWNS as CLONE_NEWNS, - CLONE_NEWPID as CLONE_NEWPID, - CLONE_NEWTIME as CLONE_NEWTIME, - CLONE_NEWUSER as CLONE_NEWUSER, - CLONE_NEWUTS as CLONE_NEWUTS, - CLONE_SIGHAND as CLONE_SIGHAND, - CLONE_SYSVSEM as CLONE_SYSVSEM, - CLONE_THREAD as CLONE_THREAD, - CLONE_VM as CLONE_VM, - setns as setns, - unshare as unshare, - ) + if sys.version_info >= (3, 12): + from os import ( + CLONE_FILES as CLONE_FILES, + CLONE_FS as CLONE_FS, + CLONE_NEWCGROUP as CLONE_NEWCGROUP, + CLONE_NEWIPC as CLONE_NEWIPC, + CLONE_NEWNET as CLONE_NEWNET, + CLONE_NEWNS as CLONE_NEWNS, + CLONE_NEWPID as CLONE_NEWPID, + CLONE_NEWTIME as CLONE_NEWTIME, + CLONE_NEWUSER as CLONE_NEWUSER, + CLONE_NEWUTS as CLONE_NEWUTS, + CLONE_SIGHAND as CLONE_SIGHAND, + CLONE_SYSVSEM as CLONE_SYSVSEM, + CLONE_THREAD as CLONE_THREAD, + CLONE_VM as CLONE_VM, + setns as setns, + unshare as unshare, + ) - if sys.version_info >= (3, 12) and sys.platform == "darwin": - from os import ( - PRIO_DARWIN_BG as PRIO_DARWIN_BG, - PRIO_DARWIN_NONUI as PRIO_DARWIN_NONUI, - PRIO_DARWIN_PROCESS as PRIO_DARWIN_PROCESS, - PRIO_DARWIN_THREAD as PRIO_DARWIN_THREAD, - ) + if sys.platform == "darwin": + if sys.version_info >= (3, 12): + from os import ( + PRIO_DARWIN_BG as PRIO_DARWIN_BG, + PRIO_DARWIN_NONUI as PRIO_DARWIN_NONUI, + PRIO_DARWIN_PROCESS as PRIO_DARWIN_PROCESS, + PRIO_DARWIN_THREAD as PRIO_DARWIN_THREAD, + ) # Not same as os.environ or os.environb # Because of this variable, we can't do "from posix import *" in os/__init__.pyi diff --git a/mypy/typeshed/stdlib/posixpath.pyi b/mypy/typeshed/stdlib/posixpath.pyi index 45a8ad7ec6a4..29e7c0f01017 100644 --- a/mypy/typeshed/stdlib/posixpath.pyi +++ b/mypy/typeshed/stdlib/posixpath.pyi @@ -1,6 +1,6 @@ import sys from _typeshed import AnyOrLiteralStr, BytesPath, FileDescriptorOrPath, StrOrBytesPath, StrPath -from collections.abc import Sequence +from collections.abc import Iterable from genericpath import ( commonprefix as commonprefix, exists as exists, @@ -102,11 +102,11 @@ def normpath(path: PathLike[AnyStr]) -> AnyStr: ... @overload def normpath(path: AnyOrLiteralStr) -> AnyOrLiteralStr: ... @overload -def commonpath(paths: Sequence[LiteralString]) -> LiteralString: ... +def commonpath(paths: Iterable[LiteralString]) -> LiteralString: ... @overload -def commonpath(paths: Sequence[StrPath]) -> str: ... +def commonpath(paths: Iterable[StrPath]) -> str: ... @overload -def commonpath(paths: Sequence[BytesPath]) -> bytes: ... +def commonpath(paths: Iterable[BytesPath]) -> bytes: ... # First parameter is not actually pos-only, # but must be defined as pos-only in the stub or cross-platform code doesn't type-check, diff --git a/mypy/typeshed/stdlib/pprint.pyi b/mypy/typeshed/stdlib/pprint.pyi index 5a909c69b077..171878f4165d 100644 --- a/mypy/typeshed/stdlib/pprint.pyi +++ b/mypy/typeshed/stdlib/pprint.pyi @@ -1,10 +1,7 @@ import sys from typing import IO -if sys.version_info >= (3, 8): - __all__ = ["pprint", "pformat", "isreadable", "isrecursive", "saferepr", "PrettyPrinter", "pp"] -else: - __all__ = ["pprint", "pformat", "isreadable", "isrecursive", "saferepr", "PrettyPrinter"] +__all__ = ["pprint", "pformat", "isreadable", "isrecursive", "saferepr", "PrettyPrinter", "pp"] if sys.version_info >= (3, 10): def pformat( @@ -18,7 +15,7 @@ if sys.version_info >= (3, 10): underscore_numbers: bool = False, ) -> str: ... -elif sys.version_info >= (3, 8): +else: def pformat( object: object, indent: int = 1, @@ -29,9 +26,6 @@ elif sys.version_info >= (3, 8): sort_dicts: bool = True, ) -> str: ... -else: - def pformat(object: object, indent: int = 1, width: int = 80, depth: int | None = None, *, compact: bool = False) -> str: ... - if sys.version_info >= (3, 10): def pp( object: object, @@ -45,7 +39,7 @@ if sys.version_info >= (3, 10): underscore_numbers: bool = ..., ) -> None: ... -elif sys.version_info >= (3, 8): +else: def pp( object: object, stream: IO[str] | None = ..., @@ -70,18 +64,6 @@ if sys.version_info >= (3, 10): underscore_numbers: bool = False, ) -> None: ... -elif sys.version_info >= (3, 8): - def pprint( - object: object, - stream: IO[str] | None = None, - indent: int = 1, - width: int = 80, - depth: int | None = None, - *, - compact: bool = False, - sort_dicts: bool = True, - ) -> None: ... - else: def pprint( object: object, @@ -91,6 +73,7 @@ else: depth: int | None = None, *, compact: bool = False, + sort_dicts: bool = True, ) -> None: ... def isreadable(object: object) -> bool: ... @@ -110,17 +93,6 @@ class PrettyPrinter: sort_dicts: bool = True, underscore_numbers: bool = False, ) -> None: ... - elif sys.version_info >= (3, 8): - def __init__( - self, - indent: int = 1, - width: int = 80, - depth: int | None = None, - stream: IO[str] | None = None, - *, - compact: bool = False, - sort_dicts: bool = True, - ) -> None: ... else: def __init__( self, @@ -130,6 +102,7 @@ class PrettyPrinter: stream: IO[str] | None = None, *, compact: bool = False, + sort_dicts: bool = True, ) -> None: ... def pformat(self, object: object) -> str: ... diff --git a/mypy/typeshed/stdlib/pstats.pyi b/mypy/typeshed/stdlib/pstats.pyi index 44ce33469ff9..a6ffd54de005 100644 --- a/mypy/typeshed/stdlib/pstats.pyi +++ b/mypy/typeshed/stdlib/pstats.pyi @@ -3,8 +3,8 @@ from _typeshed import StrEnum, StrOrBytesPath from collections.abc import Iterable from cProfile import Profile as _cProfile from profile import Profile -from typing import IO, Any, overload -from typing_extensions import Literal, Self, TypeAlias +from typing import IO, Any, Literal, overload +from typing_extensions import Self, TypeAlias if sys.version_info >= (3, 9): __all__ = ["Stats", "SortKey", "FunctionProfile", "StatsProfile"] diff --git a/mypy/typeshed/stdlib/pty.pyi b/mypy/typeshed/stdlib/pty.pyi index a6a2d8fabb69..022b08046c54 100644 --- a/mypy/typeshed/stdlib/pty.pyi +++ b/mypy/typeshed/stdlib/pty.pyi @@ -1,6 +1,7 @@ import sys from collections.abc import Callable, Iterable -from typing_extensions import Literal, TypeAlias +from typing import Literal +from typing_extensions import TypeAlias if sys.platform != "win32": __all__ = ["openpty", "fork", "spawn"] diff --git a/mypy/typeshed/stdlib/pwd.pyi b/mypy/typeshed/stdlib/pwd.pyi index 80813479d7af..64e831bcecce 100644 --- a/mypy/typeshed/stdlib/pwd.pyi +++ b/mypy/typeshed/stdlib/pwd.pyi @@ -1,7 +1,6 @@ import sys from _typeshed import structseq -from typing import Any -from typing_extensions import Final, final +from typing import Any, Final, final if sys.platform != "win32": @final diff --git a/mypy/typeshed/stdlib/py_compile.pyi b/mypy/typeshed/stdlib/py_compile.pyi index 48f1d7dc3e70..81561a202883 100644 --- a/mypy/typeshed/stdlib/py_compile.pyi +++ b/mypy/typeshed/stdlib/py_compile.pyi @@ -17,27 +17,15 @@ class PycInvalidationMode(enum.Enum): UNCHECKED_HASH: int def _get_default_invalidation_mode() -> PycInvalidationMode: ... - -if sys.version_info >= (3, 8): - def compile( - file: AnyStr, - cfile: AnyStr | None = None, - dfile: AnyStr | None = None, - doraise: bool = False, - optimize: int = -1, - invalidation_mode: PycInvalidationMode | None = None, - quiet: int = 0, - ) -> AnyStr | None: ... - -else: - def compile( - file: AnyStr, - cfile: AnyStr | None = None, - dfile: AnyStr | None = None, - doraise: bool = False, - optimize: int = -1, - invalidation_mode: PycInvalidationMode | None = None, - ) -> AnyStr | None: ... +def compile( + file: AnyStr, + cfile: AnyStr | None = None, + dfile: AnyStr | None = None, + doraise: bool = False, + optimize: int = -1, + invalidation_mode: PycInvalidationMode | None = None, + quiet: int = 0, +) -> AnyStr | None: ... if sys.version_info >= (3, 10): def main() -> None: ... diff --git a/mypy/typeshed/stdlib/pydoc.pyi b/mypy/typeshed/stdlib/pydoc.pyi index 1b09bcb059e4..3134de79352d 100644 --- a/mypy/typeshed/stdlib/pydoc.pyi +++ b/mypy/typeshed/stdlib/pydoc.pyi @@ -5,8 +5,8 @@ from builtins import list as _list # "list" conflicts with method name from collections.abc import Callable, Container, Mapping, MutableMapping from reprlib import Repr from types import MethodType, ModuleType, TracebackType -from typing import IO, Any, AnyStr, NoReturn, TypeVar -from typing_extensions import Final, TypeGuard +from typing import IO, Any, AnyStr, Final, NoReturn, TypeVar +from typing_extensions import TypeGuard __all__ = ["help"] diff --git a/mypy/typeshed/stdlib/pyexpat/__init__.pyi b/mypy/typeshed/stdlib/pyexpat/__init__.pyi index 9e1eea08be54..92d926ebd332 100644 --- a/mypy/typeshed/stdlib/pyexpat/__init__.pyi +++ b/mypy/typeshed/stdlib/pyexpat/__init__.pyi @@ -1,8 +1,8 @@ from _typeshed import ReadableBuffer, SupportsRead from collections.abc import Callable from pyexpat import errors as errors, model as model -from typing import Any -from typing_extensions import TypeAlias, final +from typing import Any, final +from typing_extensions import TypeAlias EXPAT_VERSION: str # undocumented version_info: tuple[int, int, int] # undocumented diff --git a/mypy/typeshed/stdlib/re.pyi b/mypy/typeshed/stdlib/re.pyi index ec532ca3cffe..84c6cfceb1de 100644 --- a/mypy/typeshed/stdlib/re.pyi +++ b/mypy/typeshed/stdlib/re.pyi @@ -4,8 +4,8 @@ import sys from _typeshed import ReadableBuffer from collections.abc import Callable, Iterator, Mapping from sre_constants import error as error -from typing import Any, AnyStr, Generic, TypeVar, overload -from typing_extensions import Literal, TypeAlias, final +from typing import Any, AnyStr, Generic, Literal, TypeVar, final, overload +from typing_extensions import TypeAlias if sys.version_info >= (3, 9): from types import GenericAlias diff --git a/mypy/typeshed/stdlib/resource.pyi b/mypy/typeshed/stdlib/resource.pyi index 57cefb4681ac..31c55111360a 100644 --- a/mypy/typeshed/stdlib/resource.pyi +++ b/mypy/typeshed/stdlib/resource.pyi @@ -1,6 +1,6 @@ import sys from _typeshed import structseq -from typing_extensions import Final, final +from typing import Final, final if sys.platform != "win32": RLIMIT_AS: int diff --git a/mypy/typeshed/stdlib/select.pyi b/mypy/typeshed/stdlib/select.pyi index 5e2828e42c30..f2cfc881c1da 100644 --- a/mypy/typeshed/stdlib/select.pyi +++ b/mypy/typeshed/stdlib/select.pyi @@ -2,8 +2,8 @@ import sys from _typeshed import FileDescriptorLike from collections.abc import Iterable from types import TracebackType -from typing import Any -from typing_extensions import Self, final +from typing import Any, final +from typing_extensions import Self if sys.platform != "win32": PIPE_BUF: int diff --git a/mypy/typeshed/stdlib/shlex.pyi b/mypy/typeshed/stdlib/shlex.pyi index c4fd23d60666..3fda03b5694a 100644 --- a/mypy/typeshed/stdlib/shlex.pyi +++ b/mypy/typeshed/stdlib/shlex.pyi @@ -1,18 +1,11 @@ -import sys from collections.abc import Iterable from typing import TextIO from typing_extensions import Self -if sys.version_info >= (3, 8): - __all__ = ["shlex", "split", "quote", "join"] -else: - __all__ = ["shlex", "split", "quote"] +__all__ = ["shlex", "split", "quote", "join"] def split(s: str, comments: bool = False, posix: bool = True) -> list[str]: ... - -if sys.version_info >= (3, 8): - def join(split_command: Iterable[str]) -> str: ... - +def join(split_command: Iterable[str]) -> str: ... def quote(s: str) -> str: ... class shlex(Iterable[str]): diff --git a/mypy/typeshed/stdlib/shutil.pyi b/mypy/typeshed/stdlib/shutil.pyi index 78e930920073..f6440aa27513 100644 --- a/mypy/typeshed/stdlib/shutil.pyi +++ b/mypy/typeshed/stdlib/shutil.pyi @@ -48,12 +48,7 @@ class ExecError(OSError): ... class ReadError(OSError): ... class RegistryError(Exception): ... -if sys.version_info >= (3, 8): - def copyfileobj(fsrc: SupportsRead[AnyStr], fdst: SupportsWrite[AnyStr], length: int = 0) -> None: ... - -else: - def copyfileobj(fsrc: SupportsRead[AnyStr], fdst: SupportsWrite[AnyStr], length: int = 16384) -> None: ... - +def copyfileobj(fsrc: SupportsRead[AnyStr], fdst: SupportsWrite[AnyStr], length: int = 0) -> None: ... def copyfile(src: StrOrBytesPath, dst: _StrOrBytesPathT, *, follow_symlinks: bool = True) -> _StrOrBytesPathT: ... def copymode(src: StrOrBytesPath, dst: StrOrBytesPath, *, follow_symlinks: bool = True) -> None: ... def copystat(src: StrOrBytesPath, dst: StrOrBytesPath, *, follow_symlinks: bool = True) -> None: ... @@ -66,27 +61,15 @@ def copy2(src: StrPath, dst: StrPath, *, follow_symlinks: bool = True) -> _PathR @overload def copy2(src: BytesPath, dst: BytesPath, *, follow_symlinks: bool = True) -> _PathReturn: ... def ignore_patterns(*patterns: StrPath) -> Callable[[Any, list[str]], set[str]]: ... - -if sys.version_info >= (3, 8): - def copytree( - src: StrPath, - dst: StrPath, - symlinks: bool = False, - ignore: None | Callable[[str, list[str]], Iterable[str]] | Callable[[StrPath, list[str]], Iterable[str]] = None, - copy_function: Callable[[str, str], object] = ..., - ignore_dangling_symlinks: bool = False, - dirs_exist_ok: bool = False, - ) -> _PathReturn: ... - -else: - def copytree( - src: StrPath, - dst: StrPath, - symlinks: bool = False, - ignore: None | Callable[[str, list[str]], Iterable[str]] | Callable[[StrPath, list[str]], Iterable[str]] = None, - copy_function: Callable[[str, str], object] = ..., - ignore_dangling_symlinks: bool = False, - ) -> _PathReturn: ... +def copytree( + src: StrPath, + dst: StrPath, + symlinks: bool = False, + ignore: None | Callable[[str, list[str]], Iterable[str]] | Callable[[StrPath, list[str]], Iterable[str]] = None, + copy_function: Callable[[str, str], object] = ..., + ignore_dangling_symlinks: bool = False, + dirs_exist_ok: bool = False, +) -> _PathReturn: ... _OnErrorCallback: TypeAlias = Callable[[Callable[..., Any], str, Any], object] _OnExcCallback: TypeAlias = Callable[[Callable[..., Any], str, Exception], object] @@ -161,16 +144,10 @@ def chown(path: FileDescriptorOrPath, user: None = None, *, group: str | int) -> def chown(path: FileDescriptorOrPath, user: None, group: str | int) -> None: ... @overload def chown(path: FileDescriptorOrPath, user: str | int, group: str | int) -> None: ... - -if sys.version_info >= (3, 8): - @overload - def which(cmd: _StrPathT, mode: int = 1, path: StrPath | None = None) -> str | _StrPathT | None: ... - @overload - def which(cmd: bytes, mode: int = 1, path: StrPath | None = None) -> bytes | None: ... - -else: - def which(cmd: _StrPathT, mode: int = 1, path: StrPath | None = None) -> str | _StrPathT | None: ... - +@overload +def which(cmd: _StrPathT, mode: int = 1, path: StrPath | None = None) -> str | _StrPathT | None: ... +@overload +def which(cmd: bytes, mode: int = 1, path: StrPath | None = None) -> bytes | None: ... def make_archive( base_name: str, format: str, @@ -192,15 +169,9 @@ def register_archive_format( name: str, function: Callable[[str, str], object], extra_args: None = None, description: str = "" ) -> None: ... def unregister_archive_format(name: str) -> None: ... - -if sys.version_info >= (3, 8): - def unpack_archive( - filename: StrPath, extract_dir: StrPath | None = None, format: str | None = None, *, filter: _TarfileFilter | None = None - ) -> None: ... - -else: - def unpack_archive(filename: StrPath, extract_dir: StrPath | None = None, format: str | None = None) -> None: ... - +def unpack_archive( + filename: StrPath, extract_dir: StrPath | None = None, format: str | None = None, *, filter: _TarfileFilter | None = None +) -> None: ... @overload def register_unpack_format( name: str, diff --git a/mypy/typeshed/stdlib/signal.pyi b/mypy/typeshed/stdlib/signal.pyi index 906a6dabe192..910424c01c31 100644 --- a/mypy/typeshed/stdlib/signal.pyi +++ b/mypy/typeshed/stdlib/signal.pyi @@ -3,8 +3,8 @@ from _typeshed import structseq from collections.abc import Callable, Iterable from enum import IntEnum from types import FrameType -from typing import Any -from typing_extensions import Final, Never, TypeAlias, final +from typing import Any, Final, final +from typing_extensions import Never, TypeAlias NSIG: int @@ -179,11 +179,9 @@ else: def sigtimedwait(sigset: Iterable[int], timeout: float) -> struct_siginfo | None: ... def sigwaitinfo(sigset: Iterable[int]) -> struct_siginfo: ... -if sys.version_info >= (3, 8): - def strsignal(__signalnum: _SIGNUM) -> str | None: ... - def valid_signals() -> set[Signals]: ... - def raise_signal(__signalnum: _SIGNUM) -> None: ... - +def strsignal(__signalnum: _SIGNUM) -> str | None: ... +def valid_signals() -> set[Signals]: ... +def raise_signal(__signalnum: _SIGNUM) -> None: ... def set_wakeup_fd(fd: int, *, warn_on_full_buffer: bool = ...) -> int: ... if sys.version_info >= (3, 9): diff --git a/mypy/typeshed/stdlib/socket.pyi b/mypy/typeshed/stdlib/socket.pyi index cc0cbe3709af..ce5e35228fe4 100644 --- a/mypy/typeshed/stdlib/socket.pyi +++ b/mypy/typeshed/stdlib/socket.pyi @@ -4,7 +4,7 @@ import _socket import sys from _socket import ( - _FD, + CAPI as CAPI, EAI_AGAIN as EAI_AGAIN, EAI_BADFLAGS as EAI_BADFLAGS, EAI_FAIL as EAI_FAIL, @@ -33,9 +33,28 @@ from _socket import ( IP_TTL as IP_TTL, IPPORT_RESERVED as IPPORT_RESERVED, IPPORT_USERRESERVED as IPPORT_USERRESERVED, + IPPROTO_AH as IPPROTO_AH, + IPPROTO_DSTOPTS as IPPROTO_DSTOPTS, + IPPROTO_EGP as IPPROTO_EGP, + IPPROTO_ESP as IPPROTO_ESP, + IPPROTO_FRAGMENT as IPPROTO_FRAGMENT, + IPPROTO_GGP as IPPROTO_GGP, + IPPROTO_HOPOPTS as IPPROTO_HOPOPTS, IPPROTO_ICMP as IPPROTO_ICMP, + IPPROTO_ICMPV6 as IPPROTO_ICMPV6, + IPPROTO_IDP as IPPROTO_IDP, + IPPROTO_IGMP as IPPROTO_IGMP, IPPROTO_IP as IPPROTO_IP, + IPPROTO_IPV4 as IPPROTO_IPV4, + IPPROTO_IPV6 as IPPROTO_IPV6, + IPPROTO_MAX as IPPROTO_MAX, + IPPROTO_ND as IPPROTO_ND, + IPPROTO_NONE as IPPROTO_NONE, + IPPROTO_PIM as IPPROTO_PIM, + IPPROTO_PUP as IPPROTO_PUP, IPPROTO_RAW as IPPROTO_RAW, + IPPROTO_ROUTING as IPPROTO_ROUTING, + IPPROTO_SCTP as IPPROTO_SCTP, IPPROTO_TCP as IPPROTO_TCP, IPPROTO_UDP as IPPROTO_UDP, IPV6_CHECKSUM as IPV6_CHECKSUM, @@ -82,11 +101,13 @@ from _socket import ( SOMAXCONN as SOMAXCONN, TCP_FASTOPEN as TCP_FASTOPEN, TCP_KEEPCNT as TCP_KEEPCNT, + TCP_KEEPINTVL as TCP_KEEPINTVL, TCP_MAXSEG as TCP_MAXSEG, TCP_NODELAY as TCP_NODELAY, SocketType as SocketType, _Address as _Address, _RetAddress as _RetAddress, + close as close, dup as dup, error as error, gaierror as gaierror, @@ -103,6 +124,9 @@ from _socket import ( herror as herror, htonl as htonl, htons as htons, + if_indextoname as if_indextoname, + if_nameindex as if_nameindex, + if_nametoindex as if_nametoindex, inet_aton as inet_aton, inet_ntoa as inet_ntoa, inet_ntop as inet_ntop, @@ -116,8 +140,20 @@ from _typeshed import ReadableBuffer, Unused, WriteableBuffer from collections.abc import Iterable from enum import IntEnum, IntFlag from io import BufferedReader, BufferedRWPair, BufferedWriter, IOBase, RawIOBase, TextIOWrapper -from typing import Any, Protocol, overload -from typing_extensions import Literal, Self +from typing import Any, Literal, Protocol, SupportsIndex, overload +from typing_extensions import Self + +if sys.platform == "win32": + from _socket import ( + RCVALL_MAX as RCVALL_MAX, + RCVALL_OFF as RCVALL_OFF, + RCVALL_ON as RCVALL_ON, + RCVALL_SOCKETLEVELONLY as RCVALL_SOCKETLEVELONLY, + SIO_KEEPALIVE_VALS as SIO_KEEPALIVE_VALS, + SIO_LOOPBACK_FAST_PATH as SIO_LOOPBACK_FAST_PATH, + SIO_RCVALL as SIO_RCVALL, + SO_EXCLUSIVEADDRUSE as SO_EXCLUSIVEADDRUSE, + ) if sys.platform != "darwin" or sys.version_info >= (3, 9): from _socket import ( @@ -131,54 +167,27 @@ if sys.platform != "darwin" or sys.version_info >= (3, 9): if sys.platform == "darwin": from _socket import PF_SYSTEM as PF_SYSTEM, SYSPROTO_CONTROL as SYSPROTO_CONTROL -else: - from _socket import SO_EXCLUSIVEADDRUSE as SO_EXCLUSIVEADDRUSE - -if sys.version_info >= (3, 10): - from _socket import IP_RECVTOS as IP_RECVTOS -elif sys.platform != "darwin" and sys.platform != "win32": - from _socket import IP_RECVTOS as IP_RECVTOS - -from _socket import TCP_KEEPINTVL as TCP_KEEPINTVL, close as close if sys.platform != "darwin": - from _socket import TCP_KEEPIDLE as TCP_KEEPIDLE - -if sys.platform != "win32" or sys.version_info >= (3, 8): from _socket import ( - IPPROTO_AH as IPPROTO_AH, - IPPROTO_DSTOPTS as IPPROTO_DSTOPTS, - IPPROTO_EGP as IPPROTO_EGP, - IPPROTO_ESP as IPPROTO_ESP, - IPPROTO_FRAGMENT as IPPROTO_FRAGMENT, - IPPROTO_GGP as IPPROTO_GGP, - IPPROTO_HOPOPTS as IPPROTO_HOPOPTS, - IPPROTO_ICMPV6 as IPPROTO_ICMPV6, - IPPROTO_IDP as IPPROTO_IDP, - IPPROTO_IGMP as IPPROTO_IGMP, - IPPROTO_IPV4 as IPPROTO_IPV4, - IPPROTO_IPV6 as IPPROTO_IPV6, - IPPROTO_MAX as IPPROTO_MAX, - IPPROTO_ND as IPPROTO_ND, - IPPROTO_NONE as IPPROTO_NONE, - IPPROTO_PIM as IPPROTO_PIM, - IPPROTO_PUP as IPPROTO_PUP, - IPPROTO_ROUTING as IPPROTO_ROUTING, - IPPROTO_SCTP as IPPROTO_SCTP, + IPPROTO_CBT as IPPROTO_CBT, + IPPROTO_ICLFXBM as IPPROTO_ICLFXBM, + IPPROTO_IGP as IPPROTO_IGP, + IPPROTO_L2TP as IPPROTO_L2TP, + IPPROTO_PGM as IPPROTO_PGM, + IPPROTO_RDP as IPPROTO_RDP, + IPPROTO_ST as IPPROTO_ST, + TCP_KEEPIDLE as TCP_KEEPIDLE, ) - if sys.platform != "darwin": - from _socket import ( - IPPROTO_CBT as IPPROTO_CBT, - IPPROTO_ICLFXBM as IPPROTO_ICLFXBM, - IPPROTO_IGP as IPPROTO_IGP, - IPPROTO_L2TP as IPPROTO_L2TP, - IPPROTO_PGM as IPPROTO_PGM, - IPPROTO_RDP as IPPROTO_RDP, - IPPROTO_ST as IPPROTO_ST, - ) +if sys.version_info >= (3, 10): + from _socket import IP_RECVTOS as IP_RECVTOS +elif sys.platform != "win32" and sys.platform != "darwin": + from _socket import IP_RECVTOS as IP_RECVTOS + if sys.platform != "win32" and sys.platform != "darwin": from _socket import ( + IP_BIND_ADDRESS_NO_PORT as IP_BIND_ADDRESS_NO_PORT, IP_TRANSPARENT as IP_TRANSPARENT, IPPROTO_BIP as IPPROTO_BIP, IPPROTO_MOBILE as IPPROTO_MOBILE, @@ -186,10 +195,14 @@ if sys.platform != "win32" and sys.platform != "darwin": IPX_TYPE as IPX_TYPE, SCM_CREDENTIALS as SCM_CREDENTIALS, SO_BINDTODEVICE as SO_BINDTODEVICE, + SO_DOMAIN as SO_DOMAIN, SO_MARK as SO_MARK, SO_PASSCRED as SO_PASSCRED, + SO_PASSSEC as SO_PASSSEC, SO_PEERCRED as SO_PEERCRED, + SO_PEERSEC as SO_PEERSEC, SO_PRIORITY as SO_PRIORITY, + SO_PROTOCOL as SO_PROTOCOL, SO_SETFIB as SO_SETFIB, SOL_ATALK as SOL_ATALK, SOL_AX25 as SOL_AX25, @@ -197,6 +210,7 @@ if sys.platform != "win32" and sys.platform != "darwin": SOL_IPX as SOL_IPX, SOL_NETROM as SOL_NETROM, SOL_ROSE as SOL_ROSE, + TCP_CONGESTION as TCP_CONGESTION, TCP_CORK as TCP_CORK, TCP_DEFER_ACCEPT as TCP_DEFER_ACCEPT, TCP_INFO as TCP_INFO, @@ -206,6 +220,7 @@ if sys.platform != "win32" and sys.platform != "darwin": TCP_USER_TIMEOUT as TCP_USER_TIMEOUT, TCP_WINDOW_CLAMP as TCP_WINDOW_CLAMP, ) + if sys.platform != "win32": from _socket import ( CMSG_LEN as CMSG_LEN, @@ -235,6 +250,7 @@ if sys.platform != "win32": SCM_CREDS as SCM_CREDS, SCM_RIGHTS as SCM_RIGHTS, SO_REUSEPORT as SO_REUSEPORT, + TCP_NOTSENT_LOWAT as TCP_NOTSENT_LOWAT, sethostname as sethostname, ) @@ -252,9 +268,6 @@ if sys.platform != "win32": IPV6_USE_MIN_MTU as IPV6_USE_MIN_MTU, ) -if sys.platform != "win32" or sys.version_info >= (3, 8): - from _socket import if_indextoname as if_indextoname, if_nameindex as if_nameindex, if_nametoindex as if_nametoindex - if sys.platform != "darwin": if sys.platform != "win32" or sys.version_info >= (3, 9): from _socket import BDADDR_ANY as BDADDR_ANY, BDADDR_LOCAL as BDADDR_LOCAL, BTPROTO_RFCOMM as BTPROTO_RFCOMM @@ -262,6 +275,9 @@ if sys.platform != "darwin": if sys.platform == "darwin" and sys.version_info >= (3, 10): from _socket import TCP_KEEPALIVE as TCP_KEEPALIVE +if sys.platform == "darwin" and sys.version_info >= (3, 11): + from _socket import TCP_CONNECTION_INFO as TCP_CONNECTION_INFO + if sys.platform == "linux": from _socket import ( ALG_OP_DECRYPT as ALG_OP_DECRYPT, @@ -275,15 +291,27 @@ if sys.platform == "linux": ALG_SET_OP as ALG_SET_OP, ALG_SET_PUBKEY as ALG_SET_PUBKEY, CAN_BCM as CAN_BCM, + CAN_BCM_CAN_FD_FRAME as CAN_BCM_CAN_FD_FRAME, + CAN_BCM_RX_ANNOUNCE_RESUME as CAN_BCM_RX_ANNOUNCE_RESUME, CAN_BCM_RX_CHANGED as CAN_BCM_RX_CHANGED, + CAN_BCM_RX_CHECK_DLC as CAN_BCM_RX_CHECK_DLC, CAN_BCM_RX_DELETE as CAN_BCM_RX_DELETE, + CAN_BCM_RX_FILTER_ID as CAN_BCM_RX_FILTER_ID, + CAN_BCM_RX_NO_AUTOTIMER as CAN_BCM_RX_NO_AUTOTIMER, CAN_BCM_RX_READ as CAN_BCM_RX_READ, + CAN_BCM_RX_RTR_FRAME as CAN_BCM_RX_RTR_FRAME, CAN_BCM_RX_SETUP as CAN_BCM_RX_SETUP, CAN_BCM_RX_STATUS as CAN_BCM_RX_STATUS, CAN_BCM_RX_TIMEOUT as CAN_BCM_RX_TIMEOUT, + CAN_BCM_SETTIMER as CAN_BCM_SETTIMER, + CAN_BCM_STARTTIMER as CAN_BCM_STARTTIMER, + CAN_BCM_TX_ANNOUNCE as CAN_BCM_TX_ANNOUNCE, + CAN_BCM_TX_COUNTEVT as CAN_BCM_TX_COUNTEVT, + CAN_BCM_TX_CP_CAN_ID as CAN_BCM_TX_CP_CAN_ID, CAN_BCM_TX_DELETE as CAN_BCM_TX_DELETE, CAN_BCM_TX_EXPIRED as CAN_BCM_TX_EXPIRED, CAN_BCM_TX_READ as CAN_BCM_TX_READ, + CAN_BCM_TX_RESET_MULTI_IDX as CAN_BCM_TX_RESET_MULTI_IDX, CAN_BCM_TX_SEND as CAN_BCM_TX_SEND, CAN_BCM_TX_SETUP as CAN_BCM_TX_SETUP, CAN_BCM_TX_STATUS as CAN_BCM_TX_STATUS, @@ -291,6 +319,7 @@ if sys.platform == "linux": CAN_EFF_MASK as CAN_EFF_MASK, CAN_ERR_FLAG as CAN_ERR_FLAG, CAN_ERR_MASK as CAN_ERR_MASK, + CAN_ISOTP as CAN_ISOTP, CAN_RAW as CAN_RAW, CAN_RAW_ERR_FILTER as CAN_RAW_ERR_FILTER, CAN_RAW_FD_FRAMES as CAN_RAW_FD_FRAMES, @@ -299,6 +328,7 @@ if sys.platform == "linux": CAN_RAW_RECV_OWN_MSGS as CAN_RAW_RECV_OWN_MSGS, CAN_RTR_FLAG as CAN_RTR_FLAG, CAN_SFF_MASK as CAN_SFF_MASK, + IOCTL_VM_SOCKETS_GET_LOCAL_CID as IOCTL_VM_SOCKETS_GET_LOCAL_CID, NETLINK_ARPD as NETLINK_ARPD, NETLINK_CRYPTO as NETLINK_CRYPTO, NETLINK_DNRTMSG as NETLINK_DNRTMSG, @@ -341,6 +371,9 @@ if sys.platform == "linux": RDS_RDMA_SILENT as RDS_RDMA_SILENT, RDS_RDMA_USE_ONCE as RDS_RDMA_USE_ONCE, RDS_RECVERR as RDS_RECVERR, + SO_VM_SOCKETS_BUFFER_MAX_SIZE as SO_VM_SOCKETS_BUFFER_MAX_SIZE, + SO_VM_SOCKETS_BUFFER_MIN_SIZE as SO_VM_SOCKETS_BUFFER_MIN_SIZE, + SO_VM_SOCKETS_BUFFER_SIZE as SO_VM_SOCKETS_BUFFER_SIZE, SOL_ALG as SOL_ALG, SOL_CAN_BASE as SOL_CAN_BASE, SOL_CAN_RAW as SOL_CAN_RAW, @@ -369,36 +402,12 @@ if sys.platform == "linux": TIPC_WAIT_FOREVER as TIPC_WAIT_FOREVER, TIPC_WITHDRAWN as TIPC_WITHDRAWN, TIPC_ZONE_SCOPE as TIPC_ZONE_SCOPE, - ) -if sys.platform == "linux": - from _socket import ( - CAN_ISOTP as CAN_ISOTP, - IOCTL_VM_SOCKETS_GET_LOCAL_CID as IOCTL_VM_SOCKETS_GET_LOCAL_CID, - SO_VM_SOCKETS_BUFFER_MAX_SIZE as SO_VM_SOCKETS_BUFFER_MAX_SIZE, - SO_VM_SOCKETS_BUFFER_MIN_SIZE as SO_VM_SOCKETS_BUFFER_MIN_SIZE, - SO_VM_SOCKETS_BUFFER_SIZE as SO_VM_SOCKETS_BUFFER_SIZE, VM_SOCKETS_INVALID_VERSION as VM_SOCKETS_INVALID_VERSION, VMADDR_CID_ANY as VMADDR_CID_ANY, VMADDR_CID_HOST as VMADDR_CID_HOST, VMADDR_PORT_ANY as VMADDR_PORT_ANY, ) -if sys.platform != "win32": - from _socket import TCP_NOTSENT_LOWAT as TCP_NOTSENT_LOWAT -if sys.platform == "linux" and sys.version_info >= (3, 8): - from _socket import ( - CAN_BCM_CAN_FD_FRAME as CAN_BCM_CAN_FD_FRAME, - CAN_BCM_RX_ANNOUNCE_RESUME as CAN_BCM_RX_ANNOUNCE_RESUME, - CAN_BCM_RX_CHECK_DLC as CAN_BCM_RX_CHECK_DLC, - CAN_BCM_RX_FILTER_ID as CAN_BCM_RX_FILTER_ID, - CAN_BCM_RX_NO_AUTOTIMER as CAN_BCM_RX_NO_AUTOTIMER, - CAN_BCM_RX_RTR_FRAME as CAN_BCM_RX_RTR_FRAME, - CAN_BCM_SETTIMER as CAN_BCM_SETTIMER, - CAN_BCM_STARTTIMER as CAN_BCM_STARTTIMER, - CAN_BCM_TX_ANNOUNCE as CAN_BCM_TX_ANNOUNCE, - CAN_BCM_TX_COUNTEVT as CAN_BCM_TX_COUNTEVT, - CAN_BCM_TX_CP_CAN_ID as CAN_BCM_TX_CP_CAN_ID, - CAN_BCM_TX_RESET_MULTI_IDX as CAN_BCM_TX_RESET_MULTI_IDX, - ) + if sys.platform == "linux" and sys.version_info >= (3, 9): from _socket import ( CAN_J1939 as CAN_J1939, @@ -426,21 +435,14 @@ if sys.platform == "linux" and sys.version_info >= (3, 9): SO_J1939_FILTER as SO_J1939_FILTER, SO_J1939_PROMISC as SO_J1939_PROMISC, SO_J1939_SEND_PRIO as SO_J1939_SEND_PRIO, + UDPLITE_RECV_CSCOV as UDPLITE_RECV_CSCOV, + UDPLITE_SEND_CSCOV as UDPLITE_SEND_CSCOV, ) if sys.platform == "linux" and sys.version_info >= (3, 10): from _socket import IPPROTO_MPTCP as IPPROTO_MPTCP if sys.platform == "linux" and sys.version_info >= (3, 11): from _socket import SO_INCOMING_CPU as SO_INCOMING_CPU -if sys.platform == "win32": - from _socket import ( - RCVALL_MAX as RCVALL_MAX, - RCVALL_OFF as RCVALL_OFF, - RCVALL_ON as RCVALL_ON, - RCVALL_SOCKETLEVELONLY as RCVALL_SOCKETLEVELONLY, - SIO_KEEPALIVE_VALS as SIO_KEEPALIVE_VALS, - SIO_LOOPBACK_FAST_PATH as SIO_LOOPBACK_FAST_PATH, - SIO_RCVALL as SIO_RCVALL, - ) + if sys.version_info >= (3, 12): from _socket import ( IP_ADD_SOURCE_MEMBERSHIP as IP_ADD_SOURCE_MEMBERSHIP, @@ -471,8 +473,6 @@ if sys.version_info >= (3, 12): ETHERTYPE_IPV6 as ETHERTYPE_IPV6, ETHERTYPE_VLAN as ETHERTYPE_VLAN, ) -if sys.version_info >= (3, 11) and sys.platform == "darwin": - from _socket import TCP_CONNECTION_INFO as TCP_CONNECTION_INFO # Re-exported from errno EBADF: int @@ -493,7 +493,7 @@ class AddressFamily(IntEnum): AF_ROUTE: int AF_SYSTEM: int AF_UNIX: int - if sys.platform != "darwin" and sys.platform != "win32": + if sys.platform != "win32" and sys.platform != "darwin": AF_AAL5: int AF_ASH: int AF_ATMPVC: int @@ -518,8 +518,7 @@ class AddressFamily(IntEnum): AF_ALG: int AF_NETLINK: int AF_VSOCK: int - if sys.version_info >= (3, 8): - AF_QIPCRTR: int + AF_QIPCRTR: int if sys.platform != "win32" or sys.version_info >= (3, 9): AF_LINK: int if sys.platform != "darwin": @@ -569,8 +568,7 @@ if sys.platform == "linux": AF_ALG = AddressFamily.AF_ALG AF_NETLINK = AddressFamily.AF_NETLINK AF_VSOCK = AddressFamily.AF_VSOCK - if sys.version_info >= (3, 8): - AF_QIPCRTR = AddressFamily.AF_QIPCRTR + AF_QIPCRTR = AddressFamily.AF_QIPCRTR if sys.platform != "win32" or sys.version_info >= (3, 9): AF_LINK = AddressFamily.AF_LINK @@ -771,7 +769,7 @@ class socket(_socket.socket): def get_inheritable(self) -> bool: ... def set_inheritable(self, inheritable: bool) -> None: ... -def fromfd(fd: _FD, family: AddressFamily | int, type: SocketKind | int, proto: int = 0) -> socket: ... +def fromfd(fd: SupportsIndex, family: AddressFamily | int, type: SocketKind | int, proto: int = 0) -> socket: ... if sys.platform != "win32": if sys.version_info >= (3, 9): @@ -816,16 +814,10 @@ else: address: tuple[str | None, int], timeout: float | None = ..., source_address: _Address | None = None # noqa: F811 ) -> socket: ... -if sys.version_info >= (3, 8): - def has_dualstack_ipv6() -> bool: ... - def create_server( - address: _Address, - *, - family: int = ..., - backlog: int | None = None, - reuse_port: bool = False, - dualstack_ipv6: bool = False, - ) -> socket: ... +def has_dualstack_ipv6() -> bool: ... +def create_server( + address: _Address, *, family: int = ..., backlog: int | None = None, reuse_port: bool = False, dualstack_ipv6: bool = False +) -> socket: ... # the 5th tuple item is an address def getaddrinfo( diff --git a/mypy/typeshed/stdlib/spwd.pyi b/mypy/typeshed/stdlib/spwd.pyi index 27b1061e1b0e..93dfad3b38cc 100644 --- a/mypy/typeshed/stdlib/spwd.pyi +++ b/mypy/typeshed/stdlib/spwd.pyi @@ -1,7 +1,6 @@ import sys from _typeshed import structseq -from typing import Any -from typing_extensions import Final, final +from typing import Any, Final, final if sys.platform != "win32": @final diff --git a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi index 236e093c9909..659545c50b41 100644 --- a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi +++ b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi @@ -1,11 +1,11 @@ import sqlite3 import sys -from _typeshed import Incomplete, ReadableBuffer, StrOrBytesPath, SupportsLenAndGetItem, Unused +from _typeshed import ReadableBuffer, StrOrBytesPath, SupportsLenAndGetItem, Unused from collections.abc import Callable, Generator, Iterable, Iterator, Mapping from datetime import date, datetime, time from types import TracebackType -from typing import Any, Protocol, TypeVar, overload -from typing_extensions import Literal, Self, SupportsIndex, TypeAlias, final +from typing import Any, Literal, Protocol, SupportsIndex, TypeVar, final, overload +from typing_extensions import Self, TypeAlias _T = TypeVar("_T") _CursorT = TypeVar("_CursorT", bound=Cursor) @@ -245,12 +245,6 @@ else: def register_adapter(__type: type[_T], __caster: _Adapter[_T]) -> None: ... def register_converter(__name: str, __converter: _Converter) -> None: ... -if sys.version_info < (3, 8): - class Cache: - def __init__(self, *args: Incomplete, **kwargs: Unused) -> None: ... - def display(self, *args: Incomplete, **kwargs: Incomplete) -> None: ... - def get(self, *args: Incomplete, **kwargs: Incomplete) -> None: ... - class _AggregateProtocol(Protocol): def step(self, __value: int) -> object: ... def finalize(self) -> int: ... @@ -341,13 +335,9 @@ class Connection: ) -> None: ... def create_collation(self, __name: str, __callback: Callable[[str, str], int | SupportsIndex] | None) -> None: ... - if sys.version_info >= (3, 8): - def create_function( - self, name: str, narg: int, func: Callable[..., _SqliteData] | None, *, deterministic: bool = False - ) -> None: ... - else: - def create_function(self, name: str, num_params: int, func: Callable[..., _SqliteData] | None) -> None: ... - + def create_function( + self, name: str, narg: int, func: Callable[..., _SqliteData] | None, *, deterministic: bool = False + ) -> None: ... @overload def cursor(self, factory: None = None) -> Cursor: ... @overload @@ -458,15 +448,8 @@ class Row: def __lt__(self, __value: object) -> bool: ... def __ne__(self, __value: object) -> bool: ... -if sys.version_info >= (3, 8): - @final - class _Statement: ... - -else: - @final - class Statement: - def __init__(self, *args: Incomplete, **kwargs: Incomplete) -> None: ... - _Statement: TypeAlias = Statement +@final +class _Statement: ... class Warning(Exception): ... diff --git a/mypy/typeshed/stdlib/sre_parse.pyi b/mypy/typeshed/stdlib/sre_parse.pyi index 2c10bf7e7c3b..c242bd2a065f 100644 --- a/mypy/typeshed/stdlib/sre_parse.pyi +++ b/mypy/typeshed/stdlib/sre_parse.pyi @@ -25,7 +25,14 @@ if sys.version_info >= (3, 11): if sys.version_info < (3, 11): class Verbose(Exception): ... -class _State: +_OpSubpatternType: TypeAlias = tuple[int | None, int, int, SubPattern] +_OpGroupRefExistsType: TypeAlias = tuple[int, SubPattern, SubPattern] +_OpInType: TypeAlias = list[tuple[_NIC, int]] +_OpBranchType: TypeAlias = tuple[None, list[SubPattern]] +_AvType: TypeAlias = _OpInType | _OpBranchType | Iterable[SubPattern] | _OpGroupRefExistsType | _OpSubpatternType +_CodeType: TypeAlias = tuple[_NIC, _AvType] + +class State: flags: int groupdict: dict[str, int] groupwidths: list[int | None] @@ -37,29 +44,12 @@ class _State: def checkgroup(self, gid: int) -> bool: ... def checklookbehindgroup(self, gid: int, source: Tokenizer) -> None: ... -if sys.version_info >= (3, 8): - State: TypeAlias = _State -else: - Pattern: TypeAlias = _State - -_OpSubpatternType: TypeAlias = tuple[int | None, int, int, SubPattern] -_OpGroupRefExistsType: TypeAlias = tuple[int, SubPattern, SubPattern] -_OpInType: TypeAlias = list[tuple[_NIC, int]] -_OpBranchType: TypeAlias = tuple[None, list[SubPattern]] -_AvType: TypeAlias = _OpInType | _OpBranchType | Iterable[SubPattern] | _OpGroupRefExistsType | _OpSubpatternType -_CodeType: TypeAlias = tuple[_NIC, _AvType] - class SubPattern: data: list[_CodeType] width: int | None + state: State - if sys.version_info >= (3, 8): - state: State - def __init__(self, state: State, data: list[_CodeType] | None = None) -> None: ... - else: - pattern: Pattern - def __init__(self, pattern: Pattern, data: list[_CodeType] | None = None) -> None: ... - + def __init__(self, state: State, data: list[_CodeType] | None = None) -> None: ... def dump(self, level: int = 0) -> None: ... def __len__(self) -> int: ... def __delitem__(self, index: int | slice) -> None: ... @@ -79,11 +69,7 @@ class Tokenizer: def match(self, char: str) -> bool: ... def get(self) -> str | None: ... def getwhile(self, n: int, charset: Iterable[str]) -> str: ... - if sys.version_info >= (3, 8): - def getuntil(self, terminator: str, name: str) -> str: ... - else: - def getuntil(self, terminator: str) -> str: ... - + def getuntil(self, terminator: str, name: str) -> str: ... @property def pos(self) -> int: ... def tell(self) -> int: ... @@ -106,23 +92,13 @@ if sys.version_info >= (3, 12): @overload def parse_template(source: bytes, pattern: _Pattern[Any]) -> _TemplateByteType: ... -elif sys.version_info >= (3, 8): +else: @overload def parse_template(source: str, state: _Pattern[Any]) -> _TemplateType: ... @overload def parse_template(source: bytes, state: _Pattern[Any]) -> _TemplateByteType: ... -else: - @overload - def parse_template(source: str, pattern: _Pattern[Any]) -> _TemplateType: ... - @overload - def parse_template(source: bytes, pattern: _Pattern[Any]) -> _TemplateByteType: ... - -if sys.version_info >= (3, 8): - def parse(str: str, flags: int = 0, state: State | None = None) -> SubPattern: ... - -else: - def parse(str: str, flags: int = 0, pattern: Pattern | None = None) -> SubPattern: ... +def parse(str: str, flags: int = 0, state: State | None = None) -> SubPattern: ... if sys.version_info < (3, 12): def expand_template(template: _TemplateType, match: Match[Any]) -> str: ... diff --git a/mypy/typeshed/stdlib/ssl.pyi b/mypy/typeshed/stdlib/ssl.pyi index d7f256d031ac..583ac82750ac 100644 --- a/mypy/typeshed/stdlib/ssl.pyi +++ b/mypy/typeshed/stdlib/ssl.pyi @@ -3,8 +3,8 @@ import socket import sys from _typeshed import ReadableBuffer, StrOrBytesPath, WriteableBuffer from collections.abc import Callable, Iterable -from typing import Any, NamedTuple, overload -from typing_extensions import Literal, Never, Self, TypeAlias, TypedDict, final +from typing import Any, Literal, NamedTuple, TypedDict, final, overload +from typing_extensions import Never, Self, TypeAlias _PCTRTT: TypeAlias = tuple[tuple[str, str], ...] _PCTRTTT: TypeAlias = tuple[_PCTRTT, ...] @@ -199,14 +199,11 @@ class Options(enum.IntFlag): OP_NO_COMPRESSION: int OP_NO_TICKET: int OP_NO_RENEGOTIATION: int - if sys.version_info >= (3, 8): - OP_ENABLE_MIDDLEBOX_COMPAT: int + OP_ENABLE_MIDDLEBOX_COMPAT: int if sys.version_info >= (3, 12): OP_LEGACY_SERVER_CONNECT: int OP_ENABLE_KTLS: int - if sys.version_info >= (3, 11): - OP_IGNORE_UNEXPECTED_EOF: int - elif sys.version_info >= (3, 8) and sys.platform == "linux": + if sys.version_info >= (3, 11) or sys.platform == "linux": OP_IGNORE_UNEXPECTED_EOF: int OP_ALL: Options @@ -222,14 +219,11 @@ OP_SINGLE_ECDH_USE: Options OP_NO_COMPRESSION: Options OP_NO_TICKET: Options OP_NO_RENEGOTIATION: Options -if sys.version_info >= (3, 8): - OP_ENABLE_MIDDLEBOX_COMPAT: Options +OP_ENABLE_MIDDLEBOX_COMPAT: Options if sys.version_info >= (3, 12): OP_LEGACY_SERVER_CONNECT: Options OP_ENABLE_KTLS: Options -if sys.version_info >= (3, 11): - OP_IGNORE_UNEXPECTED_EOF: Options -elif sys.version_info >= (3, 8) and sys.platform == "linux": +if sys.version_info >= (3, 11) or sys.platform == "linux": OP_IGNORE_UNEXPECTED_EOF: Options HAS_NEVER_CHECK_COMMON_NAME: bool @@ -365,8 +359,7 @@ class SSLSocket(socket.socket): def unwrap(self) -> socket.socket: ... def version(self) -> str | None: ... def pending(self) -> int: ... - if sys.version_info >= (3, 8): - def verify_client_post_handshake(self) -> None: ... + def verify_client_post_handshake(self) -> None: ... # These methods always raise `NotImplementedError`: def recvmsg(self, *args: Never, **kwargs: Never) -> Never: ... # type: ignore[override] def recvmsg_into(self, *args: Never, **kwargs: Never) -> Never: ... # type: ignore[override] @@ -397,9 +390,8 @@ class SSLContext: # so making these ClassVars wouldn't be appropriate sslobject_class: type[SSLObject] sslsocket_class: type[SSLSocket] - if sys.version_info >= (3, 8): - keylog_filename: str - post_handshake_auth: bool + keylog_filename: str + post_handshake_auth: bool if sys.version_info >= (3, 10): security_level: int if sys.version_info >= (3, 10): @@ -481,8 +473,7 @@ class SSLObject: def unwrap(self) -> None: ... def version(self) -> str | None: ... def get_channel_binding(self, cb_type: str = "tls-unique") -> bytes | None: ... - if sys.version_info >= (3, 8): - def verify_client_post_handshake(self) -> None: ... + def verify_client_post_handshake(self) -> None: ... @final class MemoryBIO: diff --git a/mypy/typeshed/stdlib/statistics.pyi b/mypy/typeshed/stdlib/statistics.pyi index 07174f4531b9..f3f013fc93e7 100644 --- a/mypy/typeshed/stdlib/statistics.pyi +++ b/mypy/typeshed/stdlib/statistics.pyi @@ -3,11 +3,15 @@ from _typeshed import SupportsRichComparisonT from collections.abc import Hashable, Iterable, Sequence from decimal import Decimal from fractions import Fraction -from typing import Any, NamedTuple, SupportsFloat, TypeVar -from typing_extensions import Literal, Self, TypeAlias +from typing import Any, Literal, NamedTuple, SupportsFloat, TypeVar +from typing_extensions import Self, TypeAlias __all__ = [ "StatisticsError", + "fmean", + "geometric_mean", + "mean", + "harmonic_mean", "pstdev", "pvariance", "stdev", @@ -16,14 +20,12 @@ __all__ = [ "median_low", "median_high", "median_grouped", - "mean", "mode", - "harmonic_mean", + "multimode", + "NormalDist", + "quantiles", ] -if sys.version_info >= (3, 8): - __all__ += ["geometric_mean", "multimode", "NormalDist", "fmean", "quantiles"] - if sys.version_info >= (3, 10): __all__ += ["covariance", "correlation", "linear_regression"] @@ -39,12 +41,10 @@ class StatisticsError(ValueError): ... if sys.version_info >= (3, 11): def fmean(data: Iterable[SupportsFloat], weights: Iterable[SupportsFloat] | None = None) -> float: ... -elif sys.version_info >= (3, 8): +else: def fmean(data: Iterable[SupportsFloat]) -> float: ... -if sys.version_info >= (3, 8): - def geometric_mean(data: Iterable[SupportsFloat]) -> float: ... - +def geometric_mean(data: Iterable[SupportsFloat]) -> float: ... def mean(data: Iterable[_NumberT]) -> _NumberT: ... if sys.version_info >= (3, 10): @@ -64,56 +64,49 @@ else: def median_grouped(data: Iterable[_NumberT], interval: _NumberT | float = 1) -> _NumberT | float: ... def mode(data: Iterable[_HashableT]) -> _HashableT: ... - -if sys.version_info >= (3, 8): - def multimode(data: Iterable[_HashableT]) -> list[_HashableT]: ... - +def multimode(data: Iterable[_HashableT]) -> list[_HashableT]: ... def pstdev(data: Iterable[_NumberT], mu: _NumberT | None = None) -> _NumberT: ... def pvariance(data: Iterable[_NumberT], mu: _NumberT | None = None) -> _NumberT: ... - -if sys.version_info >= (3, 8): - def quantiles( - data: Iterable[_NumberT], *, n: int = 4, method: Literal["inclusive", "exclusive"] = "exclusive" - ) -> list[_NumberT]: ... - +def quantiles( + data: Iterable[_NumberT], *, n: int = 4, method: Literal["inclusive", "exclusive"] = "exclusive" +) -> list[_NumberT]: ... def stdev(data: Iterable[_NumberT], xbar: _NumberT | None = None) -> _NumberT: ... def variance(data: Iterable[_NumberT], xbar: _NumberT | None = None) -> _NumberT: ... -if sys.version_info >= (3, 8): - class NormalDist: - def __init__(self, mu: float = 0.0, sigma: float = 1.0) -> None: ... - @property - def mean(self) -> float: ... - @property - def median(self) -> float: ... - @property - def mode(self) -> float: ... - @property - def stdev(self) -> float: ... - @property - def variance(self) -> float: ... - @classmethod - def from_samples(cls, data: Iterable[SupportsFloat]) -> Self: ... - def samples(self, n: int, *, seed: Any | None = None) -> list[float]: ... - def pdf(self, x: float) -> float: ... - def cdf(self, x: float) -> float: ... - def inv_cdf(self, p: float) -> float: ... - def overlap(self, other: NormalDist) -> float: ... - def quantiles(self, n: int = 4) -> list[float]: ... - if sys.version_info >= (3, 9): - def zscore(self, x: float) -> float: ... - - def __eq__(self, x2: object) -> bool: ... - def __add__(self, x2: float | NormalDist) -> NormalDist: ... - def __sub__(self, x2: float | NormalDist) -> NormalDist: ... - def __mul__(self, x2: float) -> NormalDist: ... - def __truediv__(self, x2: float) -> NormalDist: ... - def __pos__(self) -> NormalDist: ... - def __neg__(self) -> NormalDist: ... - __radd__ = __add__ - def __rsub__(self, x2: float | NormalDist) -> NormalDist: ... - __rmul__ = __mul__ - def __hash__(self) -> int: ... +class NormalDist: + def __init__(self, mu: float = 0.0, sigma: float = 1.0) -> None: ... + @property + def mean(self) -> float: ... + @property + def median(self) -> float: ... + @property + def mode(self) -> float: ... + @property + def stdev(self) -> float: ... + @property + def variance(self) -> float: ... + @classmethod + def from_samples(cls, data: Iterable[SupportsFloat]) -> Self: ... + def samples(self, n: int, *, seed: Any | None = None) -> list[float]: ... + def pdf(self, x: float) -> float: ... + def cdf(self, x: float) -> float: ... + def inv_cdf(self, p: float) -> float: ... + def overlap(self, other: NormalDist) -> float: ... + def quantiles(self, n: int = 4) -> list[float]: ... + if sys.version_info >= (3, 9): + def zscore(self, x: float) -> float: ... + + def __eq__(self, x2: object) -> bool: ... + def __add__(self, x2: float | NormalDist) -> NormalDist: ... + def __sub__(self, x2: float | NormalDist) -> NormalDist: ... + def __mul__(self, x2: float) -> NormalDist: ... + def __truediv__(self, x2: float) -> NormalDist: ... + def __pos__(self) -> NormalDist: ... + def __neg__(self) -> NormalDist: ... + __radd__ = __add__ + def __rsub__(self, x2: float | NormalDist) -> NormalDist: ... + __rmul__ = __mul__ + def __hash__(self) -> int: ... if sys.version_info >= (3, 12): def correlation( diff --git a/mypy/typeshed/stdlib/subprocess.pyi b/mypy/typeshed/stdlib/subprocess.pyi index b89623f05c99..df1db5c82eea 100644 --- a/mypy/typeshed/stdlib/subprocess.pyi +++ b/mypy/typeshed/stdlib/subprocess.pyi @@ -2,8 +2,8 @@ import sys from _typeshed import ReadableBuffer, StrOrBytesPath from collections.abc import Callable, Collection, Iterable, Mapping, Sequence from types import TracebackType -from typing import IO, Any, AnyStr, Generic, TypeVar, overload -from typing_extensions import Literal, Self, TypeAlias +from typing import IO, Any, AnyStr, Generic, Literal, TypeVar, overload +from typing_extensions import Self, TypeAlias if sys.version_info >= (3, 9): from types import GenericAlias @@ -64,12 +64,7 @@ if sys.platform == "win32": # reveal_type(e.cmd) # Any, but morally is _CMD _FILE: TypeAlias = None | int | IO[Any] _InputString: TypeAlias = ReadableBuffer | str -if sys.version_info >= (3, 8): - _CMD: TypeAlias = StrOrBytesPath | Sequence[StrOrBytesPath] -else: - # Python 3.7 doesn't support _CMD being a single PathLike. - # See: https://bugs.python.org/issue31961 - _CMD: TypeAlias = str | bytes | Sequence[StrOrBytesPath] +_CMD: TypeAlias = StrOrBytesPath | Sequence[StrOrBytesPath] if sys.platform == "win32": _ENV: TypeAlias = Mapping[str, str] else: @@ -80,8 +75,7 @@ _T = TypeVar("_T") # These two are private but documented if sys.version_info >= (3, 11): _USE_VFORK: bool -if sys.version_info >= (3, 8): - _USE_POSIX_SPAWN: bool +_USE_POSIX_SPAWN: bool class CompletedProcess(Generic[_T]): # morally: _CMD @@ -2577,11 +2571,7 @@ else: def getstatusoutput(cmd: str | bytes) -> tuple[int, str]: ... def getoutput(cmd: str | bytes) -> str: ... -if sys.version_info >= (3, 8): - def list2cmdline(seq: Iterable[StrOrBytesPath]) -> str: ... # undocumented - -else: - def list2cmdline(seq: Iterable[str]) -> str: ... # undocumented +def list2cmdline(seq: Iterable[StrOrBytesPath]) -> str: ... # undocumented if sys.platform == "win32": class STARTUPINFO: diff --git a/mypy/typeshed/stdlib/sunau.pyi b/mypy/typeshed/stdlib/sunau.pyi index b508a1ea8e20..9b051e82b64b 100644 --- a/mypy/typeshed/stdlib/sunau.pyi +++ b/mypy/typeshed/stdlib/sunau.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import Unused -from typing import IO, Any, NamedTuple, NoReturn, overload -from typing_extensions import Literal, Self, TypeAlias +from typing import IO, Any, Literal, NamedTuple, NoReturn, overload +from typing_extensions import Self, TypeAlias _File: TypeAlias = str | IO[bytes] diff --git a/mypy/typeshed/stdlib/symbol.pyi b/mypy/typeshed/stdlib/symbol.pyi index bb6660374d16..48ae3567a1a5 100644 --- a/mypy/typeshed/stdlib/symbol.pyi +++ b/mypy/typeshed/stdlib/symbol.pyi @@ -1,5 +1,3 @@ -import sys - single_input: int file_input: int eval_input: int @@ -87,11 +85,9 @@ encoding_decl: int yield_expr: int yield_arg: int sync_comp_for: int -if sys.version_info >= (3, 8): - func_body_suite: int - func_type: int - func_type_input: int - namedexpr_test: int - typelist: int - +func_body_suite: int +func_type: int +func_type_input: int +namedexpr_test: int +typelist: int sym_name: dict[int, str] diff --git a/mypy/typeshed/stdlib/symtable.pyi b/mypy/typeshed/stdlib/symtable.pyi index 304ae8bf8126..0f080954ba2c 100644 --- a/mypy/typeshed/stdlib/symtable.pyi +++ b/mypy/typeshed/stdlib/symtable.pyi @@ -29,21 +29,16 @@ class Function(SymbolTable): def get_locals(self) -> tuple[str, ...]: ... def get_globals(self) -> tuple[str, ...]: ... def get_frees(self) -> tuple[str, ...]: ... - if sys.version_info >= (3, 8): - def get_nonlocals(self) -> tuple[str, ...]: ... + def get_nonlocals(self) -> tuple[str, ...]: ... class Class(SymbolTable): def get_methods(self) -> tuple[str, ...]: ... class Symbol: - if sys.version_info >= (3, 8): - def __init__( - self, name: str, flags: int, namespaces: Sequence[SymbolTable] | None = None, *, module_scope: bool = False - ) -> None: ... - def is_nonlocal(self) -> bool: ... - else: - def __init__(self, name: str, flags: int, namespaces: Sequence[SymbolTable] | None = None) -> None: ... - + def __init__( + self, name: str, flags: int, namespaces: Sequence[SymbolTable] | None = None, *, module_scope: bool = False + ) -> None: ... + def is_nonlocal(self) -> bool: ... def get_name(self) -> str: ... def is_referenced(self) -> bool: ... def is_parameter(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/sys/__init__.pyi b/mypy/typeshed/stdlib/sys/__init__.pyi index 1d4111af3a49..2f847498214b 100644 --- a/mypy/typeshed/stdlib/sys/__init__.pyi +++ b/mypy/typeshed/stdlib/sys/__init__.pyi @@ -1,13 +1,13 @@ import sys from _typeshed import OptExcInfo, ProfileFunction, TraceFunction, structseq from builtins import object as _object -from collections.abc import AsyncGenerator, Callable, Coroutine, Sequence +from collections.abc import AsyncGenerator, Callable, Sequence from importlib.abc import PathEntryFinder from importlib.machinery import ModuleSpec from io import TextIOWrapper from types import FrameType, ModuleType, TracebackType -from typing import Any, NoReturn, Protocol, TextIO, TypeVar -from typing_extensions import Final, Literal, TypeAlias, final +from typing import Any, Final, Literal, NoReturn, Protocol, TextIO, TypeVar, final +from typing_extensions import TypeAlias _T = TypeVar("_T") @@ -55,8 +55,7 @@ platform: str if sys.version_info >= (3, 9): platlibdir: str prefix: str -if sys.version_info >= (3, 8): - pycache_prefix: str | None +pycache_prefix: str | None ps1: object ps2: object @@ -322,18 +321,19 @@ if sys.version_info < (3, 9): # An 11-tuple or None def callstats() -> tuple[int, int, int, int, int, int, int, int, int, int, int] | None: ... -if sys.version_info >= (3, 8): - # Doesn't exist at runtime, but exported in the stubs so pytest etc. can annotate their code more easily. - class UnraisableHookArgs(Protocol): - exc_type: type[BaseException] - exc_value: BaseException | None - exc_traceback: TracebackType | None - err_msg: str | None - object: _object - unraisablehook: Callable[[UnraisableHookArgs], Any] - def __unraisablehook__(__unraisable: UnraisableHookArgs) -> Any: ... - def addaudithook(hook: Callable[[str, tuple[Any, ...]], Any]) -> None: ... - def audit(__event: str, *args: Any) -> None: ... +# Doesn't exist at runtime, but exported in the stubs so pytest etc. can annotate their code more easily. +class UnraisableHookArgs(Protocol): + exc_type: type[BaseException] + exc_value: BaseException | None + exc_traceback: TracebackType | None + err_msg: str | None + object: _object + +unraisablehook: Callable[[UnraisableHookArgs], Any] + +def __unraisablehook__(__unraisable: UnraisableHookArgs) -> Any: ... +def addaudithook(hook: Callable[[str, tuple[Any, ...]], Any]) -> None: ... +def audit(__event: str, *args: Any) -> None: ... _AsyncgenHook: TypeAlias = Callable[[AsyncGenerator[Any, Any]], None] | None @@ -353,12 +353,7 @@ if sys.platform == "win32": def get_coroutine_origin_tracking_depth() -> int: ... def set_coroutine_origin_tracking_depth(depth: int) -> None: ... -if sys.version_info < (3, 8): - _CoroWrapper: TypeAlias = Callable[[Coroutine[Any, Any, Any]], Any] - def set_coroutine_wrapper(__wrapper: _CoroWrapper) -> None: ... - def get_coroutine_wrapper() -> _CoroWrapper: ... - -# The following two functions were added in 3.11.0, 3.10.7, 3.9.14, 3.8.14, & 3.7.14, +# The following two functions were added in 3.11.0, 3.10.7, 3.9.14, and 3.8.14, # as part of the response to CVE-2020-10735 def set_int_max_str_digits(maxdigits: int) -> None: ... def get_int_max_str_digits() -> int: ... diff --git a/mypy/typeshed/stdlib/sysconfig.pyi b/mypy/typeshed/stdlib/sysconfig.pyi index 7e29cf1326d6..2edb71d78cdd 100644 --- a/mypy/typeshed/stdlib/sysconfig.pyi +++ b/mypy/typeshed/stdlib/sysconfig.pyi @@ -1,6 +1,5 @@ import sys -from typing import IO, Any, overload -from typing_extensions import Literal +from typing import IO, Any, Literal, overload __all__ = [ "get_config_h_filename", diff --git a/mypy/typeshed/stdlib/syslog.pyi b/mypy/typeshed/stdlib/syslog.pyi index 0b769301a482..164334f60a6f 100644 --- a/mypy/typeshed/stdlib/syslog.pyi +++ b/mypy/typeshed/stdlib/syslog.pyi @@ -1,6 +1,5 @@ import sys -from typing import overload -from typing_extensions import Literal +from typing import Literal, overload if sys.platform != "win32": LOG_ALERT: Literal[1] diff --git a/mypy/typeshed/stdlib/tarfile.pyi b/mypy/typeshed/stdlib/tarfile.pyi index d9d9641ac698..0bfd91ce2161 100644 --- a/mypy/typeshed/stdlib/tarfile.pyi +++ b/mypy/typeshed/stdlib/tarfile.pyi @@ -6,8 +6,8 @@ from builtins import list as _list # aliases to avoid name clashes with fields from collections.abc import Callable, Iterable, Iterator, Mapping from gzip import _ReadableFileobj as _GzipReadableFileobj, _WritableFileobj as _GzipWritableFileobj from types import TracebackType -from typing import IO, ClassVar, Protocol, overload -from typing_extensions import Literal, Self, TypeAlias +from typing import IO, ClassVar, Literal, Protocol, overload +from typing_extensions import Self, TypeAlias __all__ = [ "TarFile", @@ -119,6 +119,7 @@ def open( debug: int | None = ..., errorlevel: int | None = ..., compresslevel: int | None = ..., + preset: Literal[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] | None = ..., ) -> TarFile: ... class ExFileObject(io.BufferedReader): @@ -291,32 +292,23 @@ class TarFile: def getnames(self) -> _list[str]: ... def list(self, verbose: bool = True, *, members: _list[TarInfo] | None = None) -> None: ... def next(self) -> TarInfo | None: ... - if sys.version_info >= (3, 8): - def extractall( - self, - path: StrOrBytesPath = ".", - members: Iterable[TarInfo] | None = None, - *, - numeric_owner: bool = False, - filter: _TarfileFilter | None = ..., - ) -> None: ... - def extract( - self, - member: str | TarInfo, - path: StrOrBytesPath = "", - set_attrs: bool = True, - *, - numeric_owner: bool = False, - filter: _TarfileFilter | None = ..., - ) -> None: ... - else: - def extractall( - self, path: StrOrBytesPath = ".", members: Iterable[TarInfo] | None = None, *, numeric_owner: bool = False - ) -> None: ... - def extract( - self, member: str | TarInfo, path: StrOrBytesPath = "", set_attrs: bool = True, *, numeric_owner: bool = False - ) -> None: ... - + def extractall( + self, + path: StrOrBytesPath = ".", + members: Iterable[TarInfo] | None = None, + *, + numeric_owner: bool = False, + filter: _TarfileFilter | None = ..., + ) -> None: ... + def extract( + self, + member: str | TarInfo, + path: StrOrBytesPath = "", + set_attrs: bool = True, + *, + numeric_owner: bool = False, + filter: _TarfileFilter | None = ..., + ) -> None: ... def _extract_member( self, tarinfo: TarInfo, targetpath: str, set_attrs: bool = True, numeric_owner: bool = False ) -> None: ... # undocumented @@ -350,9 +342,6 @@ if sys.version_info >= (3, 9): else: def is_tarfile(name: StrOrBytesPath) -> bool: ... -if sys.version_info < (3, 8): - def filemode(mode: int) -> str: ... # undocumented - class TarError(Exception): ... class ReadError(TarError): ... class CompressionError(TarError): ... @@ -360,30 +349,29 @@ class StreamError(TarError): ... class ExtractError(TarError): ... class HeaderError(TarError): ... -if sys.version_info >= (3, 8): - class FilterError(TarError): - # This attribute is only set directly on the subclasses, but the documentation guarantees - # that it is always present on FilterError. - tarinfo: TarInfo +class FilterError(TarError): + # This attribute is only set directly on the subclasses, but the documentation guarantees + # that it is always present on FilterError. + tarinfo: TarInfo - class AbsolutePathError(FilterError): - def __init__(self, tarinfo: TarInfo) -> None: ... +class AbsolutePathError(FilterError): + def __init__(self, tarinfo: TarInfo) -> None: ... - class OutsideDestinationError(FilterError): - def __init__(self, tarinfo: TarInfo, path: str) -> None: ... +class OutsideDestinationError(FilterError): + def __init__(self, tarinfo: TarInfo, path: str) -> None: ... - class SpecialFileError(FilterError): - def __init__(self, tarinfo: TarInfo) -> None: ... +class SpecialFileError(FilterError): + def __init__(self, tarinfo: TarInfo) -> None: ... - class AbsoluteLinkError(FilterError): - def __init__(self, tarinfo: TarInfo) -> None: ... +class AbsoluteLinkError(FilterError): + def __init__(self, tarinfo: TarInfo) -> None: ... - class LinkOutsideDestinationError(FilterError): - def __init__(self, tarinfo: TarInfo, path: str) -> None: ... +class LinkOutsideDestinationError(FilterError): + def __init__(self, tarinfo: TarInfo, path: str) -> None: ... - def fully_trusted_filter(member: TarInfo, dest_path: str) -> TarInfo: ... - def tar_filter(member: TarInfo, dest_path: str) -> TarInfo: ... - def data_filter(member: TarInfo, dest_path: str) -> TarInfo: ... +def fully_trusted_filter(member: TarInfo, dest_path: str) -> TarInfo: ... +def tar_filter(member: TarInfo, dest_path: str) -> TarInfo: ... +def data_filter(member: TarInfo, dest_path: str) -> TarInfo: ... class TarInfo: name: str @@ -414,27 +402,21 @@ class TarInfo: def linkpath(self) -> str: ... @linkpath.setter def linkpath(self, linkname: str) -> None: ... - if sys.version_info >= (3, 8): - def replace( - self, - *, - name: str = ..., - mtime: int = ..., - mode: int = ..., - linkname: str = ..., - uid: int = ..., - gid: int = ..., - uname: str = ..., - gname: str = ..., - deep: bool = True, - ) -> Self: ... - + def replace( + self, + *, + name: str = ..., + mtime: int = ..., + mode: int = ..., + linkname: str = ..., + uid: int = ..., + gid: int = ..., + uname: str = ..., + gname: str = ..., + deep: bool = True, + ) -> Self: ... def get_info(self) -> Mapping[str, str | int | bytes | Mapping[str, str]]: ... - if sys.version_info >= (3, 8): - def tobuf(self, format: int | None = 2, encoding: str | None = "utf-8", errors: str = "surrogateescape") -> bytes: ... - else: - def tobuf(self, format: int | None = 1, encoding: str | None = "utf-8", errors: str = "surrogateescape") -> bytes: ... - + def tobuf(self, format: int | None = 2, encoding: str | None = "utf-8", errors: str = "surrogateescape") -> bytes: ... def create_ustar_header( self, info: Mapping[str, str | int | bytes | Mapping[str, str]], encoding: str, errors: str ) -> bytes: ... diff --git a/mypy/typeshed/stdlib/tempfile.pyi b/mypy/typeshed/stdlib/tempfile.pyi index 628f99410732..2c4b548458ea 100644 --- a/mypy/typeshed/stdlib/tempfile.pyi +++ b/mypy/typeshed/stdlib/tempfile.pyi @@ -14,8 +14,8 @@ from _typeshed import ( ) from collections.abc import Iterable, Iterator from types import TracebackType -from typing import IO, Any, AnyStr, Generic, overload -from typing_extensions import Literal, Self +from typing import IO, Any, AnyStr, Generic, Literal, overload +from typing_extensions import Self if sys.version_info >= (3, 9): from types import GenericAlias @@ -85,7 +85,7 @@ if sys.version_info >= (3, 12): delete_on_close: bool = True, ) -> _TemporaryFileWrapper[Any]: ... -elif sys.version_info >= (3, 8): +else: @overload def NamedTemporaryFile( mode: OpenTextMode, @@ -126,9 +126,12 @@ elif sys.version_info >= (3, 8): errors: str | None = None, ) -> _TemporaryFileWrapper[Any]: ... +if sys.platform == "win32": + TemporaryFile = NamedTemporaryFile else: + # See the comments for builtins.open() for an explanation of the overloads. @overload - def NamedTemporaryFile( + def TemporaryFile( mode: OpenTextMode, buffering: int = -1, encoding: str | None = None, @@ -136,21 +139,70 @@ else: suffix: AnyStr | None = None, prefix: AnyStr | None = None, dir: GenericPath[AnyStr] | None = None, - delete: bool = True, - ) -> _TemporaryFileWrapper[str]: ... + *, + errors: str | None = None, + ) -> io.TextIOWrapper: ... @overload - def NamedTemporaryFile( - mode: OpenBinaryMode = "w+b", - buffering: int = -1, + def TemporaryFile( + mode: OpenBinaryMode, + buffering: Literal[0], encoding: str | None = None, newline: str | None = None, suffix: AnyStr | None = None, prefix: AnyStr | None = None, dir: GenericPath[AnyStr] | None = None, - delete: bool = True, - ) -> _TemporaryFileWrapper[bytes]: ... + *, + errors: str | None = None, + ) -> io.FileIO: ... @overload - def NamedTemporaryFile( + def TemporaryFile( + *, + buffering: Literal[0], + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: GenericPath[AnyStr] | None = None, + errors: str | None = None, + ) -> io.FileIO: ... + @overload + def TemporaryFile( + mode: OpenBinaryModeWriting, + buffering: Literal[-1, 1] = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: GenericPath[AnyStr] | None = None, + *, + errors: str | None = None, + ) -> io.BufferedWriter: ... + @overload + def TemporaryFile( + mode: OpenBinaryModeReading, + buffering: Literal[-1, 1] = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: GenericPath[AnyStr] | None = None, + *, + errors: str | None = None, + ) -> io.BufferedReader: ... + @overload + def TemporaryFile( + mode: OpenBinaryModeUpdating = "w+b", + buffering: Literal[-1, 1] = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: GenericPath[AnyStr] | None = None, + *, + errors: str | None = None, + ) -> io.BufferedRandom: ... + @overload + def TemporaryFile( mode: str = "w+b", buffering: int = -1, encoding: str | None = None, @@ -158,168 +210,9 @@ else: suffix: AnyStr | None = None, prefix: AnyStr | None = None, dir: GenericPath[AnyStr] | None = None, - delete: bool = True, - ) -> _TemporaryFileWrapper[Any]: ... - -if sys.platform == "win32": - TemporaryFile = NamedTemporaryFile -else: - # See the comments for builtins.open() for an explanation of the overloads. - if sys.version_info >= (3, 8): - @overload - def TemporaryFile( - mode: OpenTextMode, - buffering: int = -1, - encoding: str | None = None, - newline: str | None = None, - suffix: AnyStr | None = None, - prefix: AnyStr | None = None, - dir: GenericPath[AnyStr] | None = None, - *, - errors: str | None = None, - ) -> io.TextIOWrapper: ... - @overload - def TemporaryFile( - mode: OpenBinaryMode, - buffering: Literal[0], - encoding: str | None = None, - newline: str | None = None, - suffix: AnyStr | None = None, - prefix: AnyStr | None = None, - dir: GenericPath[AnyStr] | None = None, - *, - errors: str | None = None, - ) -> io.FileIO: ... - @overload - def TemporaryFile( - *, - buffering: Literal[0], - encoding: str | None = None, - newline: str | None = None, - suffix: AnyStr | None = None, - prefix: AnyStr | None = None, - dir: GenericPath[AnyStr] | None = None, - errors: str | None = None, - ) -> io.FileIO: ... - @overload - def TemporaryFile( - mode: OpenBinaryModeWriting, - buffering: Literal[-1, 1] = -1, - encoding: str | None = None, - newline: str | None = None, - suffix: AnyStr | None = None, - prefix: AnyStr | None = None, - dir: GenericPath[AnyStr] | None = None, - *, - errors: str | None = None, - ) -> io.BufferedWriter: ... - @overload - def TemporaryFile( - mode: OpenBinaryModeReading, - buffering: Literal[-1, 1] = -1, - encoding: str | None = None, - newline: str | None = None, - suffix: AnyStr | None = None, - prefix: AnyStr | None = None, - dir: GenericPath[AnyStr] | None = None, - *, - errors: str | None = None, - ) -> io.BufferedReader: ... - @overload - def TemporaryFile( - mode: OpenBinaryModeUpdating = "w+b", - buffering: Literal[-1, 1] = -1, - encoding: str | None = None, - newline: str | None = None, - suffix: AnyStr | None = None, - prefix: AnyStr | None = None, - dir: GenericPath[AnyStr] | None = None, - *, - errors: str | None = None, - ) -> io.BufferedRandom: ... - @overload - def TemporaryFile( - mode: str = "w+b", - buffering: int = -1, - encoding: str | None = None, - newline: str | None = None, - suffix: AnyStr | None = None, - prefix: AnyStr | None = None, - dir: GenericPath[AnyStr] | None = None, - *, - errors: str | None = None, - ) -> IO[Any]: ... - else: - @overload - def TemporaryFile( - mode: OpenTextMode, - buffering: int = -1, - encoding: str | None = None, - newline: str | None = None, - suffix: AnyStr | None = None, - prefix: AnyStr | None = None, - dir: GenericPath[AnyStr] | None = None, - ) -> io.TextIOWrapper: ... - @overload - def TemporaryFile( - mode: OpenBinaryMode, - buffering: Literal[0], - encoding: str | None = None, - newline: str | None = None, - suffix: AnyStr | None = None, - prefix: AnyStr | None = None, - dir: GenericPath[AnyStr] | None = None, - ) -> io.FileIO: ... - @overload - def TemporaryFile( - *, - buffering: Literal[0], - encoding: str | None = None, - newline: str | None = None, - suffix: AnyStr | None = None, - prefix: AnyStr | None = None, - dir: GenericPath[AnyStr] | None = None, - ) -> io.FileIO: ... - @overload - def TemporaryFile( - mode: OpenBinaryModeUpdating = "w+b", - buffering: Literal[-1, 1] = -1, - encoding: str | None = None, - newline: str | None = None, - suffix: AnyStr | None = None, - prefix: AnyStr | None = None, - dir: GenericPath[AnyStr] | None = None, - ) -> io.BufferedRandom: ... - @overload - def TemporaryFile( - mode: OpenBinaryModeWriting, - buffering: Literal[-1, 1] = -1, - encoding: str | None = None, - newline: str | None = None, - suffix: AnyStr | None = None, - prefix: AnyStr | None = None, - dir: GenericPath[AnyStr] | None = None, - ) -> io.BufferedWriter: ... - @overload - def TemporaryFile( - mode: OpenBinaryModeReading, - buffering: Literal[-1, 1] = -1, - encoding: str | None = None, - newline: str | None = None, - suffix: AnyStr | None = None, - prefix: AnyStr | None = None, - dir: GenericPath[AnyStr] | None = None, - ) -> io.BufferedReader: ... - @overload - def TemporaryFile( - mode: str = "w+b", - buffering: int = -1, - encoding: str | None = None, - newline: str | None = None, - suffix: AnyStr | None = None, - prefix: AnyStr | None = None, - dir: GenericPath[AnyStr] | None = None, - ) -> IO[Any]: ... + *, + errors: str | None = None, + ) -> IO[Any]: ... class _TemporaryFileWrapper(IO[AnyStr]): file: IO[AnyStr] # io.TextIOWrapper, io.BufferedReader or io.BufferedWriter @@ -386,143 +279,78 @@ class SpooledTemporaryFile(IO[AnyStr], _SpooledTemporaryFileBase): @property def newlines(self) -> str | tuple[str, ...] | None: ... # undocumented # bytes needs to go first, as default mode is to open as bytes - if sys.version_info >= (3, 8): - @overload - def __init__( - self: SpooledTemporaryFile[bytes], - max_size: int = 0, - mode: OpenBinaryMode = "w+b", - buffering: int = -1, - encoding: str | None = None, - newline: str | None = None, - suffix: str | None = None, - prefix: str | None = None, - dir: str | None = None, - *, - errors: str | None = None, - ) -> None: ... - @overload - def __init__( - self: SpooledTemporaryFile[str], - max_size: int, - mode: OpenTextMode, - buffering: int = -1, - encoding: str | None = None, - newline: str | None = None, - suffix: str | None = None, - prefix: str | None = None, - dir: str | None = None, - *, - errors: str | None = None, - ) -> None: ... - @overload - def __init__( - self: SpooledTemporaryFile[str], - max_size: int = 0, - *, - mode: OpenTextMode, - buffering: int = -1, - encoding: str | None = None, - newline: str | None = None, - suffix: str | None = None, - prefix: str | None = None, - dir: str | None = None, - errors: str | None = None, - ) -> None: ... - @overload - def __init__( - self, - max_size: int, - mode: str, - buffering: int = -1, - encoding: str | None = None, - newline: str | None = None, - suffix: str | None = None, - prefix: str | None = None, - dir: str | None = None, - *, - errors: str | None = None, - ) -> None: ... - @overload - def __init__( - self, - max_size: int = 0, - *, - mode: str, - buffering: int = -1, - encoding: str | None = None, - newline: str | None = None, - suffix: str | None = None, - prefix: str | None = None, - dir: str | None = None, - errors: str | None = None, - ) -> None: ... - @property - def errors(self) -> str | None: ... - else: - @overload - def __init__( - self: SpooledTemporaryFile[bytes], - max_size: int = 0, - mode: OpenBinaryMode = "w+b", - buffering: int = -1, - encoding: str | None = None, - newline: str | None = None, - suffix: str | None = None, - prefix: str | None = None, - dir: str | None = None, - ) -> None: ... - @overload - def __init__( - self: SpooledTemporaryFile[str], - max_size: int, - mode: OpenTextMode, - buffering: int = -1, - encoding: str | None = None, - newline: str | None = None, - suffix: str | None = None, - prefix: str | None = None, - dir: str | None = None, - ) -> None: ... - @overload - def __init__( - self: SpooledTemporaryFile[str], - max_size: int = 0, - *, - mode: OpenTextMode, - buffering: int = -1, - encoding: str | None = None, - newline: str | None = None, - suffix: str | None = None, - prefix: str | None = None, - dir: str | None = None, - ) -> None: ... - @overload - def __init__( - self, - max_size: int, - mode: str, - buffering: int = -1, - encoding: str | None = None, - newline: str | None = None, - suffix: str | None = None, - prefix: str | None = None, - dir: str | None = None, - ) -> None: ... - @overload - def __init__( - self, - max_size: int = 0, - *, - mode: str, - buffering: int = -1, - encoding: str | None = None, - newline: str | None = None, - suffix: str | None = None, - prefix: str | None = None, - dir: str | None = None, - ) -> None: ... - + @overload + def __init__( + self: SpooledTemporaryFile[bytes], + max_size: int = 0, + mode: OpenBinaryMode = "w+b", + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, + *, + errors: str | None = None, + ) -> None: ... + @overload + def __init__( + self: SpooledTemporaryFile[str], + max_size: int, + mode: OpenTextMode, + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, + *, + errors: str | None = None, + ) -> None: ... + @overload + def __init__( + self: SpooledTemporaryFile[str], + max_size: int = 0, + *, + mode: OpenTextMode, + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, + errors: str | None = None, + ) -> None: ... + @overload + def __init__( + self, + max_size: int, + mode: str, + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, + *, + errors: str | None = None, + ) -> None: ... + @overload + def __init__( + self, + max_size: int = 0, + *, + mode: str, + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, + errors: str | None = None, + ) -> None: ... + @property + def errors(self) -> str | None: ... def rollover(self) -> None: ... def __enter__(self) -> Self: ... def __exit__(self, exc: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) -> None: ... diff --git a/mypy/typeshed/stdlib/threading.pyi b/mypy/typeshed/stdlib/threading.pyi index bcd73823c63f..90b6cabb5237 100644 --- a/mypy/typeshed/stdlib/threading.pyi +++ b/mypy/typeshed/stdlib/threading.pyi @@ -1,10 +1,10 @@ import _thread import sys +from _thread import _excepthook, _ExceptHookArgs, get_native_id as get_native_id from _typeshed import ProfileFunction, TraceFunction from collections.abc import Callable, Iterable, Mapping from types import TracebackType -from typing import Any, TypeVar -from typing_extensions import final +from typing import Any, TypeVar, final _T = TypeVar("_T") @@ -26,15 +26,15 @@ __all__ = [ "BrokenBarrierError", "Timer", "ThreadError", + "ExceptHookArgs", "setprofile", "settrace", "local", "stack_size", + "excepthook", + "get_native_id", ] -if sys.version_info >= (3, 8): - __all__ += ["ExceptHookArgs", "excepthook", "get_native_id"] - if sys.version_info >= (3, 10): __all__ += ["getprofile", "gettrace"] @@ -50,10 +50,6 @@ def currentThread() -> Thread: ... # deprecated alias for current_thread() def get_ident() -> int: ... def enumerate() -> list[Thread]: ... def main_thread() -> Thread: ... - -if sys.version_info >= (3, 8): - from _thread import get_native_id as get_native_id - def settrace(func: TraceFunction) -> None: ... def setprofile(func: ProfileFunction | None) -> None: ... @@ -90,10 +86,8 @@ class Thread: def start(self) -> None: ... def run(self) -> None: ... def join(self, timeout: float | None = None) -> None: ... - if sys.version_info >= (3, 8): - @property - def native_id(self) -> int | None: ... # only available on some platforms - + @property + def native_id(self) -> int | None: ... # only available on some platforms def is_alive(self) -> bool: ... if sys.version_info < (3, 9): def isAlive(self) -> bool: ... @@ -159,11 +153,8 @@ class Event: def clear(self) -> None: ... def wait(self, timeout: float | None = None) -> bool: ... -if sys.version_info >= (3, 8): - from _thread import _excepthook, _ExceptHookArgs - - excepthook = _excepthook - ExceptHookArgs = _ExceptHookArgs +excepthook = _excepthook +ExceptHookArgs = _ExceptHookArgs class Timer(Thread): args: Iterable[Any] # undocumented diff --git a/mypy/typeshed/stdlib/time.pyi b/mypy/typeshed/stdlib/time.pyi index 035d78934f3a..28752bddc4dd 100644 --- a/mypy/typeshed/stdlib/time.pyi +++ b/mypy/typeshed/stdlib/time.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import structseq -from typing import Any, Protocol -from typing_extensions import Final, Literal, TypeAlias, final +from typing import Any, Final, Literal, Protocol, final +from typing_extensions import TypeAlias _TimeTuple: TypeAlias = tuple[int, int, int, int, int, int, int, int, int] @@ -25,7 +25,7 @@ if sys.platform != "win32": if sys.platform != "linux" and sys.platform != "darwin": CLOCK_HIGHRES: int # Solaris only -if sys.version_info >= (3, 8) and sys.platform == "darwin": +if sys.platform == "darwin": CLOCK_UPTIME_RAW: int if sys.version_info >= (3, 9) and sys.platform == "linux": @@ -63,18 +63,14 @@ class struct_time(structseq[Any | int], _TimeTuple): @property def tm_gmtoff(self) -> int: ... -def asctime(t: _TimeTuple | struct_time = ...) -> str: ... - -if sys.version_info < (3, 8): - def clock() -> float: ... - -def ctime(secs: float | None = ...) -> str: ... -def gmtime(secs: float | None = ...) -> struct_time: ... -def localtime(secs: float | None = ...) -> struct_time: ... -def mktime(t: _TimeTuple | struct_time) -> float: ... -def sleep(secs: float) -> None: ... -def strftime(format: str, t: _TimeTuple | struct_time = ...) -> str: ... -def strptime(string: str, format: str = ...) -> struct_time: ... +def asctime(time_tuple: _TimeTuple | struct_time = ..., /) -> str: ... +def ctime(seconds: float | None = None, /) -> str: ... +def gmtime(seconds: float | None = None, /) -> struct_time: ... +def localtime(seconds: float | None = None, /) -> struct_time: ... +def mktime(time_tuple: _TimeTuple | struct_time, /) -> float: ... +def sleep(seconds: float, /) -> None: ... +def strftime(format: str, time_tuple: _TimeTuple | struct_time = ..., /) -> str: ... +def strptime(data_string: str, format: str = "%a %b %d %H:%M:%S %Y", /) -> struct_time: ... def time() -> float: ... if sys.platform != "win32": @@ -86,22 +82,22 @@ class _ClockInfo(Protocol): monotonic: bool resolution: float -def get_clock_info(name: Literal["monotonic", "perf_counter", "process_time", "time", "thread_time"]) -> _ClockInfo: ... +def get_clock_info(name: Literal["monotonic", "perf_counter", "process_time", "time", "thread_time"], /) -> _ClockInfo: ... def monotonic() -> float: ... def perf_counter() -> float: ... def process_time() -> float: ... if sys.platform != "win32": - def clock_getres(clk_id: int) -> float: ... # Unix only - def clock_gettime(clk_id: int) -> float: ... # Unix only - def clock_settime(clk_id: int, time: float) -> None: ... # Unix only + def clock_getres(clk_id: int, /) -> float: ... # Unix only + def clock_gettime(clk_id: int, /) -> float: ... # Unix only + def clock_settime(clk_id: int, time: float, /) -> None: ... # Unix only if sys.platform != "win32": - def clock_gettime_ns(clock_id: int) -> int: ... - def clock_settime_ns(clock_id: int, time: int) -> int: ... + def clock_gettime_ns(clock_id: int, /) -> int: ... + def clock_settime_ns(clock_id: int, time: int, /) -> int: ... if sys.platform == "linux": - def pthread_getcpuclockid(thread_id: int) -> int: ... + def pthread_getcpuclockid(thread_id: int, /) -> int: ... def monotonic_ns() -> int: ... def perf_counter_ns() -> int: ... diff --git a/mypy/typeshed/stdlib/tkinter/__init__.pyi b/mypy/typeshed/stdlib/tkinter/__init__.pyi index 5f7c3cb4527d..ff876d0bb88c 100644 --- a/mypy/typeshed/stdlib/tkinter/__init__.pyi +++ b/mypy/typeshed/stdlib/tkinter/__init__.pyi @@ -5,8 +5,8 @@ from collections.abc import Callable, Mapping, Sequence from tkinter.constants import * from tkinter.font import _FontDescription from types import TracebackType -from typing import Any, Generic, NamedTuple, TypeVar, overload, type_check_only -from typing_extensions import Literal, TypeAlias, TypedDict, TypeVarTuple, Unpack, deprecated +from typing import Any, Generic, Literal, NamedTuple, TypedDict, TypeVar, overload, type_check_only +from typing_extensions import TypeAlias, TypeVarTuple, Unpack, deprecated if sys.version_info >= (3, 9): __all__ = [ @@ -1254,7 +1254,7 @@ class Canvas(Widget, XView, YView): offset: _ScreenUnits = ..., smooth: bool = ..., splinesteps: float = ..., - state: Literal["normal", "active", "disabled"] = ..., + state: Literal["normal", "hidden", "disabled"] = ..., stipple: str = ..., tags: str | list[str] | tuple[str, ...] = ..., width: _ScreenUnits = ..., @@ -1283,7 +1283,7 @@ class Canvas(Widget, XView, YView): offset: _ScreenUnits = ..., smooth: bool = ..., splinesteps: float = ..., - state: Literal["normal", "active", "disabled"] = ..., + state: Literal["normal", "hidden", "disabled"] = ..., stipple: str = ..., tags: str | list[str] | tuple[str, ...] = ..., width: _ScreenUnits = ..., @@ -1318,7 +1318,7 @@ class Canvas(Widget, XView, YView): offset: _ScreenUnits = ..., smooth: bool = ..., splinesteps: float = ..., - state: Literal["normal", "active", "disabled"] = ..., + state: Literal["normal", "hidden", "disabled"] = ..., stipple: str = ..., tags: str | list[str] | tuple[str, ...] = ..., width: _ScreenUnits = ..., @@ -1350,7 +1350,7 @@ class Canvas(Widget, XView, YView): outline: str = ..., outlineoffset: _ScreenUnits = ..., outlinestipple: str = ..., - state: Literal["normal", "active", "disabled"] = ..., + state: Literal["normal", "hidden", "disabled"] = ..., stipple: str = ..., tags: str | list[str] | tuple[str, ...] = ..., width: _ScreenUnits = ..., @@ -1380,7 +1380,7 @@ class Canvas(Widget, XView, YView): outline: str = ..., outlineoffset: _ScreenUnits = ..., outlinestipple: str = ..., - state: Literal["normal", "active", "disabled"] = ..., + state: Literal["normal", "hidden", "disabled"] = ..., stipple: str = ..., tags: str | list[str] | tuple[str, ...] = ..., width: _ScreenUnits = ..., @@ -1416,7 +1416,7 @@ class Canvas(Widget, XView, YView): outline: str = ..., outlineoffset: _ScreenUnits = ..., outlinestipple: str = ..., - state: Literal["normal", "active", "disabled"] = ..., + state: Literal["normal", "hidden", "disabled"] = ..., stipple: str = ..., tags: str | list[str] | tuple[str, ...] = ..., width: _ScreenUnits = ..., @@ -1451,7 +1451,7 @@ class Canvas(Widget, XView, YView): outlinestipple: str = ..., smooth: bool = ..., splinesteps: float = ..., - state: Literal["normal", "active", "disabled"] = ..., + state: Literal["normal", "hidden", "disabled"] = ..., stipple: str = ..., tags: str | list[str] | tuple[str, ...] = ..., width: _ScreenUnits = ..., @@ -1484,7 +1484,7 @@ class Canvas(Widget, XView, YView): outlinestipple: str = ..., smooth: bool = ..., splinesteps: float = ..., - state: Literal["normal", "active", "disabled"] = ..., + state: Literal["normal", "hidden", "disabled"] = ..., stipple: str = ..., tags: str | list[str] | tuple[str, ...] = ..., width: _ScreenUnits = ..., @@ -1523,7 +1523,7 @@ class Canvas(Widget, XView, YView): outlinestipple: str = ..., smooth: bool = ..., splinesteps: float = ..., - state: Literal["normal", "active", "disabled"] = ..., + state: Literal["normal", "hidden", "disabled"] = ..., stipple: str = ..., tags: str | list[str] | tuple[str, ...] = ..., width: _ScreenUnits = ..., @@ -1555,7 +1555,7 @@ class Canvas(Widget, XView, YView): outline: str = ..., outlineoffset: _ScreenUnits = ..., outlinestipple: str = ..., - state: Literal["normal", "active", "disabled"] = ..., + state: Literal["normal", "hidden", "disabled"] = ..., stipple: str = ..., tags: str | list[str] | tuple[str, ...] = ..., width: _ScreenUnits = ..., @@ -1585,7 +1585,7 @@ class Canvas(Widget, XView, YView): outline: str = ..., outlineoffset: _ScreenUnits = ..., outlinestipple: str = ..., - state: Literal["normal", "active", "disabled"] = ..., + state: Literal["normal", "hidden", "disabled"] = ..., stipple: str = ..., tags: str | list[str] | tuple[str, ...] = ..., width: _ScreenUnits = ..., @@ -1621,7 +1621,7 @@ class Canvas(Widget, XView, YView): outline: str = ..., outlineoffset: _ScreenUnits = ..., outlinestipple: str = ..., - state: Literal["normal", "active", "disabled"] = ..., + state: Literal["normal", "hidden", "disabled"] = ..., stipple: str = ..., tags: str | list[str] | tuple[str, ...] = ..., width: _ScreenUnits = ..., @@ -1642,7 +1642,7 @@ class Canvas(Widget, XView, YView): font: _FontDescription = ..., justify: Literal["left", "center", "right"] = ..., offset: _ScreenUnits = ..., - state: Literal["normal", "active", "disabled"] = ..., + state: Literal["normal", "hidden", "disabled"] = ..., stipple: str = ..., tags: str | list[str] | tuple[str, ...] = ..., text: float | str = ..., @@ -1663,7 +1663,7 @@ class Canvas(Widget, XView, YView): font: _FontDescription = ..., justify: Literal["left", "center", "right"] = ..., offset: _ScreenUnits = ..., - state: Literal["normal", "active", "disabled"] = ..., + state: Literal["normal", "hidden", "disabled"] = ..., stipple: str = ..., tags: str | list[str] | tuple[str, ...] = ..., text: float | str = ..., @@ -1677,7 +1677,7 @@ class Canvas(Widget, XView, YView): *, anchor: _Anchor = ..., height: _ScreenUnits = ..., - state: Literal["normal", "active", "disabled"] = ..., + state: Literal["normal", "hidden", "disabled"] = ..., tags: str | list[str] | tuple[str, ...] = ..., width: _ScreenUnits = ..., window: Widget = ..., @@ -1689,7 +1689,7 @@ class Canvas(Widget, XView, YView): *, anchor: _Anchor = ..., height: _ScreenUnits = ..., - state: Literal["normal", "active", "disabled"] = ..., + state: Literal["normal", "hidden", "disabled"] = ..., tags: str | list[str] | tuple[str, ...] = ..., width: _ScreenUnits = ..., window: Widget = ..., @@ -1712,9 +1712,7 @@ class Canvas(Widget, XView, YView): ) -> dict[str, tuple[str, str, str, str, str]] | None: ... itemconfig = itemconfigure def move(self, *args) -> None: ... - if sys.version_info >= (3, 8): - def moveto(self, tagOrId: str | int, x: Literal[""] | float = "", y: Literal[""] | float = "") -> None: ... - + def moveto(self, tagOrId: str | int, x: Literal[""] | float = "", y: Literal[""] | float = "") -> None: ... def postscript(self, cnf={}, **kw): ... # tkinter does: # lower = tag_lower @@ -3338,9 +3336,8 @@ class PhotoImage(Image, _PhotoImageLike): to: tuple[int, int] | None = None, ) -> None: ... def write(self, filename: StrOrBytesPath, format: str | None = None, from_coords: tuple[int, int] | None = None) -> None: ... - if sys.version_info >= (3, 8): - def transparency_get(self, x: int, y: int) -> bool: ... - def transparency_set(self, x: int, y: int, boolean: bool) -> None: ... + def transparency_get(self, x: int, y: int) -> bool: ... + def transparency_set(self, x: int, y: int, boolean: bool) -> None: ... class BitmapImage(Image, _BitmapImageLike): # This should be kept in sync with PIL.ImageTK.BitmapImage.__init__() @@ -3495,11 +3492,10 @@ class Spinbox(Widget, XView): def selection_adjust(self, index): ... def selection_clear(self): ... def selection_element(self, element: Incomplete | None = None): ... - if sys.version_info >= (3, 8): - def selection_from(self, index: int) -> None: ... - def selection_present(self) -> None: ... - def selection_range(self, start: int, end: int) -> None: ... - def selection_to(self, index: int) -> None: ... + def selection_from(self, index: int) -> None: ... + def selection_present(self) -> None: ... + def selection_range(self, start: int, end: int) -> None: ... + def selection_to(self, index: int) -> None: ... class LabelFrame(Widget): def __init__( diff --git a/mypy/typeshed/stdlib/tkinter/constants.pyi b/mypy/typeshed/stdlib/tkinter/constants.pyi index 1383b0f9bf4b..74fa72acb0bf 100644 --- a/mypy/typeshed/stdlib/tkinter/constants.pyi +++ b/mypy/typeshed/stdlib/tkinter/constants.pyi @@ -1,4 +1,4 @@ -from typing_extensions import Literal +from typing import Literal # These are not actually bools. See #4669 NO: bool diff --git a/mypy/typeshed/stdlib/tkinter/filedialog.pyi b/mypy/typeshed/stdlib/tkinter/filedialog.pyi index 10b36e4d3c06..3d62f079178e 100644 --- a/mypy/typeshed/stdlib/tkinter/filedialog.pyi +++ b/mypy/typeshed/stdlib/tkinter/filedialog.pyi @@ -2,8 +2,7 @@ import sys from _typeshed import Incomplete, StrOrBytesPath from collections.abc import Iterable from tkinter import Button, Entry, Frame, Listbox, Misc, Scrollbar, StringVar, Toplevel, commondialog -from typing import IO, ClassVar -from typing_extensions import Literal +from typing import IO, ClassVar, Literal if sys.version_info >= (3, 9): __all__ = [ diff --git a/mypy/typeshed/stdlib/tkinter/font.pyi b/mypy/typeshed/stdlib/tkinter/font.pyi index 9dffcd1ba0c6..448e2b0054a5 100644 --- a/mypy/typeshed/stdlib/tkinter/font.pyi +++ b/mypy/typeshed/stdlib/tkinter/font.pyi @@ -1,8 +1,8 @@ import _tkinter import sys import tkinter -from typing import Any, overload -from typing_extensions import Literal, TypeAlias, TypedDict +from typing import Any, Literal, TypedDict, overload +from typing_extensions import TypeAlias if sys.version_info >= (3, 9): __all__ = ["NORMAL", "ROMAN", "BOLD", "ITALIC", "nametofont", "Font", "families", "names"] @@ -15,8 +15,11 @@ ITALIC: Literal["italic"] _FontDescription: TypeAlias = ( str # "Helvetica 12" | Font # A font object constructed in Python - | list[Any] # ("Helvetica", 12, BOLD) - | tuple[Any, ...] + | list[Any] # ["Helvetica", 12, BOLD] + | tuple[str] # ("Liberation Sans",) needs wrapping in tuple/list to handle spaces + | tuple[str, int] # ("Liberation Sans", 12) + | tuple[str, int, str] # ("Liberation Sans", 12, "bold") + | tuple[str, int, list[str] | tuple[str, ...]] # e.g. bold and italic | _tkinter.Tcl_Obj # A font object constructed in Tcl ) diff --git a/mypy/typeshed/stdlib/tkinter/tix.pyi b/mypy/typeshed/stdlib/tkinter/tix.pyi index 672c5ab67403..73649de427e8 100644 --- a/mypy/typeshed/stdlib/tkinter/tix.pyi +++ b/mypy/typeshed/stdlib/tkinter/tix.pyi @@ -1,7 +1,6 @@ import tkinter from _typeshed import Incomplete -from typing import Any -from typing_extensions import Literal +from typing import Any, Literal WINDOW: Literal["window"] TEXT: Literal["text"] diff --git a/mypy/typeshed/stdlib/tkinter/ttk.pyi b/mypy/typeshed/stdlib/tkinter/ttk.pyi index 2bbbafbcb945..ac5accb73d9f 100644 --- a/mypy/typeshed/stdlib/tkinter/ttk.pyi +++ b/mypy/typeshed/stdlib/tkinter/ttk.pyi @@ -1,11 +1,10 @@ import _tkinter -import sys import tkinter from _typeshed import Incomplete from collections.abc import Callable from tkinter.font import _FontDescription -from typing import Any, overload -from typing_extensions import Literal, TypeAlias, TypedDict +from typing import Any, Literal, TypedDict, overload +from typing_extensions import TypeAlias __all__ = [ "Button", @@ -1102,11 +1101,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): def parent(self, item: str | int) -> str: ... def prev(self, item: str | int) -> str: ... # returning empty string means first item def see(self, item: str | int) -> None: ... - if sys.version_info >= (3, 8): - def selection(self) -> tuple[str, ...]: ... - else: - def selection(self, selop: Incomplete | None = ..., items: Incomplete | None = None) -> tuple[str, ...]: ... - + def selection(self) -> tuple[str, ...]: ... @overload def selection_set(self, __items: list[str] | tuple[str, ...] | list[int] | tuple[int, ...]) -> None: ... @overload diff --git a/mypy/typeshed/stdlib/token.pyi b/mypy/typeshed/stdlib/token.pyi index 85867a2b9744..f1fec7698043 100644 --- a/mypy/typeshed/stdlib/token.pyi +++ b/mypy/typeshed/stdlib/token.pyi @@ -3,11 +3,14 @@ import sys __all__ = [ "AMPER", "AMPEREQUAL", + "ASYNC", "AT", "ATEQUAL", + "AWAIT", "CIRCUMFLEX", "CIRCUMFLEXEQUAL", "COLON", + "COLONEQUAL", "COMMA", "DEDENT", "DOT", @@ -59,6 +62,8 @@ __all__ = [ "STAREQUAL", "STRING", "TILDE", + "TYPE_COMMENT", + "TYPE_IGNORE", "VBAR", "VBAREQUAL", "tok_name", @@ -67,9 +72,6 @@ __all__ = [ "COMMENT", ] -if sys.version_info >= (3, 8): - __all__ += ["ASYNC", "AWAIT", "COLONEQUAL", "TYPE_COMMENT", "TYPE_IGNORE"] - if sys.version_info >= (3, 10): __all__ += ["SOFT_KEYWORD"] @@ -129,9 +131,8 @@ AT: int RARROW: int ELLIPSIS: int ATEQUAL: int -if sys.version_info >= (3, 8): - AWAIT: int - ASYNC: int +AWAIT: int +ASYNC: int OP: int ERRORTOKEN: int N_TOKENS: int @@ -140,11 +141,10 @@ tok_name: dict[int, str] COMMENT: int NL: int ENCODING: int -if sys.version_info >= (3, 8): - TYPE_COMMENT: int - TYPE_IGNORE: int - COLONEQUAL: int - EXACT_TOKEN_TYPES: dict[str, int] +TYPE_COMMENT: int +TYPE_IGNORE: int +COLONEQUAL: int +EXACT_TOKEN_TYPES: dict[str, int] if sys.version_info >= (3, 10): SOFT_KEYWORD: int diff --git a/mypy/typeshed/stdlib/tokenize.pyi b/mypy/typeshed/stdlib/tokenize.pyi index 0028ed034ae6..3cd9ab8f87ce 100644 --- a/mypy/typeshed/stdlib/tokenize.pyi +++ b/mypy/typeshed/stdlib/tokenize.pyi @@ -3,17 +3,21 @@ from _typeshed import FileDescriptorOrPath from collections.abc import Callable, Generator, Iterable, Sequence from re import Pattern from token import * +from token import EXACT_TOKEN_TYPES as EXACT_TOKEN_TYPES from typing import Any, NamedTuple, TextIO from typing_extensions import TypeAlias __all__ = [ "AMPER", "AMPEREQUAL", + "ASYNC", "AT", "ATEQUAL", + "AWAIT", "CIRCUMFLEX", "CIRCUMFLEXEQUAL", "COLON", + "COLONEQUAL", "COMMA", "COMMENT", "DEDENT", @@ -68,29 +72,24 @@ __all__ = [ "STAREQUAL", "STRING", "TILDE", + "TYPE_COMMENT", + "TYPE_IGNORE", "TokenInfo", "VBAR", "VBAREQUAL", "detect_encoding", + "generate_tokens", "tok_name", "tokenize", "untokenize", ] -if sys.version_info >= (3, 8): - __all__ += ["ASYNC", "AWAIT", "COLONEQUAL", "generate_tokens", "TYPE_COMMENT", "TYPE_IGNORE"] - if sys.version_info >= (3, 10): __all__ += ["SOFT_KEYWORD"] if sys.version_info >= (3, 12): __all__ += ["EXCLAMATION", "FSTRING_END", "FSTRING_MIDDLE", "FSTRING_START"] -if sys.version_info >= (3, 8): - from token import EXACT_TOKEN_TYPES as EXACT_TOKEN_TYPES -else: - EXACT_TOKEN_TYPES: dict[str, int] - cookie_re: Pattern[str] blank_re: Pattern[bytes] diff --git a/mypy/typeshed/stdlib/traceback.pyi b/mypy/typeshed/stdlib/traceback.pyi index 47449dfe8143..f6720155936f 100644 --- a/mypy/typeshed/stdlib/traceback.pyi +++ b/mypy/typeshed/stdlib/traceback.pyi @@ -2,8 +2,8 @@ import sys from _typeshed import SupportsWrite, Unused from collections.abc import Generator, Iterable, Iterator, Mapping from types import FrameType, TracebackType -from typing import Any, overload -from typing_extensions import Literal, Self, TypeAlias +from typing import Any, Literal, overload +from typing_extensions import Self, TypeAlias __all__ = [ "extract_stack", @@ -240,8 +240,7 @@ class FrameSummary(Iterable[Any]): def __getitem__(self, pos: int) -> Any: ... def __iter__(self) -> Iterator[Any]: ... def __eq__(self, other: object) -> bool: ... - if sys.version_info >= (3, 8): - def __len__(self) -> Literal[4]: ... + def __len__(self) -> Literal[4]: ... class StackSummary(list[FrameSummary]): @classmethod diff --git a/mypy/typeshed/stdlib/tracemalloc.pyi b/mypy/typeshed/stdlib/tracemalloc.pyi index 6448a16ce11a..e721e414138b 100644 --- a/mypy/typeshed/stdlib/tracemalloc.pyi +++ b/mypy/typeshed/stdlib/tracemalloc.pyi @@ -1,8 +1,8 @@ import sys from _tracemalloc import * from collections.abc import Sequence -from typing import Any, overload -from typing_extensions import SupportsIndex, TypeAlias +from typing import Any, SupportsIndex, overload +from typing_extensions import TypeAlias def get_object_traceback(obj: object) -> Traceback | None: ... def take_snapshot() -> Snapshot: ... diff --git a/mypy/typeshed/stdlib/types.pyi b/mypy/typeshed/stdlib/types.pyi index b26a668d273b..05ffc2143233 100644 --- a/mypy/typeshed/stdlib/types.pyi +++ b/mypy/typeshed/stdlib/types.pyi @@ -16,8 +16,8 @@ from collections.abc import ( from importlib.machinery import ModuleSpec # pytype crashes if types.MappingProxyType inherits from collections.abc.Mapping instead of typing.Mapping -from typing import Any, ClassVar, Mapping, Protocol, TypeVar, overload # noqa: Y022 -from typing_extensions import Literal, ParamSpec, Self, TypeVarTuple, final +from typing import Any, ClassVar, Literal, Mapping, Protocol, TypeVar, final, overload # noqa: Y022 +from typing_extensions import ParamSpec, Self, TypeVarTuple __all__ = [ "FunctionType", @@ -45,11 +45,9 @@ __all__ = [ "MethodWrapperType", "WrapperDescriptorType", "resolve_bases", + "CellType", ] -if sys.version_info >= (3, 8): - __all__ += ["CellType"] - if sys.version_info >= (3, 9): __all__ += ["GenericAlias"] @@ -68,9 +66,7 @@ _VT_co = TypeVar("_VT_co", covariant=True) @final class _Cell: - if sys.version_info >= (3, 8): - def __new__(cls, __contents: object = ...) -> Self: ... - + def __new__(cls, __contents: object = ...) -> Self: ... def __eq__(self, __value: object) -> bool: ... __hash__: ClassVar[None] # type: ignore[assignment] cell_contents: Any @@ -118,10 +114,8 @@ class CodeType: def __hash__(self) -> int: ... @property def co_argcount(self) -> int: ... - if sys.version_info >= (3, 8): - @property - def co_posonlyargcount(self) -> int: ... - + @property + def co_posonlyargcount(self) -> int: ... @property def co_kwonlyargcount(self) -> int: ... @property @@ -203,30 +197,11 @@ class CodeType: __freevars: tuple[str, ...] = ..., __cellvars: tuple[str, ...] = ..., ) -> Self: ... - elif sys.version_info >= (3, 8): - def __new__( - cls, - __argcount: int, - __posonlyargcount: int, - __kwonlyargcount: int, - __nlocals: int, - __stacksize: int, - __flags: int, - __codestring: bytes, - __constants: tuple[object, ...], - __names: tuple[str, ...], - __varnames: tuple[str, ...], - __filename: str, - __name: str, - __firstlineno: int, - __lnotab: bytes, - __freevars: tuple[str, ...] = ..., - __cellvars: tuple[str, ...] = ..., - ) -> Self: ... else: def __new__( cls, __argcount: int, + __posonlyargcount: int, __kwonlyargcount: int, __nlocals: int, __stacksize: int, @@ -286,7 +261,7 @@ class CodeType: co_name: str = ..., co_linetable: bytes = ..., ) -> CodeType: ... - elif sys.version_info >= (3, 8): + else: def replace( self, *, @@ -418,18 +393,6 @@ class CoroutineType(Coroutine[_YieldT_co, _SendT_contra, _ReturnT_co]): @overload def throw(self, __typ: BaseException, __val: None = None, __tb: TracebackType | None = ...) -> _YieldT_co: ... -class _StaticFunctionType: - # Fictional type to correct the type of MethodType.__func__. - # FunctionType is a descriptor, so mypy follows the descriptor protocol and - # converts MethodType.__func__ back to MethodType (the return type of - # FunctionType.__get__). But this is actually a special case; MethodType is - # implemented in C and its attribute access doesn't go through - # __getattribute__. - # By wrapping FunctionType in _StaticFunctionType, we get the right result; - # similar to wrapping a function in staticmethod() at runtime to prevent it - # being bound as a method. - def __get__(self, obj: object, type: type | None) -> FunctionType: ... - @final class MethodType: @property @@ -437,7 +400,7 @@ class MethodType: @property def __defaults__(self) -> tuple[Any, ...] | None: ... # inherited from the added function @property - def __func__(self) -> _StaticFunctionType: ... + def __func__(self) -> Callable[..., Any]: ... @property def __self__(self) -> object: ... @property @@ -515,7 +478,7 @@ class ClassMethodDescriptorType: class TracebackType: def __new__(cls, tb_next: TracebackType | None, tb_frame: FrameType, tb_lasti: int, tb_lineno: int) -> Self: ... tb_next: TracebackType | None - # the rest are read-only even in 3.7 + # the rest are read-only @property def tb_frame(self) -> FrameType: ... @property @@ -598,8 +561,7 @@ def coroutine(func: Callable[_P, Generator[Any, Any, _R]]) -> Callable[_P, Await @overload def coroutine(func: _Fn) -> _Fn: ... -if sys.version_info >= (3, 8): - CellType = _Cell +CellType = _Cell if sys.version_info >= (3, 9): class GenericAlias: @@ -626,7 +588,10 @@ if sys.version_info >= (3, 10): @final class NoneType: def __bool__(self) -> Literal[False]: ... - EllipsisType = ellipsis # noqa: F821 from builtins + + @final + class EllipsisType: ... + from builtins import _NotImplementedType NotImplementedType = _NotImplementedType diff --git a/mypy/typeshed/stdlib/typing.pyi b/mypy/typeshed/stdlib/typing.pyi index 555df0ea47c8..9fef9d3922f5 100644 --- a/mypy/typeshed/stdlib/typing.pyi +++ b/mypy/typeshed/stdlib/typing.pyi @@ -1,4 +1,6 @@ -import collections # Needed by aliases like DefaultDict, see mypy issue 2986 +# TODO: The collections import is required, otherwise mypy crashes. +# https://github.com/python/mypy/issues/16744 +import collections # noqa: F401 # pyright: ignore import sys import typing_extensions from _collections_abc import dict_items, dict_keys, dict_values @@ -18,7 +20,7 @@ from types import ( TracebackType, WrapperDescriptorType, ) -from typing_extensions import Never as _Never, ParamSpec as _ParamSpec, final as _final +from typing_extensions import Never as _Never, ParamSpec as _ParamSpec if sys.version_info >= (3, 10): from types import UnionType @@ -46,6 +48,7 @@ __all__ = [ "DefaultDict", "Deque", "Dict", + "Final", "FrozenSet", "Generator", "Generic", @@ -55,6 +58,7 @@ __all__ = [ "Iterator", "KeysView", "List", + "Literal", "Mapping", "MappingView", "MutableMapping", @@ -63,6 +67,7 @@ __all__ = [ "NamedTuple", "NewType", "Optional", + "Protocol", "Reversible", "Sequence", "Set", @@ -71,38 +76,31 @@ __all__ = [ "SupportsBytes", "SupportsComplex", "SupportsFloat", + "SupportsIndex", "SupportsInt", "SupportsRound", "Text", "Tuple", "Type", "TypeVar", + "TypedDict", "Union", "ValuesView", "TYPE_CHECKING", "cast", + "final", + "get_args", + "get_origin", "get_type_hints", "no_type_check", "no_type_check_decorator", "overload", + "runtime_checkable", "ForwardRef", "NoReturn", "OrderedDict", ] -if sys.version_info >= (3, 8): - __all__ += [ - "Final", - "Literal", - "Protocol", - "SupportsIndex", - "TypedDict", - "final", - "get_args", - "get_origin", - "runtime_checkable", - ] - if sys.version_info >= (3, 9): __all__ += ["Annotated", "BinaryIO", "IO", "Match", "Pattern", "TextIO"] @@ -137,7 +135,8 @@ def type_check_only(func_or_cls: _F) -> _F: ... Any = object() -@_final +def final(f: _T) -> _T: ... +@final class TypeVar: @property def __name__(self) -> str: ... @@ -175,7 +174,7 @@ class TypeVar: _promote = object() # N.B. Keep this definition in sync with typing_extensions._SpecialForm -@_final +@final class _SpecialForm: def __getitem__(self, parameters: Any) -> object: ... if sys.version_info >= (3, 10): @@ -199,12 +198,11 @@ ClassVar: _SpecialForm Optional: _SpecialForm Tuple: _SpecialForm -if sys.version_info >= (3, 8): - Final: _SpecialForm - def final(f: _T) -> _T: ... - Literal: _SpecialForm - # TypedDict is a (non-subscriptable) special form. - TypedDict: object +Final: _SpecialForm + +Literal: _SpecialForm +# TypedDict is a (non-subscriptable) special form. +TypedDict: object if sys.version_info >= (3, 11): Self: _SpecialForm @@ -214,7 +212,7 @@ if sys.version_info >= (3, 11): NotRequired: _SpecialForm LiteralString: _SpecialForm - @_final + @final class TypeVarTuple: @property def __name__(self) -> str: ... @@ -224,21 +222,21 @@ if sys.version_info >= (3, 11): def __typing_prepare_subst__(self, alias: Incomplete, args: Incomplete) -> Incomplete: ... if sys.version_info >= (3, 10): - @_final + @final class ParamSpecArgs: @property def __origin__(self) -> ParamSpec: ... def __init__(self, origin: ParamSpec) -> None: ... def __eq__(self, other: object) -> bool: ... - @_final + @final class ParamSpecKwargs: @property def __origin__(self) -> ParamSpec: ... def __init__(self, origin: ParamSpec) -> None: ... def __eq__(self, other: object) -> bool: ... - @_final + @final class ParamSpec: @property def __name__(self) -> str: ... @@ -301,7 +299,7 @@ _VT = TypeVar("_VT") # Value type. _T_co = TypeVar("_T_co", covariant=True) # Any type covariant containers. _KT_co = TypeVar("_KT_co", covariant=True) # Key type covariant containers. _VT_co = TypeVar("_VT_co", covariant=True) # Value type covariant containers. -_TC = TypeVar("_TC", bound=Type[object]) +_TC = TypeVar("_TC", bound=type[object]) def no_type_check(arg: _F) -> _F: ... def no_type_check_decorator(decorator: Callable[_P, _T]) -> Callable[_P, _T]: ... @@ -329,8 +327,6 @@ if sys.version_info >= (3, 9): # Predefined type variables. AnyStr = TypeVar("AnyStr", str, bytes) # noqa: Y001 -# Technically in 3.7 this inherited from GenericMeta. But let's not reflect that, since -# type checkers tend to assume that Protocols all have the ABCMeta metaclass. class _ProtocolMeta(ABCMeta): if sys.version_info >= (3, 12): def __init__(cls, *args: Any, **kwargs: Any) -> None: ... @@ -358,11 +354,10 @@ class SupportsBytes(Protocol, metaclass=ABCMeta): @abstractmethod def __bytes__(self) -> bytes: ... -if sys.version_info >= (3, 8): - @runtime_checkable - class SupportsIndex(Protocol, metaclass=ABCMeta): - @abstractmethod - def __index__(self) -> int: ... +@runtime_checkable +class SupportsIndex(Protocol, metaclass=ABCMeta): + @abstractmethod + def __index__(self) -> int: ... @runtime_checkable class SupportsAbs(Protocol[_T_co]): @@ -418,7 +413,7 @@ class Generator(Iterator[_YieldT_co], Generic[_YieldT_co, _SendT_contra, _Return @overload @abstractmethod def throw( - self, __typ: Type[BaseException], __val: BaseException | object = None, __tb: TracebackType | None = None + self, __typ: type[BaseException], __val: BaseException | object = None, __tb: TracebackType | None = None ) -> _YieldT_co: ... @overload @abstractmethod @@ -455,7 +450,7 @@ class Coroutine(Awaitable[_ReturnT_co], Generic[_YieldT_co, _SendT_contra, _Retu @overload @abstractmethod def throw( - self, __typ: Type[BaseException], __val: BaseException | object = None, __tb: TracebackType | None = None + self, __typ: type[BaseException], __val: BaseException | object = None, __tb: TracebackType | None = None ) -> _YieldT_co: ... @overload @abstractmethod @@ -491,7 +486,7 @@ class AsyncGenerator(AsyncIterator[_YieldT_co], Generic[_YieldT_co, _SendT_contr @overload @abstractmethod def athrow( - self, __typ: Type[BaseException], __val: BaseException | object = None, __tb: TracebackType | None = None + self, __typ: type[BaseException], __val: BaseException | object = None, __tb: TracebackType | None = None ) -> Awaitable[_YieldT_co]: ... @overload @abstractmethod @@ -602,9 +597,7 @@ class ItemsView(MappingView, AbstractSet[tuple[_KT_co, _VT_co]], Generic[_KT_co, def __rand__(self, other: Iterable[_T]) -> set[_T]: ... def __contains__(self, item: object) -> bool: ... def __iter__(self) -> Iterator[tuple[_KT_co, _VT_co]]: ... - if sys.version_info >= (3, 8): - def __reversed__(self) -> Iterator[tuple[_KT_co, _VT_co]]: ... - + def __reversed__(self) -> Iterator[tuple[_KT_co, _VT_co]]: ... def __or__(self, other: Iterable[_T]) -> set[tuple[_KT_co, _VT_co] | _T]: ... def __ror__(self, other: Iterable[_T]) -> set[tuple[_KT_co, _VT_co] | _T]: ... def __sub__(self, other: Iterable[Any]) -> set[tuple[_KT_co, _VT_co]]: ... @@ -618,9 +611,7 @@ class KeysView(MappingView, AbstractSet[_KT_co]): def __rand__(self, other: Iterable[_T]) -> set[_T]: ... def __contains__(self, key: object) -> bool: ... def __iter__(self) -> Iterator[_KT_co]: ... - if sys.version_info >= (3, 8): - def __reversed__(self) -> Iterator[_KT_co]: ... - + def __reversed__(self) -> Iterator[_KT_co]: ... def __or__(self, other: Iterable[_T]) -> set[_KT_co | _T]: ... def __ror__(self, other: Iterable[_T]) -> set[_KT_co | _T]: ... def __sub__(self, other: Iterable[Any]) -> set[_KT_co]: ... @@ -632,8 +623,7 @@ class ValuesView(MappingView, Collection[_VT_co]): def __init__(self, mapping: Mapping[Any, _VT_co]) -> None: ... # undocumented def __contains__(self, value: object) -> bool: ... def __iter__(self) -> Iterator[_VT_co]: ... - if sys.version_info >= (3, 8): - def __reversed__(self) -> Iterator[_VT_co]: ... + def __reversed__(self) -> Iterator[_VT_co]: ... class Mapping(Collection[_KT], Generic[_KT, _VT_co]): # TODO: We wish the key type could also be covariant, but that doesn't work, @@ -772,7 +762,7 @@ class IO(Iterator[AnyStr]): def __enter__(self) -> IO[AnyStr]: ... @abstractmethod def __exit__( - self, __type: Type[BaseException] | None, __value: BaseException | None, __traceback: TracebackType | None + self, __type: type[BaseException] | None, __value: BaseException | None, __traceback: TracebackType | None ) -> None: ... class BinaryIO(IO[bytes]): @@ -823,24 +813,25 @@ else: obj: _get_type_hints_obj_allowed_types, globalns: dict[str, Any] | None = None, localns: dict[str, Any] | None = None ) -> dict[str, Any]: ... -if sys.version_info >= (3, 8): - def get_args(tp: Any) -> tuple[Any, ...]: ... +def get_args(tp: Any) -> tuple[Any, ...]: ... - if sys.version_info >= (3, 10): - @overload - def get_origin(tp: ParamSpecArgs | ParamSpecKwargs) -> ParamSpec: ... - @overload - def get_origin(tp: UnionType) -> type[UnionType]: ... - if sys.version_info >= (3, 9): - @overload - def get_origin(tp: GenericAlias) -> type: ... - @overload - def get_origin(tp: Any) -> Any | None: ... - else: - def get_origin(tp: Any) -> Any | None: ... +if sys.version_info >= (3, 10): + @overload + def get_origin(tp: ParamSpecArgs | ParamSpecKwargs) -> ParamSpec: ... + @overload + def get_origin(tp: UnionType) -> type[UnionType]: ... + +if sys.version_info >= (3, 9): + @overload + def get_origin(tp: GenericAlias) -> type: ... + @overload + def get_origin(tp: Any) -> Any | None: ... + +else: + def get_origin(tp: Any) -> Any | None: ... @overload -def cast(typ: Type[_T], val: Any) -> _T: ... +def cast(typ: type[_T], val: Any) -> _T: ... @overload def cast(typ: str, val: Any) -> Any: ... @overload @@ -865,9 +856,7 @@ if sys.version_info >= (3, 11): # Type constructors class NamedTuple(tuple[Any, ...]): - if sys.version_info < (3, 8): - _field_types: ClassVar[collections.OrderedDict[str, type]] - elif sys.version_info < (3, 9): + if sys.version_info < (3, 9): _field_types: ClassVar[dict[str, type]] _field_defaults: ClassVar[dict[str, Any]] _fields: ClassVar[tuple[str, ...]] @@ -881,11 +870,7 @@ class NamedTuple(tuple[Any, ...]): def __init__(self, __typename: str, __fields: None = None, **kwargs: Any) -> None: ... @classmethod def _make(cls, iterable: Iterable[Any]) -> typing_extensions.Self: ... - if sys.version_info >= (3, 8): - def _asdict(self) -> dict[str, Any]: ... - else: - def _asdict(self) -> collections.OrderedDict[str, Any]: ... - + def _asdict(self) -> dict[str, Any]: ... def _replace(self, **kwargs: Any) -> typing_extensions.Self: ... # Internal mypy fallback type for all typed dicts (does not exist at runtime) @@ -923,7 +908,7 @@ class _TypedDict(Mapping[str, object], metaclass=ABCMeta): # supposedly incompatible definitions of __or__ and __ior__ def __ior__(self, __value: typing_extensions.Self) -> typing_extensions.Self: ... # type: ignore[misc] -@_final +@final class ForwardRef: __forward_arg__: str __forward_code__: CodeType @@ -958,7 +943,7 @@ def _type_repr(obj: object) -> str: ... if sys.version_info >= (3, 12): def override(__method: _F) -> _F: ... - @_final + @final class TypeAliasType: def __init__( self, name: str, value: Any, *, type_params: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] = () diff --git a/mypy/typeshed/stdlib/typing_extensions.pyi b/mypy/typeshed/stdlib/typing_extensions.pyi index 5c5b756f5256..ea5c7b21aa87 100644 --- a/mypy/typeshed/stdlib/typing_extensions.pyi +++ b/mypy/typeshed/stdlib/typing_extensions.pyi @@ -1,5 +1,4 @@ import abc -import collections import sys import typing from _collections_abc import dict_items, dict_keys, dict_values @@ -353,9 +352,7 @@ else: ) -> IdentityFunction: ... class NamedTuple(tuple[Any, ...]): - if sys.version_info < (3, 8): - _field_types: ClassVar[collections.OrderedDict[str, type]] - elif sys.version_info < (3, 9): + if sys.version_info < (3, 9): _field_types: ClassVar[dict[str, type]] _field_defaults: ClassVar[dict[str, Any]] _fields: ClassVar[tuple[str, ...]] @@ -366,11 +363,7 @@ else: def __init__(self, typename: str, fields: None = None, **kwargs: Any) -> None: ... @classmethod def _make(cls, iterable: Iterable[Any]) -> Self: ... - if sys.version_info >= (3, 8): - def _asdict(self) -> dict[str, Any]: ... - else: - def _asdict(self) -> collections.OrderedDict[str, Any]: ... - + def _asdict(self) -> dict[str, Any]: ... def _replace(self, **kwargs: Any) -> Self: ... class NewType: diff --git a/mypy/typeshed/stdlib/unicodedata.pyi b/mypy/typeshed/stdlib/unicodedata.pyi index 5a1f7fe6638d..35ab6d609a19 100644 --- a/mypy/typeshed/stdlib/unicodedata.pyi +++ b/mypy/typeshed/stdlib/unicodedata.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import ReadOnlyBuffer -from typing import Any, TypeVar, overload -from typing_extensions import Literal, TypeAlias, final +from typing import Any, Literal, TypeVar, final, overload +from typing_extensions import TypeAlias ucd_3_2_0: UCD unidata_version: str @@ -27,10 +27,7 @@ def digit(__chr: str, __default: _T) -> int | _T: ... _EastAsianWidth: TypeAlias = Literal["F", "H", "W", "Na", "A", "N"] def east_asian_width(__chr: str) -> _EastAsianWidth: ... - -if sys.version_info >= (3, 8): - def is_normalized(__form: str, __unistr: str) -> bool: ... - +def is_normalized(__form: str, __unistr: str) -> bool: ... def lookup(__name: str | ReadOnlyBuffer) -> str: ... def mirrored(__chr: str) -> int: ... @overload @@ -60,9 +57,7 @@ class UCD: @overload def digit(self, __chr: str, __default: _T) -> int | _T: ... def east_asian_width(self, __chr: str) -> _EastAsianWidth: ... - if sys.version_info >= (3, 8): - def is_normalized(self, __form: str, __unistr: str) -> bool: ... - + def is_normalized(self, __form: str, __unistr: str) -> bool: ... def lookup(self, __name: str | ReadOnlyBuffer) -> str: ... def mirrored(self, __chr: str) -> int: ... @overload diff --git a/mypy/typeshed/stdlib/unittest/__init__.pyi b/mypy/typeshed/stdlib/unittest/__init__.pyi index f96d6fb185c5..f2532ccf7fd8 100644 --- a/mypy/typeshed/stdlib/unittest/__init__.pyi +++ b/mypy/typeshed/stdlib/unittest/__init__.pyi @@ -1,9 +1,11 @@ import sys +from unittest.async_case import * from .case import ( FunctionTestCase as FunctionTestCase, SkipTest as SkipTest, TestCase as TestCase, + addModuleCleanup as addModuleCleanup, expectedFailure as expectedFailure, skip as skip, skipIf as skipIf, @@ -27,15 +29,11 @@ from .signals import ( ) from .suite import BaseTestSuite as BaseTestSuite, TestSuite as TestSuite -if sys.version_info >= (3, 8): - from unittest.async_case import * - - from .case import addModuleCleanup as addModuleCleanup - if sys.version_info >= (3, 11): from .case import doModuleCleanups as doModuleCleanups, enterModuleContext as enterModuleContext __all__ = [ + "IsolatedAsyncioTestCase", "TestResult", "TestCase", "TestSuite", @@ -57,11 +55,9 @@ __all__ = [ "getTestCaseNames", "makeSuite", "findTestCases", + "addModuleCleanup", ] -if sys.version_info >= (3, 8): - __all__ += ["addModuleCleanup", "IsolatedAsyncioTestCase"] - if sys.version_info >= (3, 11): __all__ += ["enterModuleContext", "doModuleCleanups"] diff --git a/mypy/typeshed/stdlib/unittest/case.pyi b/mypy/typeshed/stdlib/unittest/case.pyi index d66f027324f1..120bb96d761b 100644 --- a/mypy/typeshed/stdlib/unittest/case.pyi +++ b/mypy/typeshed/stdlib/unittest/case.pyi @@ -68,9 +68,8 @@ else: self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None ) -> bool | None: ... -if sys.version_info >= (3, 8): - def addModuleCleanup(__function: Callable[_P, object], *args: _P.args, **kwargs: _P.kwargs) -> None: ... - def doModuleCleanups() -> None: ... +def addModuleCleanup(__function: Callable[_P, object], *args: _P.args, **kwargs: _P.kwargs) -> None: ... +def doModuleCleanups() -> None: ... if sys.version_info >= (3, 11): def enterModuleContext(cm: AbstractContextManager[_T]) -> _T: ... @@ -274,20 +273,16 @@ class TestCase: def defaultTestResult(self) -> unittest.result.TestResult: ... def id(self) -> str: ... def shortDescription(self) -> str | None: ... - if sys.version_info >= (3, 8): - def addCleanup(self, __function: Callable[_P, object], *args: _P.args, **kwargs: _P.kwargs) -> None: ... - else: - def addCleanup(self, function: Callable[_P, object], *args: _P.args, **kwargs: _P.kwargs) -> None: ... + def addCleanup(self, __function: Callable[_P, object], *args: _P.args, **kwargs: _P.kwargs) -> None: ... if sys.version_info >= (3, 11): def enterContext(self, cm: AbstractContextManager[_T]) -> _T: ... def doCleanups(self) -> None: ... - if sys.version_info >= (3, 8): - @classmethod - def addClassCleanup(cls, __function: Callable[_P, object], *args: _P.args, **kwargs: _P.kwargs) -> None: ... - @classmethod - def doClassCleanups(cls) -> None: ... + @classmethod + def addClassCleanup(cls, __function: Callable[_P, object], *args: _P.args, **kwargs: _P.kwargs) -> None: ... + @classmethod + def doClassCleanups(cls) -> None: ... if sys.version_info >= (3, 11): @classmethod diff --git a/mypy/typeshed/stdlib/unittest/mock.pyi b/mypy/typeshed/stdlib/unittest/mock.pyi index 8e96b23ce959..c6014d4bb886 100644 --- a/mypy/typeshed/stdlib/unittest/mock.pyi +++ b/mypy/typeshed/stdlib/unittest/mock.pyi @@ -2,8 +2,8 @@ import sys from collections.abc import Awaitable, Callable, Coroutine, Iterable, Mapping, Sequence from contextlib import _GeneratorContextManager from types import TracebackType -from typing import Any, Generic, TypeVar, overload -from typing_extensions import Final, Literal, ParamSpec, Self, TypeAlias +from typing import Any, Final, Generic, Literal, TypeVar, overload +from typing_extensions import ParamSpec, Self, TypeAlias _T = TypeVar("_T") _TT = TypeVar("_TT", bound=type[Any]) @@ -12,41 +12,23 @@ _F = TypeVar("_F", bound=Callable[..., Any]) _AF = TypeVar("_AF", bound=Callable[..., Coroutine[Any, Any, Any]]) _P = ParamSpec("_P") -if sys.version_info >= (3, 8): - __all__ = ( - "Mock", - "MagicMock", - "patch", - "sentinel", - "DEFAULT", - "ANY", - "call", - "create_autospec", - "AsyncMock", - "FILTER_DIR", - "NonCallableMock", - "NonCallableMagicMock", - "mock_open", - "PropertyMock", - "seal", - ) -else: - __all__ = ( - "Mock", - "MagicMock", - "patch", - "sentinel", - "DEFAULT", - "ANY", - "call", - "create_autospec", - "FILTER_DIR", - "NonCallableMock", - "NonCallableMagicMock", - "mock_open", - "PropertyMock", - "seal", - ) +__all__ = ( + "Mock", + "MagicMock", + "patch", + "sentinel", + "DEFAULT", + "ANY", + "call", + "create_autospec", + "AsyncMock", + "FILTER_DIR", + "NonCallableMock", + "NonCallableMagicMock", + "mock_open", + "PropertyMock", + "seal", +) if sys.version_info < (3, 9): __version__: Final[str] @@ -87,12 +69,10 @@ class _Call(tuple[Any, ...]): def __call__(self, *args: Any, **kwargs: Any) -> _Call: ... def __getattr__(self, attr: str) -> Any: ... def __getattribute__(self, attr: str) -> Any: ... - if sys.version_info >= (3, 8): - @property - def args(self) -> tuple[Any, ...]: ... - @property - def kwargs(self) -> Mapping[str, Any]: ... - + @property + def args(self) -> tuple[Any, ...]: ... + @property + def kwargs(self) -> Mapping[str, Any]: ... def call_list(self) -> Any: ... call: _Call @@ -144,24 +124,13 @@ class NonCallableMock(Base, Any): def __delattr__(self, name: str) -> None: ... def __setattr__(self, name: str, value: Any) -> None: ... def __dir__(self) -> list[str]: ... - if sys.version_info >= (3, 8): - def _calls_repr(self, prefix: str = "Calls") -> str: ... - def assert_called_with(self, *args: Any, **kwargs: Any) -> None: ... - def assert_not_called(self) -> None: ... - def assert_called_once_with(self, *args: Any, **kwargs: Any) -> None: ... - def _format_mock_failure_message(self, args: Any, kwargs: Any, action: str = "call") -> str: ... - else: - def assert_called_with(_mock_self, *args: Any, **kwargs: Any) -> None: ... - def assert_not_called(_mock_self) -> None: ... - def assert_called_once_with(_mock_self, *args: Any, **kwargs: Any) -> None: ... - def _format_mock_failure_message(self, args: Any, kwargs: Any) -> str: ... - if sys.version_info >= (3, 8): - def assert_called(self) -> None: ... - def assert_called_once(self) -> None: ... - else: - def assert_called(_mock_self) -> None: ... - def assert_called_once(_mock_self) -> None: ... - + def _calls_repr(self, prefix: str = "Calls") -> str: ... + def assert_called_with(self, *args: Any, **kwargs: Any) -> None: ... + def assert_not_called(self) -> None: ... + def assert_called_once_with(self, *args: Any, **kwargs: Any) -> None: ... + def _format_mock_failure_message(self, args: Any, kwargs: Any, action: str = "call") -> str: ... + def assert_called(self) -> None: ... + def assert_called_once(self) -> None: ... def reset_mock(self, visited: Any = None, *, return_value: bool = False, side_effect: bool = False) -> None: ... def _extract_mock_name(self) -> str: ... def _get_call_signature_from_name(self, name: str) -> Any: ... @@ -198,10 +167,7 @@ class CallableMixin(Base): _new_parent: Any | None = None, **kwargs: Any, ) -> None: ... - if sys.version_info >= (3, 8): - def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - else: - def __call__(_mock_self, *args: Any, **kwargs: Any) -> Any: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... class Mock(CallableMixin, NonCallableMock): ... @@ -256,16 +222,12 @@ class _patch(Generic[_T]): # arguments. See the _patch_default_new class below for this functionality. @overload def __call__(self, func: Callable[_P, _R]) -> Callable[_P, _R]: ... - if sys.version_info >= (3, 8): - def decoration_helper( - self, patched: _patch[Any], args: Sequence[Any], keywargs: Any - ) -> _GeneratorContextManager[tuple[Sequence[Any], Any]]: ... - + def decoration_helper( + self, patched: _patch[Any], args: Sequence[Any], keywargs: Any + ) -> _GeneratorContextManager[tuple[Sequence[Any], Any]]: ... def decorate_class(self, klass: _TT) -> _TT: ... def decorate_callable(self, func: Callable[..., _R]) -> Callable[..., _R]: ... - if sys.version_info >= (3, 8): - def decorate_async_callable(self, func: Callable[..., Awaitable[_R]]) -> Callable[..., Awaitable[_R]]: ... - + def decorate_async_callable(self, func: Callable[..., Awaitable[_R]]) -> Callable[..., Awaitable[_R]]: ... def get_original(self) -> tuple[Any, bool]: ... target: Any temp_original: Any @@ -277,15 +239,10 @@ class _patch(Generic[_T]): def start(self) -> _T: ... def stop(self) -> None: ... -if sys.version_info >= (3, 8): - _Mock: TypeAlias = MagicMock | AsyncMock -else: - _Mock: TypeAlias = MagicMock - # This class does not exist at runtime, it's a hack to make this work: # @patch("foo") # def bar(..., mock: MagicMock) -> None: ... -class _patch_default_new(_patch[_Mock]): +class _patch_default_new(_patch[MagicMock | AsyncMock]): @overload def __call__(self, func: _TT) -> _TT: ... # Can't use the following as ParamSpec is only allowed as last parameter: @@ -366,7 +323,7 @@ class _patcher: autospec: Any | None = ..., new_callable: Any | None = ..., **kwargs: Any, - ) -> _patch[_Mock]: ... + ) -> _patch[MagicMock | AsyncMock]: ... @staticmethod def multiple( target: Any, @@ -388,38 +345,34 @@ class MagicMixin: class NonCallableMagicMock(MagicMixin, NonCallableMock): ... class MagicMock(MagicMixin, Mock): ... -if sys.version_info >= (3, 8): - class AsyncMockMixin(Base): - def __init__(self, *args: Any, **kwargs: Any) -> None: ... - async def _execute_mock_call(self, *args: Any, **kwargs: Any) -> Any: ... - def assert_awaited(self) -> None: ... - def assert_awaited_once(self) -> None: ... - def assert_awaited_with(self, *args: Any, **kwargs: Any) -> None: ... - def assert_awaited_once_with(self, *args: Any, **kwargs: Any) -> None: ... - def assert_any_await(self, *args: Any, **kwargs: Any) -> None: ... - def assert_has_awaits(self, calls: Iterable[_Call], any_order: bool = False) -> None: ... - def assert_not_awaited(self) -> None: ... - def reset_mock(self, *args: Any, **kwargs: Any) -> None: ... - await_count: int - await_args: _Call | None - await_args_list: _CallList - - class AsyncMagicMixin(MagicMixin): - def __init__(self, *args: Any, **kw: Any) -> None: ... - - class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock): - # Improving the `reset_mock` signature. - # It is defined on `AsyncMockMixin` with `*args, **kwargs`, which is not ideal. - # But, `NonCallableMock` super-class has the better version. - def reset_mock(self, visited: Any = None, *, return_value: bool = False, side_effect: bool = False) -> None: ... +class AsyncMockMixin(Base): + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + async def _execute_mock_call(self, *args: Any, **kwargs: Any) -> Any: ... + def assert_awaited(self) -> None: ... + def assert_awaited_once(self) -> None: ... + def assert_awaited_with(self, *args: Any, **kwargs: Any) -> None: ... + def assert_awaited_once_with(self, *args: Any, **kwargs: Any) -> None: ... + def assert_any_await(self, *args: Any, **kwargs: Any) -> None: ... + def assert_has_awaits(self, calls: Iterable[_Call], any_order: bool = False) -> None: ... + def assert_not_awaited(self) -> None: ... + def reset_mock(self, *args: Any, **kwargs: Any) -> None: ... + await_count: int + await_args: _Call | None + await_args_list: _CallList + +class AsyncMagicMixin(MagicMixin): + def __init__(self, *args: Any, **kw: Any) -> None: ... + +class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock): + # Improving the `reset_mock` signature. + # It is defined on `AsyncMockMixin` with `*args, **kwargs`, which is not ideal. + # But, `NonCallableMock` super-class has the better version. + def reset_mock(self, visited: Any = None, *, return_value: bool = False, side_effect: bool = False) -> None: ... class MagicProxy: name: str parent: Any def __init__(self, name: str, parent: Any) -> None: ... - if sys.version_info < (3, 8): - def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - def create_mock(self) -> Any: ... def __get__(self, obj: Any, _type: Any | None = None) -> Any: ... @@ -471,11 +424,7 @@ class _SpecState: def mock_open(mock: Any | None = None, read_data: Any = "") -> Any: ... class PropertyMock(Mock): - if sys.version_info >= (3, 8): - def __get__(self, obj: _T, obj_type: type[_T] | None = None) -> Self: ... - else: - def __get__(self, obj: _T, obj_type: type[_T] | None) -> Self: ... - + def __get__(self, obj: _T, obj_type: type[_T] | None = None) -> Self: ... def __set__(self, obj: Any, val: Any) -> None: ... def seal(mock: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/urllib/parse.pyi b/mypy/typeshed/stdlib/urllib/parse.pyi index 116754091d1a..ed1929b26501 100644 --- a/mypy/typeshed/stdlib/urllib/parse.pyi +++ b/mypy/typeshed/stdlib/urllib/parse.pyi @@ -1,7 +1,7 @@ import sys from collections.abc import Callable, Iterable, Mapping, Sequence -from typing import Any, AnyStr, Generic, NamedTuple, TypeVar, overload -from typing_extensions import Literal, TypeAlias +from typing import Any, AnyStr, Generic, Literal, NamedTuple, TypeVar, overload +from typing_extensions import TypeAlias if sys.version_info >= (3, 9): from types import GenericAlias diff --git a/mypy/typeshed/stdlib/urllib/robotparser.pyi b/mypy/typeshed/stdlib/urllib/robotparser.pyi index d218c3dc6c0f..14ceef550dab 100644 --- a/mypy/typeshed/stdlib/urllib/robotparser.pyi +++ b/mypy/typeshed/stdlib/urllib/robotparser.pyi @@ -1,4 +1,3 @@ -import sys from collections.abc import Iterable from typing import NamedTuple @@ -18,5 +17,4 @@ class RobotFileParser: def modified(self) -> None: ... def crawl_delay(self, useragent: str) -> str | None: ... def request_rate(self, useragent: str) -> RequestRate | None: ... - if sys.version_info >= (3, 8): - def site_maps(self) -> list[str] | None: ... + def site_maps(self) -> list[str] | None: ... diff --git a/mypy/typeshed/stdlib/warnings.pyi b/mypy/typeshed/stdlib/warnings.pyi index 6222eb65918a..12afea9337e7 100644 --- a/mypy/typeshed/stdlib/warnings.pyi +++ b/mypy/typeshed/stdlib/warnings.pyi @@ -2,8 +2,8 @@ import sys from _warnings import warn as warn, warn_explicit as warn_explicit from collections.abc import Sequence from types import ModuleType, TracebackType -from typing import Any, Generic, TextIO, TypeVar, overload -from typing_extensions import Literal, TypeAlias +from typing import Any, Generic, Literal, TextIO, TypeVar, overload +from typing_extensions import TypeAlias __all__ = [ "warn", diff --git a/mypy/typeshed/stdlib/wave.pyi b/mypy/typeshed/stdlib/wave.pyi index 6b7af2f79da1..9137f1e47643 100644 --- a/mypy/typeshed/stdlib/wave.pyi +++ b/mypy/typeshed/stdlib/wave.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import ReadableBuffer, Unused -from typing import IO, Any, BinaryIO, NamedTuple, NoReturn, overload -from typing_extensions import Literal, Self, TypeAlias, deprecated +from typing import IO, Any, BinaryIO, Literal, NamedTuple, NoReturn, overload +from typing_extensions import Self, TypeAlias, deprecated if sys.version_info >= (3, 9): __all__ = ["open", "Error", "Wave_read", "Wave_write"] diff --git a/mypy/typeshed/stdlib/webbrowser.pyi b/mypy/typeshed/stdlib/webbrowser.pyi index 99c7bb5846b6..2b3f978c814b 100644 --- a/mypy/typeshed/stdlib/webbrowser.pyi +++ b/mypy/typeshed/stdlib/webbrowser.pyi @@ -1,7 +1,7 @@ import sys from abc import abstractmethod from collections.abc import Callable, Sequence -from typing_extensions import Literal +from typing import Literal __all__ = ["Error", "open", "open_new", "open_new_tab", "get", "register"] diff --git a/mypy/typeshed/stdlib/winreg.pyi b/mypy/typeshed/stdlib/winreg.pyi index 613b239ff663..897177547c71 100644 --- a/mypy/typeshed/stdlib/winreg.pyi +++ b/mypy/typeshed/stdlib/winreg.pyi @@ -1,7 +1,7 @@ import sys from types import TracebackType -from typing import Any -from typing_extensions import Literal, Self, TypeAlias, final +from typing import Any, Literal, final +from typing_extensions import Self, TypeAlias if sys.platform == "win32": _KeyType: TypeAlias = HKEYType | int diff --git a/mypy/typeshed/stdlib/winsound.pyi b/mypy/typeshed/stdlib/winsound.pyi index aa04fdc27a01..bacc5302826f 100644 --- a/mypy/typeshed/stdlib/winsound.pyi +++ b/mypy/typeshed/stdlib/winsound.pyi @@ -1,7 +1,6 @@ import sys from _typeshed import ReadableBuffer -from typing import overload -from typing_extensions import Literal +from typing import Literal, overload if sys.platform == "win32": SND_APPLICATION: Literal[128] diff --git a/mypy/typeshed/stdlib/xml/dom/minicompat.pyi b/mypy/typeshed/stdlib/xml/dom/minicompat.pyi index 4d83bef025d9..162f60254a58 100644 --- a/mypy/typeshed/stdlib/xml/dom/minicompat.pyi +++ b/mypy/typeshed/stdlib/xml/dom/minicompat.pyi @@ -1,6 +1,5 @@ from collections.abc import Iterable -from typing import Any, TypeVar -from typing_extensions import Literal +from typing import Any, Literal, TypeVar __all__ = ["NodeList", "EmptyNodeList", "StringTypes", "defproperty"] diff --git a/mypy/typeshed/stdlib/xml/dom/minidom.pyi b/mypy/typeshed/stdlib/xml/dom/minidom.pyi index ec17f0a41497..28bfa1b36924 100644 --- a/mypy/typeshed/stdlib/xml/dom/minidom.pyi +++ b/mypy/typeshed/stdlib/xml/dom/minidom.pyi @@ -1,8 +1,8 @@ import sys import xml.dom from _typeshed import Incomplete, ReadableBuffer, SupportsRead, SupportsWrite -from typing import NoReturn, TypeVar, overload -from typing_extensions import Literal, Self +from typing import Literal, NoReturn, TypeVar, overload +from typing_extensions import Self from xml.dom.minicompat import NodeList from xml.dom.xmlbuilder import DocumentLS, DOMImplementationLS from xml.sax.xmlreader import XMLReader diff --git a/mypy/typeshed/stdlib/xml/dom/pulldom.pyi b/mypy/typeshed/stdlib/xml/dom/pulldom.pyi index 920905160e43..95436ab5dd38 100644 --- a/mypy/typeshed/stdlib/xml/dom/pulldom.pyi +++ b/mypy/typeshed/stdlib/xml/dom/pulldom.pyi @@ -1,7 +1,8 @@ import sys from _typeshed import Incomplete, SupportsRead from collections.abc import Sequence -from typing_extensions import Literal, TypeAlias +from typing import Literal +from typing_extensions import TypeAlias from xml.dom.minidom import Document, DOMImplementation, Element, Text from xml.sax.handler import ContentHandler from xml.sax.xmlreader import XMLReader diff --git a/mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi b/mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi index c07e4ba2465e..480dd7ce732c 100644 --- a/mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi +++ b/mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi @@ -1,6 +1,6 @@ from _typeshed import Incomplete, Unused -from typing import Any, NoReturn -from typing_extensions import Literal, TypeAlias +from typing import Any, Literal, NoReturn +from typing_extensions import TypeAlias from urllib.request import OpenerDirector from xml.dom.expatbuilder import ExpatBuilder, ExpatBuilderNS from xml.dom.minidom import Node diff --git a/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi b/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi index b08ca88e7e97..c508f72892c1 100644 --- a/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi +++ b/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi @@ -2,14 +2,16 @@ import sys from _collections_abc import dict_keys from _typeshed import FileDescriptorOrPath, ReadableBuffer, SupportsRead, SupportsWrite from collections.abc import Callable, Generator, ItemsView, Iterable, Iterator, Mapping, Sequence -from typing import Any, TypeVar, overload -from typing_extensions import Literal, SupportsIndex, TypeAlias, TypeGuard +from typing import Any, Literal, SupportsIndex, TypeVar, overload +from typing_extensions import TypeAlias, TypeGuard __all__ = [ + "C14NWriterTarget", "Comment", "dump", "Element", "ElementTree", + "canonicalize", "fromstring", "fromstringlist", "iselement", @@ -31,9 +33,6 @@ __all__ = [ "register_namespace", ] -if sys.version_info >= (3, 8): - __all__ += ["C14NWriterTarget", "canonicalize"] - if sys.version_info >= (3, 9): __all__ += ["indent"] @@ -50,36 +49,34 @@ class ParseError(SyntaxError): # In reality it works based on `.tag` attribute duck typing. def iselement(element: object) -> TypeGuard[Element]: ... - -if sys.version_info >= (3, 8): - @overload - def canonicalize( - xml_data: str | ReadableBuffer | None = None, - *, - out: None = None, - from_file: _FileRead | None = None, - with_comments: bool = False, - strip_text: bool = False, - rewrite_prefixes: bool = False, - qname_aware_tags: Iterable[str] | None = None, - qname_aware_attrs: Iterable[str] | None = None, - exclude_attrs: Iterable[str] | None = None, - exclude_tags: Iterable[str] | None = None, - ) -> str: ... - @overload - def canonicalize( - xml_data: str | ReadableBuffer | None = None, - *, - out: SupportsWrite[str], - from_file: _FileRead | None = None, - with_comments: bool = False, - strip_text: bool = False, - rewrite_prefixes: bool = False, - qname_aware_tags: Iterable[str] | None = None, - qname_aware_attrs: Iterable[str] | None = None, - exclude_attrs: Iterable[str] | None = None, - exclude_tags: Iterable[str] | None = None, - ) -> None: ... +@overload +def canonicalize( + xml_data: str | ReadableBuffer | None = None, + *, + out: None = None, + from_file: _FileRead | None = None, + with_comments: bool = False, + strip_text: bool = False, + rewrite_prefixes: bool = False, + qname_aware_tags: Iterable[str] | None = None, + qname_aware_attrs: Iterable[str] | None = None, + exclude_attrs: Iterable[str] | None = None, + exclude_tags: Iterable[str] | None = None, +) -> str: ... +@overload +def canonicalize( + xml_data: str | ReadableBuffer | None = None, + *, + out: SupportsWrite[str], + from_file: _FileRead | None = None, + with_comments: bool = False, + strip_text: bool = False, + rewrite_prefixes: bool = False, + qname_aware_tags: Iterable[str] | None = None, + qname_aware_attrs: Iterable[str] | None = None, + exclude_attrs: Iterable[str] | None = None, + exclude_tags: Iterable[str] | None = None, +) -> None: ... class Element: tag: str @@ -172,93 +169,66 @@ class ElementTree: def write_c14n(self, file: _FileWriteC14N) -> None: ... def register_namespace(prefix: str, uri: str) -> None: ... - -if sys.version_info >= (3, 8): - @overload - def tostring( - element: Element, - encoding: None = None, - method: str | None = None, - *, - xml_declaration: bool | None = None, - default_namespace: str | None = None, - short_empty_elements: bool = True, - ) -> bytes: ... - @overload - def tostring( - element: Element, - encoding: Literal["unicode"], - method: str | None = None, - *, - xml_declaration: bool | None = None, - default_namespace: str | None = None, - short_empty_elements: bool = True, - ) -> str: ... - @overload - def tostring( - element: Element, - encoding: str, - method: str | None = None, - *, - xml_declaration: bool | None = None, - default_namespace: str | None = None, - short_empty_elements: bool = True, - ) -> Any: ... - @overload - def tostringlist( - element: Element, - encoding: None = None, - method: str | None = None, - *, - xml_declaration: bool | None = None, - default_namespace: str | None = None, - short_empty_elements: bool = True, - ) -> list[bytes]: ... - @overload - def tostringlist( - element: Element, - encoding: Literal["unicode"], - method: str | None = None, - *, - xml_declaration: bool | None = None, - default_namespace: str | None = None, - short_empty_elements: bool = True, - ) -> list[str]: ... - @overload - def tostringlist( - element: Element, - encoding: str, - method: str | None = None, - *, - xml_declaration: bool | None = None, - default_namespace: str | None = None, - short_empty_elements: bool = True, - ) -> list[Any]: ... - -else: - @overload - def tostring( - element: Element, encoding: None = None, method: str | None = None, *, short_empty_elements: bool = True - ) -> bytes: ... - @overload - def tostring( - element: Element, encoding: Literal["unicode"], method: str | None = None, *, short_empty_elements: bool = True - ) -> str: ... - @overload - def tostring(element: Element, encoding: str, method: str | None = None, *, short_empty_elements: bool = True) -> Any: ... - @overload - def tostringlist( - element: Element, encoding: None = None, method: str | None = None, *, short_empty_elements: bool = True - ) -> list[bytes]: ... - @overload - def tostringlist( - element: Element, encoding: Literal["unicode"], method: str | None = None, *, short_empty_elements: bool = True - ) -> list[str]: ... - @overload - def tostringlist( - element: Element, encoding: str, method: str | None = None, *, short_empty_elements: bool = True - ) -> list[Any]: ... - +@overload +def tostring( + element: Element, + encoding: None = None, + method: str | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, +) -> bytes: ... +@overload +def tostring( + element: Element, + encoding: Literal["unicode"], + method: str | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, +) -> str: ... +@overload +def tostring( + element: Element, + encoding: str, + method: str | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, +) -> Any: ... +@overload +def tostringlist( + element: Element, + encoding: None = None, + method: str | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, +) -> list[bytes]: ... +@overload +def tostringlist( + element: Element, + encoding: Literal["unicode"], + method: str | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, +) -> list[str]: ... +@overload +def tostringlist( + element: Element, + encoding: str, + method: str | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, +) -> list[Any]: ... def dump(elem: Element) -> None: ... if sys.version_info >= (3, 9): @@ -297,21 +267,18 @@ def fromstringlist(sequence: Sequence[str | ReadableBuffer], parser: XMLParser | _ElementFactory: TypeAlias = Callable[[Any, dict[Any, Any]], Element] class TreeBuilder: - if sys.version_info >= (3, 8): - # comment_factory can take None because passing None to Comment is not an error - def __init__( - self, - element_factory: _ElementFactory | None = ..., - *, - comment_factory: Callable[[str | None], Element] | None = ..., - pi_factory: Callable[[str, str | None], Element] | None = ..., - insert_comments: bool = ..., - insert_pis: bool = ..., - ) -> None: ... - insert_comments: bool - insert_pis: bool - else: - def __init__(self, element_factory: _ElementFactory | None = ...) -> None: ... + # comment_factory can take None because passing None to Comment is not an error + def __init__( + self, + element_factory: _ElementFactory | None = ..., + *, + comment_factory: Callable[[str | None], Element] | None = ..., + pi_factory: Callable[[str, str | None], Element] | None = ..., + insert_comments: bool = ..., + insert_pis: bool = ..., + ) -> None: ... + insert_comments: bool + insert_pis: bool def close(self) -> Element: ... def data(self, __data: str) -> None: ... @@ -319,31 +286,29 @@ class TreeBuilder: # depending on what the particular factory supports. def start(self, __tag: Any, __attrs: dict[Any, Any]) -> Element: ... def end(self, __tag: str) -> Element: ... - if sys.version_info >= (3, 8): - # These two methods have pos-only parameters in the C implementation - def comment(self, __text: str | None) -> Element: ... - def pi(self, __target: str, __text: str | None = None) -> Element: ... + # These two methods have pos-only parameters in the C implementation + def comment(self, __text: str | None) -> Element: ... + def pi(self, __target: str, __text: str | None = None) -> Element: ... -if sys.version_info >= (3, 8): - class C14NWriterTarget: - def __init__( - self, - write: Callable[[str], object], - *, - with_comments: bool = False, - strip_text: bool = False, - rewrite_prefixes: bool = False, - qname_aware_tags: Iterable[str] | None = None, - qname_aware_attrs: Iterable[str] | None = None, - exclude_attrs: Iterable[str] | None = None, - exclude_tags: Iterable[str] | None = None, - ) -> None: ... - def data(self, data: str) -> None: ... - def start_ns(self, prefix: str, uri: str) -> None: ... - def start(self, tag: str, attrs: Mapping[str, str]) -> None: ... - def end(self, tag: str) -> None: ... - def comment(self, text: str) -> None: ... - def pi(self, target: str, data: str) -> None: ... +class C14NWriterTarget: + def __init__( + self, + write: Callable[[str], object], + *, + with_comments: bool = False, + strip_text: bool = False, + rewrite_prefixes: bool = False, + qname_aware_tags: Iterable[str] | None = None, + qname_aware_attrs: Iterable[str] | None = None, + exclude_attrs: Iterable[str] | None = None, + exclude_tags: Iterable[str] | None = None, + ) -> None: ... + def data(self, data: str) -> None: ... + def start_ns(self, prefix: str, uri: str) -> None: ... + def start(self, tag: str, attrs: Mapping[str, str]) -> None: ... + def end(self, tag: str) -> None: ... + def comment(self, text: str) -> None: ... + def pi(self, target: str, data: str) -> None: ... class XMLParser: parser: Any @@ -351,11 +316,6 @@ class XMLParser: # TODO-what is entity used for??? entity: Any version: str - if sys.version_info >= (3, 8): - def __init__(self, *, target: Any = ..., encoding: str | None = ...) -> None: ... - else: - def __init__(self, html: int = ..., target: Any = ..., encoding: str | None = ...) -> None: ... - def doctype(self, __name: str, __pubid: str, __system: str) -> None: ... - + def __init__(self, *, target: Any = ..., encoding: str | None = ...) -> None: ... def close(self) -> Any: ... def feed(self, __data: str | ReadableBuffer) -> None: ... diff --git a/mypy/typeshed/stdlib/xml/sax/__init__.pyi b/mypy/typeshed/stdlib/xml/sax/__init__.pyi index d2d6f12d474a..a2eecc5a7864 100644 --- a/mypy/typeshed/stdlib/xml/sax/__init__.pyi +++ b/mypy/typeshed/stdlib/xml/sax/__init__.pyi @@ -1,4 +1,3 @@ -import sys from _typeshed import ReadableBuffer, StrPath, SupportsRead, _T_co from collections.abc import Iterable from typing import Protocol @@ -16,21 +15,11 @@ from xml.sax.xmlreader import XMLReader class _SupportsReadClose(SupportsRead[_T_co], Protocol[_T_co]): def close(self) -> None: ... -if sys.version_info >= (3, 8): - _Source: TypeAlias = StrPath | _SupportsReadClose[bytes] | _SupportsReadClose[str] -else: - _Source: TypeAlias = str | _SupportsReadClose[bytes] | _SupportsReadClose[str] +_Source: TypeAlias = StrPath | _SupportsReadClose[bytes] | _SupportsReadClose[str] default_parser_list: list[str] -if sys.version_info >= (3, 8): - - def make_parser(parser_list: Iterable[str] = ()) -> XMLReader: ... - -else: - - def make_parser(parser_list: list[str] = []) -> XMLReader: ... - +def make_parser(parser_list: Iterable[str] = ()) -> XMLReader: ... def parse(source: _Source, handler: ContentHandler, errorHandler: ErrorHandler = ...) -> None: ... def parseString(string: ReadableBuffer | str, handler: ContentHandler, errorHandler: ErrorHandler | None = ...) -> None: ... def _create_parser(parser_name: str) -> XMLReader: ... diff --git a/mypy/typeshed/stdlib/xmlrpc/client.pyi b/mypy/typeshed/stdlib/xmlrpc/client.pyi index 79969359f091..2be5f7df2d7d 100644 --- a/mypy/typeshed/stdlib/xmlrpc/client.pyi +++ b/mypy/typeshed/stdlib/xmlrpc/client.pyi @@ -1,14 +1,13 @@ import gzip import http.client -import sys import time from _typeshed import ReadableBuffer, SizedBuffer, SupportsRead, SupportsWrite from collections.abc import Callable, Iterable, Mapping from datetime import datetime from io import BytesIO from types import TracebackType -from typing import Any, Protocol, overload -from typing_extensions import Literal, Self, TypeAlias +from typing import Any, Literal, Protocol, overload +from typing_extensions import Self, TypeAlias class _SupportsTimeTuple(Protocol): def timetuple(self) -> time.struct_time: ... @@ -228,13 +227,9 @@ class Transport: _headers: list[tuple[str, str]] _extra_headers: list[tuple[str, str]] - if sys.version_info >= (3, 8): - def __init__( - self, use_datetime: bool = False, use_builtin_types: bool = False, *, headers: Iterable[tuple[str, str]] = () - ) -> None: ... - else: - def __init__(self, use_datetime: bool = False, use_builtin_types: bool = False) -> None: ... - + def __init__( + self, use_datetime: bool = False, use_builtin_types: bool = False, *, headers: Iterable[tuple[str, str]] = () + ) -> None: ... def request( self, host: _HostType, handler: str, request_body: SizedBuffer, verbose: bool = False ) -> tuple[_Marshallable, ...]: ... @@ -253,20 +248,14 @@ class Transport: def parse_response(self, response: http.client.HTTPResponse) -> tuple[_Marshallable, ...]: ... class SafeTransport(Transport): - if sys.version_info >= (3, 8): - def __init__( - self, - use_datetime: bool = False, - use_builtin_types: bool = False, - *, - headers: Iterable[tuple[str, str]] = (), - context: Any | None = None, - ) -> None: ... - else: - def __init__( - self, use_datetime: bool = False, use_builtin_types: bool = False, *, context: Any | None = None - ) -> None: ... - + def __init__( + self, + use_datetime: bool = False, + use_builtin_types: bool = False, + *, + headers: Iterable[tuple[str, str]] = (), + context: Any | None = None, + ) -> None: ... def make_connection(self, host: _HostType) -> http.client.HTTPSConnection: ... class ServerProxy: @@ -277,34 +266,19 @@ class ServerProxy: __verbose: bool __allow_none: bool - if sys.version_info >= (3, 8): - def __init__( - self, - uri: str, - transport: Transport | None = None, - encoding: str | None = None, - verbose: bool = False, - allow_none: bool = False, - use_datetime: bool = False, - use_builtin_types: bool = False, - *, - headers: Iterable[tuple[str, str]] = (), - context: Any | None = None, - ) -> None: ... - else: - def __init__( - self, - uri: str, - transport: Transport | None = None, - encoding: str | None = None, - verbose: bool = False, - allow_none: bool = False, - use_datetime: bool = False, - use_builtin_types: bool = False, - *, - context: Any | None = None, - ) -> None: ... - + def __init__( + self, + uri: str, + transport: Transport | None = None, + encoding: str | None = None, + verbose: bool = False, + allow_none: bool = False, + use_datetime: bool = False, + use_builtin_types: bool = False, + *, + headers: Iterable[tuple[str, str]] = (), + context: Any | None = None, + ) -> None: ... def __getattr__(self, name: str) -> _Method: ... @overload def __call__(self, attr: Literal["close"]) -> Callable[[], None]: ... diff --git a/mypy/typeshed/stdlib/xxlimited.pyi b/mypy/typeshed/stdlib/xxlimited.pyi index 7fc39138fec5..3e6e78de3f70 100644 --- a/mypy/typeshed/stdlib/xxlimited.pyi +++ b/mypy/typeshed/stdlib/xxlimited.pyi @@ -1,6 +1,5 @@ import sys -from typing import Any -from typing_extensions import final +from typing import Any, final class Str(str): ... diff --git a/mypy/typeshed/stdlib/zipfile/__init__.pyi b/mypy/typeshed/stdlib/zipfile/__init__.pyi index 83982be3be08..be0cdf12a4a9 100644 --- a/mypy/typeshed/stdlib/zipfile/__init__.pyi +++ b/mypy/typeshed/stdlib/zipfile/__init__.pyi @@ -5,12 +5,13 @@ from collections.abc import Callable, Iterable, Iterator from io import TextIOWrapper from os import PathLike from types import TracebackType -from typing import IO, Protocol, overload -from typing_extensions import Literal, Self, TypeAlias +from typing import IO, Literal, Protocol, overload +from typing_extensions import Self, TypeAlias __all__ = [ "BadZipFile", "BadZipfile", + "Path", "error", "ZIP_STORED", "ZIP_DEFLATED", @@ -23,15 +24,13 @@ __all__ = [ "LargeZipFile", ] -if sys.version_info >= (3, 8): - __all__ += ["Path"] - -# TODO: use TypeAlias when mypy bugs are fixed +# TODO: use TypeAlias for these two when mypy bugs are fixed # https://github.com/python/mypy/issues/16581 _DateTuple = tuple[int, int, int, int, int, int] # noqa: Y026 +_ZipFileMode = Literal["r", "w", "x", "a"] # noqa: Y026 + _ReadWriteMode: TypeAlias = Literal["r", "w"] _ReadWriteBinaryMode: TypeAlias = Literal["r", "w", "rb", "wb"] -_ZipFileMode: TypeAlias = Literal["r", "w", "x", "a"] class BadZipFile(Exception): ... @@ -132,7 +131,7 @@ class ZipFile: strict_timestamps: bool = True, metadata_encoding: None = None, ) -> None: ... - elif sys.version_info >= (3, 8): + else: def __init__( self, file: StrPath | IO[bytes], @@ -143,15 +142,6 @@ class ZipFile: *, strict_timestamps: bool = True, ) -> None: ... - else: - def __init__( - self, - file: StrPath | IO[bytes], - mode: _ZipFileMode = "r", - compression: int = 0, - allowZip64: bool = True, - compresslevel: int | None = None, - ) -> None: ... def __enter__(self) -> Self: ... def __exit__( @@ -217,20 +207,15 @@ class ZipInfo: file_size: int orig_filename: str # undocumented def __init__(self, filename: str = "NoName", date_time: _DateTuple = (1980, 1, 1, 0, 0, 0)) -> None: ... - if sys.version_info >= (3, 8): - @classmethod - def from_file(cls, filename: StrPath, arcname: StrPath | None = None, *, strict_timestamps: bool = True) -> Self: ... - else: - @classmethod - def from_file(cls, filename: StrPath, arcname: StrPath | None = None) -> Self: ... - + @classmethod + def from_file(cls, filename: StrPath, arcname: StrPath | None = None, *, strict_timestamps: bool = True) -> Self: ... def is_dir(self) -> bool: ... def FileHeader(self, zip64: bool | None = None) -> bytes: ... if sys.version_info >= (3, 12): from zipfile._path import CompleteDirs as CompleteDirs, Path as Path -elif sys.version_info >= (3, 8): +else: class CompleteDirs(ZipFile): def resolve_dir(self, name: str) -> str: ... @overload diff --git a/mypy/typeshed/stdlib/zipfile/_path.pyi b/mypy/typeshed/stdlib/zipfile/_path.pyi index 3cf034aec8f4..0398824e1fd2 100644 --- a/mypy/typeshed/stdlib/zipfile/_path.pyi +++ b/mypy/typeshed/stdlib/zipfile/_path.pyi @@ -3,8 +3,8 @@ from _typeshed import StrPath from collections.abc import Iterator, Sequence from io import TextIOWrapper from os import PathLike -from typing import IO, overload -from typing_extensions import Literal, Self, TypeAlias +from typing import IO, Literal, overload +from typing_extensions import Self, TypeAlias from zipfile import ZipFile _ReadWriteBinaryMode: TypeAlias = Literal["r", "w", "rb", "wb"] diff --git a/mypy/typeshed/stdlib/zipimport.pyi b/mypy/typeshed/stdlib/zipimport.pyi index 0189bfe712b5..158d573cac74 100644 --- a/mypy/typeshed/stdlib/zipimport.pyi +++ b/mypy/typeshed/stdlib/zipimport.pyi @@ -4,8 +4,7 @@ from importlib.abc import ResourceReader from importlib.machinery import ModuleSpec from types import CodeType, ModuleType -if sys.version_info >= (3, 8): - __all__ = ["ZipImportError", "zipimporter"] +__all__ = ["ZipImportError", "zipimporter"] class ZipImportError(ImportError): ... diff --git a/mypy/typeshed/stdlib/zlib.pyi b/mypy/typeshed/stdlib/zlib.pyi index c3419af0de3f..efeb5a88a76f 100644 --- a/mypy/typeshed/stdlib/zlib.pyi +++ b/mypy/typeshed/stdlib/zlib.pyi @@ -1,6 +1,6 @@ import sys from _typeshed import ReadableBuffer -from typing_extensions import Literal +from typing import Literal DEFLATED: Literal[8] DEF_MEM_LEVEL: int # can change From 92c7745ee1b4dd5355966d40c7c7118d4b65aabb Mon Sep 17 00:00:00 2001 From: Shantanu <12621235+hauntsaninja@users.noreply.github.com> Date: Mon, 26 Sep 2022 12:55:07 -0700 Subject: [PATCH 2/7] Remove use of LiteralString in builtins (#13743) --- mypy/typeshed/stdlib/builtins.pyi | 89 +------------------------------ 1 file changed, 1 insertion(+), 88 deletions(-) diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index b8c807dd388d..53087cc551fe 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -61,7 +61,6 @@ from typing import ( # noqa: Y022 from typing_extensions import ( # noqa: Y023 Concatenate, Literal, - LiteralString, ParamSpec, Self, TypeAlias, @@ -435,17 +434,8 @@ class str(Sequence[str]): def __new__(cls, object: object = ...) -> Self: ... @overload def __new__(cls, object: ReadableBuffer, encoding: str = ..., errors: str = ...) -> Self: ... - @overload - def capitalize(self: LiteralString) -> LiteralString: ... - @overload def capitalize(self) -> str: ... # type: ignore[misc] - @overload - def casefold(self: LiteralString) -> LiteralString: ... - @overload def casefold(self) -> str: ... # type: ignore[misc] - @overload - def center(self: LiteralString, __width: SupportsIndex, __fillchar: LiteralString = " ") -> LiteralString: ... - @overload def center(self, __width: SupportsIndex, __fillchar: str = " ") -> str: ... # type: ignore[misc] def count(self, x: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... def encode(self, encoding: str = "utf-8", errors: str = "strict") -> bytes: ... @@ -453,13 +443,10 @@ class str(Sequence[str]): self, __suffix: str | tuple[str, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> bool: ... @overload - def expandtabs(self: LiteralString, tabsize: SupportsIndex = 8) -> LiteralString: ... + def expandtabs(self: str, tabsize: SupportsIndex = 8) -> str: ... @overload def expandtabs(self, tabsize: SupportsIndex = 8) -> str: ... # type: ignore[misc] def find(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... - @overload - def format(self: LiteralString, *args: LiteralString, **kwargs: LiteralString) -> LiteralString: ... - @overload def format(self, *args: object, **kwargs: object) -> str: ... def format_map(self, map: _FormatMapMapping) -> str: ... def index(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... @@ -475,91 +462,32 @@ class str(Sequence[str]): def isspace(self) -> bool: ... def istitle(self) -> bool: ... def isupper(self) -> bool: ... - @overload - def join(self: LiteralString, __iterable: Iterable[LiteralString]) -> LiteralString: ... - @overload def join(self, __iterable: Iterable[str]) -> str: ... # type: ignore[misc] - @overload - def ljust(self: LiteralString, __width: SupportsIndex, __fillchar: LiteralString = " ") -> LiteralString: ... - @overload def ljust(self, __width: SupportsIndex, __fillchar: str = " ") -> str: ... # type: ignore[misc] - @overload - def lower(self: LiteralString) -> LiteralString: ... - @overload def lower(self) -> str: ... # type: ignore[misc] - @overload - def lstrip(self: LiteralString, __chars: LiteralString | None = None) -> LiteralString: ... - @overload def lstrip(self, __chars: str | None = None) -> str: ... # type: ignore[misc] - @overload - def partition(self: LiteralString, __sep: LiteralString) -> tuple[LiteralString, LiteralString, LiteralString]: ... - @overload def partition(self, __sep: str) -> tuple[str, str, str]: ... # type: ignore[misc] - @overload - def replace( - self: LiteralString, __old: LiteralString, __new: LiteralString, __count: SupportsIndex = -1 - ) -> LiteralString: ... - @overload def replace(self, __old: str, __new: str, __count: SupportsIndex = -1) -> str: ... # type: ignore[misc] if sys.version_info >= (3, 9): - @overload - def removeprefix(self: LiteralString, __prefix: LiteralString) -> LiteralString: ... - @overload def removeprefix(self, __prefix: str) -> str: ... # type: ignore[misc] - @overload - def removesuffix(self: LiteralString, __suffix: LiteralString) -> LiteralString: ... - @overload def removesuffix(self, __suffix: str) -> str: ... # type: ignore[misc] def rfind(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... def rindex(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... - @overload - def rjust(self: LiteralString, __width: SupportsIndex, __fillchar: LiteralString = " ") -> LiteralString: ... - @overload def rjust(self, __width: SupportsIndex, __fillchar: str = " ") -> str: ... # type: ignore[misc] - @overload - def rpartition(self: LiteralString, __sep: LiteralString) -> tuple[LiteralString, LiteralString, LiteralString]: ... - @overload def rpartition(self, __sep: str) -> tuple[str, str, str]: ... # type: ignore[misc] - @overload - def rsplit(self: LiteralString, sep: LiteralString | None = None, maxsplit: SupportsIndex = -1) -> list[LiteralString]: ... - @overload def rsplit(self, sep: str | None = None, maxsplit: SupportsIndex = -1) -> list[str]: ... # type: ignore[misc] - @overload - def rstrip(self: LiteralString, __chars: LiteralString | None = None) -> LiteralString: ... - @overload def rstrip(self, __chars: str | None = None) -> str: ... # type: ignore[misc] - @overload - def split(self: LiteralString, sep: LiteralString | None = None, maxsplit: SupportsIndex = -1) -> list[LiteralString]: ... - @overload def split(self, sep: str | None = None, maxsplit: SupportsIndex = -1) -> list[str]: ... # type: ignore[misc] - @overload - def splitlines(self: LiteralString, keepends: bool = False) -> list[LiteralString]: ... - @overload def splitlines(self, keepends: bool = False) -> list[str]: ... # type: ignore[misc] def startswith( self, __prefix: str | tuple[str, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> bool: ... - @overload - def strip(self: LiteralString, __chars: LiteralString | None = None) -> LiteralString: ... - @overload def strip(self, __chars: str | None = None) -> str: ... # type: ignore[misc] - @overload - def swapcase(self: LiteralString) -> LiteralString: ... - @overload def swapcase(self) -> str: ... # type: ignore[misc] - @overload - def title(self: LiteralString) -> LiteralString: ... - @overload def title(self) -> str: ... # type: ignore[misc] def translate(self, __table: _TranslateTable) -> str: ... - @overload - def upper(self: LiteralString) -> LiteralString: ... - @overload def upper(self) -> str: ... # type: ignore[misc] - @overload - def zfill(self: LiteralString, __width: SupportsIndex) -> LiteralString: ... - @overload def zfill(self, __width: SupportsIndex) -> str: ... # type: ignore[misc] @staticmethod @overload @@ -570,9 +498,6 @@ class str(Sequence[str]): @staticmethod @overload def maketrans(__x: str, __y: str, __z: str) -> dict[int, int | None]: ... - @overload - def __add__(self: LiteralString, __value: LiteralString) -> LiteralString: ... - @overload def __add__(self, __value: str) -> str: ... # type: ignore[misc] # Incompatible with Sequence.__contains__ def __contains__(self, __key: str) -> bool: ... # type: ignore[override] @@ -581,25 +506,13 @@ class str(Sequence[str]): def __getitem__(self, __key: SupportsIndex | slice) -> str: ... def __gt__(self, __value: str) -> bool: ... def __hash__(self) -> int: ... - @overload - def __iter__(self: LiteralString) -> Iterator[LiteralString]: ... - @overload def __iter__(self) -> Iterator[str]: ... # type: ignore[misc] def __le__(self, __value: str) -> bool: ... def __len__(self) -> int: ... def __lt__(self, __value: str) -> bool: ... - @overload - def __mod__(self: LiteralString, __value: LiteralString | tuple[LiteralString, ...]) -> LiteralString: ... - @overload def __mod__(self, __value: Any) -> str: ... - @overload - def __mul__(self: LiteralString, __value: SupportsIndex) -> LiteralString: ... - @overload def __mul__(self, __value: SupportsIndex) -> str: ... # type: ignore[misc] def __ne__(self, __value: object) -> bool: ... - @overload - def __rmul__(self: LiteralString, __value: SupportsIndex) -> LiteralString: ... - @overload def __rmul__(self, __value: SupportsIndex) -> str: ... # type: ignore[misc] def __getnewargs__(self) -> tuple[str]: ... From 725610b813f56d7bfb28c656f2cb9ed77a0b9773 Mon Sep 17 00:00:00 2001 From: Shantanu <12621235+hauntsaninja@users.noreply.github.com> Date: Sat, 29 Oct 2022 12:47:21 -0700 Subject: [PATCH 3/7] Revert sum literal integer change (#13961) This is allegedly causing large performance problems, see 13821 typeshed/8231 had zero hits on mypy_primer, so it's not the worst thing to undo. Patching this in typeshed also feels weird, since there's a more general soundness issue. If a typevar has a bound or constraint, we might not want to solve it to a Literal. If we can confirm the performance regression or fix the unsoundness within mypy, I might pursue upstreaming this in typeshed. (Reminder: add this to the sync_typeshed script once merged) --- mypy/typeshed/stdlib/builtins.pyi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index 53087cc551fe..1ae1ba03e1ad 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -1593,7 +1593,7 @@ _SupportsSumNoDefaultT = TypeVar("_SupportsSumNoDefaultT", bound=_SupportsSumWit # without creating many false-positive errors (see #7578). # Instead, we special-case the most common examples of this: bool and literal integers. @overload -def sum(__iterable: Iterable[bool | _LiteralInteger], start: int = 0) -> int: ... # type: ignore[overload-overlap] +def sum(__iterable: Iterable[bool], start: int = 0) -> int: ... # type: ignore[overload-overlap] @overload def sum(__iterable: Iterable[_SupportsSumNoDefaultT]) -> _SupportsSumNoDefaultT | Literal[0]: ... @overload From d7275ef702a964516244f8172aa870d9ccfceb9d Mon Sep 17 00:00:00 2001 From: AlexWaygood Date: Mon, 1 May 2023 20:34:55 +0100 Subject: [PATCH 4/7] Revert typeshed ctypes change Since the plugin provides superior type checking: https://github.com/python/mypy/pull/13987#issuecomment-1310863427 A manual cherry-pick of e437cdf. --- mypy/typeshed/stdlib/_ctypes.pyi | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/mypy/typeshed/stdlib/_ctypes.pyi b/mypy/typeshed/stdlib/_ctypes.pyi index 36540172ab95..ec3d86e41687 100644 --- a/mypy/typeshed/stdlib/_ctypes.pyi +++ b/mypy/typeshed/stdlib/_ctypes.pyi @@ -167,11 +167,7 @@ class Array(_CData, Generic[_CT]): def _type_(self) -> type[_CT]: ... @_type_.setter def _type_(self, value: type[_CT]) -> None: ... - # Note: only available if _CT == c_char - @property - def raw(self) -> bytes: ... - @raw.setter - def raw(self, value: ReadableBuffer) -> None: ... + raw: bytes # Note: only available if _CT == c_char value: Any # Note: bytes if _CT == c_char, str if _CT == c_wchar, unavailable otherwise # TODO These methods cannot be annotated correctly at the moment. # All of these "Any"s stand for the array's element type, but it's not possible to use _CT From 57c88b011f8a5ece604fa35e2b6ce3194bfad89c Mon Sep 17 00:00:00 2001 From: AlexWaygood Date: Sat, 4 Mar 2023 13:14:11 +0000 Subject: [PATCH 5/7] Revert use of `ParamSpec` for `functools.wraps` --- mypy/typeshed/stdlib/functools.pyi | 40 +++++++++++------------------- 1 file changed, 14 insertions(+), 26 deletions(-) diff --git a/mypy/typeshed/stdlib/functools.pyi b/mypy/typeshed/stdlib/functools.pyi index 8c48e77c16cf..0f1666024f84 100644 --- a/mypy/typeshed/stdlib/functools.pyi +++ b/mypy/typeshed/stdlib/functools.pyi @@ -1,9 +1,9 @@ import sys import types -from _typeshed import SupportsAllComparisons, SupportsItems +from _typeshed import IdentityFunction, SupportsAllComparisons, SupportsItems from collections.abc import Callable, Hashable, Iterable, Sequence, Sized from typing import Any, Generic, Literal, NamedTuple, TypedDict, TypeVar, final, overload -from typing_extensions import ParamSpec, Self, TypeAlias +from typing_extensions import Self, TypeAlias if sys.version_info >= (3, 9): from types import GenericAlias @@ -27,12 +27,10 @@ __all__ = [ if sys.version_info >= (3, 9): __all__ += ["cache"] +_AnyCallable: TypeAlias = Callable[..., object] + _T = TypeVar("_T") _S = TypeVar("_S") -_PWrapped = ParamSpec("_PWrapped") -_RWrapped = TypeVar("_RWrapped") -_PWrapper = ParamSpec("_PWrapper") -_RWrapper = TypeVar("_RWrapper") @overload def reduce(__function: Callable[[_T, _S], _T], __sequence: Iterable[_S], __initial: _T) -> _T: ... @@ -82,41 +80,31 @@ else: ] WRAPPER_UPDATES: tuple[Literal["__dict__"]] -class _Wrapped(Generic[_PWrapped, _RWrapped, _PWrapper, _RWrapper]): - __wrapped__: Callable[_PWrapped, _RWrapped] - def __call__(self, *args: _PWrapper.args, **kwargs: _PWrapper.kwargs) -> _RWrapper: ... - # as with ``Callable``, we'll assume that these attributes exist - __name__: str - __qualname__: str - -class _Wrapper(Generic[_PWrapped, _RWrapped]): - def __call__(self, f: Callable[_PWrapper, _RWrapper]) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWrapper]: ... - if sys.version_info >= (3, 12): def update_wrapper( - wrapper: Callable[_PWrapper, _RWrapper], - wrapped: Callable[_PWrapped, _RWrapped], + wrapper: _T, + wrapped: _AnyCallable, assigned: Sequence[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotations__", "__type_params__"), updated: Sequence[str] = ("__dict__",), - ) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWrapper]: ... + ) -> _T: ... def wraps( - wrapped: Callable[_PWrapped, _RWrapped], + wrapped: _AnyCallable, assigned: Sequence[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotations__", "__type_params__"), updated: Sequence[str] = ("__dict__",), - ) -> _Wrapper[_PWrapped, _RWrapped]: ... + ) -> IdentityFunction: ... else: def update_wrapper( - wrapper: Callable[_PWrapper, _RWrapper], - wrapped: Callable[_PWrapped, _RWrapped], + wrapper: _T, + wrapped: _AnyCallable, assigned: Sequence[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotations__"), updated: Sequence[str] = ("__dict__",), - ) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWrapper]: ... + ) -> _T: ... def wraps( - wrapped: Callable[_PWrapped, _RWrapped], + wrapped: _AnyCallable, assigned: Sequence[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotations__"), updated: Sequence[str] = ("__dict__",), - ) -> _Wrapper[_PWrapped, _RWrapped]: ... + ) -> IdentityFunction: ... def total_ordering(cls: type[_T]) -> type[_T]: ... def cmp_to_key(mycmp: Callable[[_T, _T], int]) -> Callable[[_T], SupportsAllComparisons]: ... From bb72f54ada486c97e9aedcc298fa2b535d6e6a99 Mon Sep 17 00:00:00 2001 From: Jared Hance Date: Thu, 1 Feb 2024 08:56:34 -0800 Subject: [PATCH 6/7] Accomodate tests that target 3.7. --- test-data/unit/pythoneval.test | 26 -------------------------- 1 file changed, 26 deletions(-) diff --git a/test-data/unit/pythoneval.test b/test-data/unit/pythoneval.test index 9f6f5d3838a4..fdcea8e6521f 100644 --- a/test-data/unit/pythoneval.test +++ b/test-data/unit/pythoneval.test @@ -866,30 +866,6 @@ _program.py:10: error: Incompatible types in assignment (expression has type "in _program.py:20: error: Argument 1 to "tst" has incompatible type "defaultdict[str, List[Never]]"; expected "defaultdict[int, List[Never]]" _program.py:24: error: Invalid index type "str" for "MyDDict[Dict[Never, Never]]"; expected type "int" -[case testNoSubcriptionOfStdlibCollections] -# flags: --python-version 3.7 -import collections -from collections import Counter -from typing import TypeVar - -collections.defaultdict[int, str]() -Counter[int]() - -T = TypeVar('T') -DDint = collections.defaultdict[T, int] - -d = DDint[str]() -d[0] = 1 - -def f(d: collections.defaultdict[int, str]) -> None: - ... -[out] -_program.py:6: error: "defaultdict" is not subscriptable -_program.py:7: error: "Counter" is not subscriptable -_program.py:10: error: "defaultdict" is not subscriptable -_program.py:13: error: Invalid index type "int" for "defaultdict[str, int]"; expected type "str" -_program.py:15: error: "defaultdict" is not subscriptable, use "typing.DefaultDict" instead - [case testCollectionsAliases] import typing as t import collections as c @@ -1590,7 +1566,6 @@ _testNoPython3StubAvailable.py:3: note: (or run "mypy --install-types" to instal [case testTypingOrderedDictAlias] -# flags: --python-version 3.7 from typing import OrderedDict x: OrderedDict[str, int] = OrderedDict({}) reveal_type(x) @@ -1711,7 +1686,6 @@ _testTypeAliasWithNewStyleUnion.py:25: note: Revealed type is "Union[Type[builti _testTypeAliasWithNewStyleUnion.py:28: note: Revealed type is "Union[Type[builtins.int], builtins.str]" [case testTypeAliasWithNewStyleUnionInStub] -# flags: --python-version 3.7 import m a: m.A reveal_type(a) From 2b69966d549313028613419ac10e9edbf40de3d6 Mon Sep 17 00:00:00 2001 From: Jared Hance Date: Thu, 1 Feb 2024 09:18:11 -0800 Subject: [PATCH 7/7] Update line numbers. --- test-data/unit/pythoneval.test | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/test-data/unit/pythoneval.test b/test-data/unit/pythoneval.test index fdcea8e6521f..b51a965c95da 100644 --- a/test-data/unit/pythoneval.test +++ b/test-data/unit/pythoneval.test @@ -1570,7 +1570,7 @@ from typing import OrderedDict x: OrderedDict[str, int] = OrderedDict({}) reveal_type(x) [out] -_testTypingOrderedDictAlias.py:4: note: Revealed type is "collections.OrderedDict[builtins.str, builtins.int]" +_testTypingOrderedDictAlias.py:3: note: Revealed type is "collections.OrderedDict[builtins.str, builtins.int]" [case testTypingExtensionsOrderedDictAlias] from typing_extensions import OrderedDict @@ -1736,12 +1736,12 @@ CU4: TypeAlias = int | Callable[[str | bool], str] [out] m.pyi:5: note: Revealed type is "typing._SpecialForm" m.pyi:22: note: Revealed type is "typing._SpecialForm" -_testTypeAliasWithNewStyleUnionInStub.py:4: note: Revealed type is "Union[Type[builtins.int], builtins.str]" -_testTypeAliasWithNewStyleUnionInStub.py:6: note: Revealed type is "Union[Type[builtins.int], builtins.str]" -_testTypeAliasWithNewStyleUnionInStub.py:8: note: Revealed type is "Union[Type[builtins.int], builtins.str]" -_testTypeAliasWithNewStyleUnionInStub.py:10: note: Revealed type is "Union[Type[builtins.int], builtins.str]" -_testTypeAliasWithNewStyleUnionInStub.py:12: note: Revealed type is "Union[builtins.str, Type[builtins.int]]" -_testTypeAliasWithNewStyleUnionInStub.py:14: note: Revealed type is "Union[builtins.str, Type[builtins.int]]" +_testTypeAliasWithNewStyleUnionInStub.py:3: note: Revealed type is "Union[Type[builtins.int], builtins.str]" +_testTypeAliasWithNewStyleUnionInStub.py:5: note: Revealed type is "Union[Type[builtins.int], builtins.str]" +_testTypeAliasWithNewStyleUnionInStub.py:7: note: Revealed type is "Union[Type[builtins.int], builtins.str]" +_testTypeAliasWithNewStyleUnionInStub.py:9: note: Revealed type is "Union[Type[builtins.int], builtins.str]" +_testTypeAliasWithNewStyleUnionInStub.py:11: note: Revealed type is "Union[builtins.str, Type[builtins.int]]" +_testTypeAliasWithNewStyleUnionInStub.py:13: note: Revealed type is "Union[builtins.str, Type[builtins.int]]" [case testEnumNameWorkCorrectlyOn311] # flags: --python-version 3.11