diff --git a/mypy/typeshed/stdlib/@python2/__builtin__.pyi b/mypy/typeshed/stdlib/@python2/__builtin__.pyi index b7b68bbb7844..0b2c89e8d80c 100644 --- a/mypy/typeshed/stdlib/@python2/__builtin__.pyi +++ b/mypy/typeshed/stdlib/@python2/__builtin__.pyi @@ -863,9 +863,14 @@ def filter(__function: Callable[[_T], Any], __iterable: Iterable[_T]) -> List[_T def format(__value: object, __format_spec: str = ...) -> str: ... # TODO unicode @overload def getattr(__o: Any, name: Text) -> Any: ... + +# While technically covered by the last overload, spelling out the types for None and bool +# help mypy out in some tricky situations involving type context (aka bidirectional inference) @overload def getattr(__o: Any, name: Text, __default: None) -> Optional[Any]: ... @overload +def getattr(__o: Any, name: Text, __default: bool) -> Union[Any, bool]: ... +@overload def getattr(__o: Any, name: Text, __default: _T) -> Union[Any, _T]: ... def globals() -> Dict[str, Any]: ... def hasattr(__obj: Any, __name: Text) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/_io.pyi b/mypy/typeshed/stdlib/@python2/_io.pyi index 4eafef332985..2d825b07bb85 100644 --- a/mypy/typeshed/stdlib/@python2/_io.pyi +++ b/mypy/typeshed/stdlib/@python2/_io.pyi @@ -1,3 +1,4 @@ +from _typeshed import Self from mmap import mmap from typing import IO, Any, BinaryIO, Iterable, List, Optional, Text, TextIO, Tuple, Type, TypeVar, Union @@ -30,7 +31,7 @@ class _IOBase(BinaryIO): def tell(self) -> int: ... def truncate(self, size: Optional[int] = ...) -> int: ... def writable(self) -> bool: ... - def __enter__(self: _T) -> _T: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, t: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[Any] ) -> Optional[bool]: ... @@ -56,7 +57,7 @@ class _BufferedIOBase(_IOBase): class BufferedRWPair(_BufferedIOBase): def __init__(self, reader: _RawIOBase, writer: _RawIOBase, buffer_size: int = ..., max_buffer_size: int = ...) -> None: ... def peek(self, n: int = ...) -> bytes: ... - def __enter__(self) -> BufferedRWPair: ... + def __enter__(self: Self) -> Self: ... class BufferedRandom(_BufferedIOBase): mode: str @@ -140,7 +141,7 @@ class _TextIOBase(TextIO): def writable(self) -> bool: ... def write(self, pbuf: unicode) -> int: ... def writelines(self, lines: Iterable[unicode]) -> None: ... - def __enter__(self: _T) -> _T: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, t: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[Any] ) -> Optional[bool]: ... diff --git a/mypy/typeshed/stdlib/@python2/_typeshed/__init__.pyi b/mypy/typeshed/stdlib/@python2/_typeshed/__init__.pyi index 9548a2497943..ca698e29ae8a 100644 --- a/mypy/typeshed/stdlib/@python2/_typeshed/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/_typeshed/__init__.pyi @@ -26,6 +26,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: ... +Self = TypeVar("Self") # noqa Y001 + class IdentityFunction(Protocol): def __call__(self, __x: _T) -> _T: ... diff --git a/mypy/typeshed/stdlib/@python2/abc.pyi b/mypy/typeshed/stdlib/@python2/abc.pyi index 0bf046a4d877..ac14246d44a5 100644 --- a/mypy/typeshed/stdlib/@python2/abc.pyi +++ b/mypy/typeshed/stdlib/@python2/abc.pyi @@ -1,4 +1,5 @@ import _weakrefset +from _typeshed import SupportsWrite from typing import Any, Callable, Dict, Set, Tuple, Type, TypeVar _FuncT = TypeVar("_FuncT", bound=Callable[..., Any]) @@ -8,17 +9,16 @@ _FuncT = TypeVar("_FuncT", bound=Callable[..., Any]) def abstractmethod(funcobj: _FuncT) -> _FuncT: ... class ABCMeta(type): - # TODO: FrozenSet - __abstractmethods__: Set[Any] + __abstractmethods__: frozenset[str] _abc_cache: _weakrefset.WeakSet[Any] _abc_invalidation_counter: int _abc_negative_cache: _weakrefset.WeakSet[Any] _abc_negative_cache_version: int _abc_registry: _weakrefset.WeakSet[Any] - def __init__(self, name: str, bases: Tuple[type, ...], namespace: Dict[Any, Any]) -> None: ... + def __init__(self, name: str, bases: Tuple[type, ...], namespace: Dict[str, Any]) -> None: ... def __instancecheck__(cls: ABCMeta, instance: Any) -> Any: ... def __subclasscheck__(cls: ABCMeta, subclass: Any) -> Any: ... - def _dump_registry(cls: ABCMeta, *args: Any, **kwargs: Any) -> None: ... + def _dump_registry(cls: ABCMeta, file: SupportsWrite[Any] | None = ...) -> None: ... def register(cls: ABCMeta, subclass: Type[Any]) -> None: ... # TODO: The real abc.abstractproperty inherits from "property". diff --git a/mypy/typeshed/stdlib/@python2/builtins.pyi b/mypy/typeshed/stdlib/@python2/builtins.pyi index b7b68bbb7844..0b2c89e8d80c 100644 --- a/mypy/typeshed/stdlib/@python2/builtins.pyi +++ b/mypy/typeshed/stdlib/@python2/builtins.pyi @@ -863,9 +863,14 @@ def filter(__function: Callable[[_T], Any], __iterable: Iterable[_T]) -> List[_T def format(__value: object, __format_spec: str = ...) -> str: ... # TODO unicode @overload def getattr(__o: Any, name: Text) -> Any: ... + +# While technically covered by the last overload, spelling out the types for None and bool +# help mypy out in some tricky situations involving type context (aka bidirectional inference) @overload def getattr(__o: Any, name: Text, __default: None) -> Optional[Any]: ... @overload +def getattr(__o: Any, name: Text, __default: bool) -> Union[Any, bool]: ... +@overload def getattr(__o: Any, name: Text, __default: _T) -> Union[Any, _T]: ... def globals() -> Dict[str, Any]: ... def hasattr(__obj: Any, __name: Text) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/mmap.pyi b/mypy/typeshed/stdlib/@python2/mmap.pyi index 1b8a0202fa76..750d0829cb8f 100644 --- a/mypy/typeshed/stdlib/@python2/mmap.pyi +++ b/mypy/typeshed/stdlib/@python2/mmap.pyi @@ -1,5 +1,5 @@ import sys -from typing import AnyStr, Generic, Optional, Sequence, Union +from typing import NoReturn, Optional, Sequence, Union ACCESS_DEFAULT: int ACCESS_READ: int @@ -23,7 +23,7 @@ if sys.platform != "win32": PAGESIZE: int -class _mmap(Generic[AnyStr]): +class mmap(Sequence[bytes]): if sys.platform == "win32": def __init__( self, fileno: int, length: int, tagname: Optional[str] = ..., access: int = ..., offset: int = ... @@ -35,21 +35,19 @@ class _mmap(Generic[AnyStr]): def close(self) -> None: ... def flush(self, offset: int = ..., size: int = ...) -> int: ... def move(self, dest: int, src: int, count: int) -> None: ... - def read_byte(self) -> AnyStr: ... - def readline(self) -> AnyStr: ... + def read_byte(self) -> bytes: ... + def readline(self) -> bytes: ... def resize(self, newsize: int) -> None: ... def seek(self, pos: int, whence: int = ...) -> None: ... def size(self) -> int: ... def tell(self) -> int: ... - def write_byte(self, byte: AnyStr) -> None: ... + def write_byte(self, byte: bytes) -> None: ... def __len__(self) -> int: ... - -class mmap(_mmap[bytes], Sequence[bytes]): def find(self, string: bytes, start: int = ..., end: int = ...) -> int: ... def rfind(self, string: bytes, start: int = ..., stop: int = ...) -> int: ... def read(self, num: int) -> bytes: ... def write(self, string: bytes) -> None: ... def __getitem__(self, index: Union[int, slice]) -> bytes: ... def __getslice__(self, i: Optional[int], j: Optional[int]) -> bytes: ... - def __delitem__(self, index: Union[int, slice]) -> None: ... + def __delitem__(self, index: Union[int, slice]) -> NoReturn: ... def __setitem__(self, index: Union[int, slice], object: bytes) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/sysconfig.pyi b/mypy/typeshed/stdlib/@python2/sysconfig.pyi index b8044bcaa615..c5f00ee9ea08 100644 --- a/mypy/typeshed/stdlib/@python2/sysconfig.pyi +++ b/mypy/typeshed/stdlib/@python2/sysconfig.pyi @@ -7,7 +7,7 @@ def get_config_vars() -> Dict[str, Any]: ... def get_config_vars(arg: str, *args: str) -> List[Any]: ... def get_scheme_names() -> Tuple[str, ...]: ... def get_path_names() -> Tuple[str, ...]: ... -def get_path(name: str, scheme: str = ..., vars: Optional[Dict[str, Any]] = ..., expand: bool = ...) -> Optional[str]: ... +def get_path(name: str, scheme: str = ..., vars: Optional[Dict[str, Any]] = ..., expand: bool = ...) -> str: ... def get_paths(scheme: str = ..., vars: Optional[Dict[str, Any]] = ..., expand: bool = ...) -> Dict[str, str]: ... def get_python_version() -> str: ... def get_platform() -> str: ... diff --git a/mypy/typeshed/stdlib/VERSIONS b/mypy/typeshed/stdlib/VERSIONS index 3f0f81947f07..3cb637f5be1e 100644 --- a/mypy/typeshed/stdlib/VERSIONS +++ b/mypy/typeshed/stdlib/VERSIONS @@ -23,7 +23,7 @@ _ast: 2.7- _bisect: 2.7- _bootlocale: 3.6-3.9 _codecs: 2.7- -_collections_abc: 3.6- +_collections_abc: 3.3- _compat_pickle: 3.6- _compression: 3.6- _csv: 2.7- @@ -43,6 +43,7 @@ _py_abc: 3.7- _pydecimal: 3.6- _random: 2.7- _sitebuiltins: 3.6- +_socket: 3.0- # present in 2.7 at runtime, but not in typeshed _stat: 3.6- _thread: 2.7- _threading_local: 3.6- @@ -82,6 +83,7 @@ code: 2.7- codecs: 2.7- codeop: 2.7- collections: 2.7- +collections.abc: 3.3- colorsys: 2.7- compileall: 2.7- concurrent: 3.2- @@ -135,6 +137,7 @@ imaplib: 2.7- imghdr: 2.7- imp: 2.7- importlib: 2.7- +importlib.metadata: 3.8- importlib.resources: 3.7- inspect: 2.7- io: 2.7- diff --git a/mypy/typeshed/stdlib/__future__.pyi b/mypy/typeshed/stdlib/__future__.pyi index a68183dbe23e..4658afa9f09e 100644 --- a/mypy/typeshed/stdlib/__future__.pyi +++ b/mypy/typeshed/stdlib/__future__.pyi @@ -21,3 +21,31 @@ if sys.version_info >= (3, 7): annotations: _Feature all_feature_names: List[str] # undocumented + +if sys.version_info >= (3, 7): + __all__ = [ + "all_feature_names", + "absolute_import", + "division", + "generators", + "nested_scopes", + "print_function", + "unicode_literals", + "with_statement", + "barry_as_FLUFL", + "generator_stop", + "annotations", + ] +else: + __all__ = [ + "all_feature_names", + "absolute_import", + "division", + "generators", + "nested_scopes", + "print_function", + "unicode_literals", + "with_statement", + "barry_as_FLUFL", + "generator_stop", + ] diff --git a/mypy/typeshed/stdlib/_ast.pyi b/mypy/typeshed/stdlib/_ast.pyi index 2d0d92d83032..eee5b55f01b0 100644 --- a/mypy/typeshed/stdlib/_ast.pyi +++ b/mypy/typeshed/stdlib/_ast.pyi @@ -1,6 +1,7 @@ import sys import typing from typing import Any, ClassVar, Optional +from typing_extensions import Literal PyCF_ONLY_AST: int if sys.version_info >= (3, 8): @@ -390,7 +391,7 @@ if sys.version_info >= (3, 10): class MatchValue(pattern): value: expr class MatchSingleton(pattern): - value: Optional[bool] + value: Literal[True, False, None] class MatchSequence(pattern): patterns: typing.List[pattern] class MatchStar(pattern): diff --git a/mypy/typeshed/stdlib/_curses.pyi b/mypy/typeshed/stdlib/_curses.pyi index db9b049a9392..b64fa66e08b5 100644 --- a/mypy/typeshed/stdlib/_curses.pyi +++ b/mypy/typeshed/stdlib/_curses.pyi @@ -89,6 +89,13 @@ BUTTON4_DOUBLE_CLICKED: int BUTTON4_PRESSED: int BUTTON4_RELEASED: int BUTTON4_TRIPLE_CLICKED: int +# Darwin ncurses doesn't provide BUTTON5_* constants +if sys.version_info >= (3, 10) and sys.platform != "darwin": + BUTTON5_PRESSED: int + BUTTON5_RELEASED: int + BUTTON5_CLICKED: int + BUTTON5_DOUBLE_CLICKED: int + BUTTON5_TRIPLE_CLICKED: int BUTTON_ALT: int BUTTON_CTRL: int BUTTON_SHIFT: int @@ -291,6 +298,10 @@ def getsyx() -> Tuple[int, int]: ... def getwin(__file: BinaryIO) -> _CursesWindow: ... def halfdelay(__tenths: int) -> None: ... def has_colors() -> bool: ... + +if sys.version_info >= (3, 10): + def has_extended_color_support() -> bool: ... + def has_ic() -> bool: ... def has_il() -> bool: ... def has_key(__key: int) -> bool: ... diff --git a/mypy/typeshed/stdlib/_socket.pyi b/mypy/typeshed/stdlib/_socket.pyi new file mode 100644 index 000000000000..109241870801 --- /dev/null +++ b/mypy/typeshed/stdlib/_socket.pyi @@ -0,0 +1,632 @@ +import sys +from _typeshed import ReadableBuffer, WriteableBuffer +from collections.abc import Iterable +from typing import Any, Optional, SupportsInt, Tuple, Union, overload + +if sys.version_info >= (3, 8): + from typing import SupportsIndex + + _FD = SupportsIndex +else: + _FD = SupportsInt + +_CMSG = Tuple[int, int, bytes] +_CMSGArg = Tuple[int, int, ReadableBuffer] + +# Addresses can be either tuples of varying lengths (AF_INET, AF_INET6, +# AF_NETLINK, AF_TIPC) or strings (AF_UNIX). +_Address = Union[Tuple[Any, ...], str] +_RetAddress = Any +# TODO Most methods allow bytes as address objects + +# ----- 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. + +has_ipv6: bool + +# Per socketmodule.c, only these three families are portable +AF_UNIX: int +AF_INET: int +AF_INET6: int + +SOCK_STREAM: int +SOCK_DGRAM: int +SOCK_RAW: int +SOCK_RDM: int +SOCK_SEQPACKET: int + +if sys.platform == "linux": + SOCK_CLOEXEC: int + SOCK_NONBLOCK: int + +# Address families not mentioned in the docs +AF_AAL5: int +AF_APPLETALK: int +AF_ASH: int +AF_ATMPVC: int +AF_ATMSVC: int +AF_AX25: int +AF_BRIDGE: int +AF_DECnet: int +AF_ECONET: int +AF_IPX: int +AF_IRDA: int +AF_KEY: int +AF_LLC: int +AF_NETBEUI: int +AF_NETROM: int +AF_PPPOX: int +AF_ROSE: int +AF_ROUTE: int +AF_SECURITY: int +AF_SNA: int +AF_SYSTEM: int +AF_UNSPEC: int +AF_WANPIPE: int +AF_X25: int + +# The "many constants" referenced by the docs +SOMAXCONN: int +AI_ADDRCONFIG: int +AI_ALL: int +AI_CANONNAME: int +AI_DEFAULT: int +AI_MASK: int +AI_NUMERICHOST: int +AI_NUMERICSERV: int +AI_PASSIVE: int +AI_V4MAPPED: int +AI_V4MAPPED_CFG: int +EAI_ADDRFAMILY: int +EAI_AGAIN: int +EAI_BADFLAGS: int +EAI_BADHINTS: int +EAI_FAIL: int +EAI_FAMILY: int +EAI_MAX: int +EAI_MEMORY: int +EAI_NODATA: int +EAI_NONAME: int +EAI_OVERFLOW: int +EAI_PROTOCOL: int +EAI_SERVICE: int +EAI_SOCKTYPE: int +EAI_SYSTEM: 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 +IPPROTO_AH: int +IPPROTO_BIP: int +IPPROTO_DSTOPTS: int +IPPROTO_EGP: int +IPPROTO_EON: int +IPPROTO_ESP: int +IPPROTO_FRAGMENT: int +IPPROTO_GGP: int +IPPROTO_GRE: int +IPPROTO_HELLO: int +IPPROTO_HOPOPTS: int +IPPROTO_ICMP: int +IPPROTO_ICMPV6: int +IPPROTO_IDP: int +IPPROTO_IGMP: int +IPPROTO_IP: int +IPPROTO_IPCOMP: int +IPPROTO_IPIP: int +IPPROTO_IPV4: int +IPPROTO_IPV6: int +IPPROTO_MAX: int +IPPROTO_MOBILE: int +IPPROTO_ND: int +IPPROTO_NONE: int +IPPROTO_PIM: int +IPPROTO_PUP: int +IPPROTO_RAW: int +IPPROTO_ROUTING: int +IPPROTO_RSVP: int +IPPROTO_SCTP: int +IPPROTO_TCP: int +IPPROTO_TP: int +IPPROTO_UDP: int +IPPROTO_VRRP: int +IPPROTO_XTP: int +IPV6_CHECKSUM: int +IPV6_DONTFRAG: int +IPV6_DSTOPTS: int +IPV6_HOPLIMIT: int +IPV6_HOPOPTS: int +IPV6_JOIN_GROUP: int +IPV6_LEAVE_GROUP: int +IPV6_MULTICAST_HOPS: int +IPV6_MULTICAST_IF: int +IPV6_MULTICAST_LOOP: int +IPV6_NEXTHOP: int +IPV6_PATHMTU: int +IPV6_PKTINFO: int +IPV6_RECVDSTOPTS: int +IPV6_RECVHOPLIMIT: int +IPV6_RECVHOPOPTS: int +IPV6_RECVPATHMTU: int +IPV6_RECVPKTINFO: int +IPV6_RECVRTHDR: int +IPV6_RECVTCLASS: int +IPV6_RTHDR: int +IPV6_RTHDRDSTOPTS: int +IPV6_RTHDR_TYPE_0: int +IPV6_TCLASS: int +IPV6_UNICAST_HOPS: int +IPV6_USE_MIN_MTU: int +IPV6_V6ONLY: int +IPX_TYPE: int +IP_ADD_MEMBERSHIP: int +IP_DEFAULT_MULTICAST_LOOP: int +IP_DEFAULT_MULTICAST_TTL: int +IP_DROP_MEMBERSHIP: int +IP_HDRINCL: int +IP_MAX_MEMBERSHIPS: int +IP_MULTICAST_IF: int +IP_MULTICAST_LOOP: int +IP_MULTICAST_TTL: int +IP_OPTIONS: int +IP_RECVDSTADDR: int +IP_RECVOPTS: int +IP_RECVRETOPTS: int +IP_RETOPTS: int +IP_TOS: int +IP_TRANSPARENT: int +IP_TTL: int +LOCAL_PEERCRED: int +MSG_BCAST: int +MSG_BTAG: int +MSG_CMSG_CLOEXEC: int +MSG_CONFIRM: int +MSG_CTRUNC: int +MSG_DONTROUTE: int +MSG_DONTWAIT: int +MSG_EOF: int +MSG_EOR: int +MSG_ERRQUEUE: int +MSG_ETAG: int +MSG_FASTOPEN: int +MSG_MCAST: int +MSG_MORE: int +MSG_NOSIGNAL: int +MSG_NOTIFICATION: 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 +SCM_CREDENTIALS: int +SCM_CREDS: int +SCM_RIGHTS: int +SHUT_RD: int +SHUT_RDWR: int +SHUT_WR: int +SOL_ATALK: int +SOL_AX25: int +SOL_HCI: int +SOL_IP: int +SOL_IPX: int +SOL_NETROM: int +SOL_ROSE: int +SOL_SOCKET: int +SOL_TCP: int +SOL_UDP: int +SO_ACCEPTCONN: int +SO_BINDTODEVICE: int +SO_BROADCAST: int +SO_DEBUG: int +SO_DONTROUTE: int +SO_ERROR: int +SO_EXCLUSIVEADDRUSE: int +SO_KEEPALIVE: int +SO_LINGER: int +SO_MARK: int +SO_OOBINLINE: int +SO_PASSCRED: int +SO_PEERCRED: int +SO_PRIORITY: int +SO_RCVBUF: int +SO_RCVLOWAT: int +SO_RCVTIMEO: int +SO_REUSEADDR: int +SO_REUSEPORT: int +SO_SETFIB: int +SO_SNDBUF: int +SO_SNDLOWAT: int +SO_SNDTIMEO: int +SO_TYPE: int +SO_USELOOPBACK: int +TCP_CORK: int +TCP_DEFER_ACCEPT: int +TCP_FASTOPEN: int +TCP_INFO: int +TCP_KEEPCNT: int +TCP_KEEPIDLE: int +TCP_KEEPINTVL: int +TCP_LINGER2: int +TCP_MAXSEG: int +TCP_NODELAY: int +TCP_QUICKACK: int +TCP_SYNCNT: int +TCP_WINDOW_CLAMP: int +if sys.version_info >= (3, 7): + TCP_NOTSENT_LOWAT: int + +# Specifically-documented constants + +if sys.platform == "linux": + AF_CAN: int + PF_CAN: int + SOL_CAN_BASE: int + SOL_CAN_RAW: int + CAN_EFF_FLAG: int + CAN_EFF_MASK: int + CAN_ERR_FLAG: int + CAN_ERR_MASK: int + CAN_RAW: int + CAN_RAW_ERR_FILTER: int + CAN_RAW_FILTER: int + CAN_RAW_LOOPBACK: int + CAN_RAW_RECV_OWN_MSGS: int + CAN_RTR_FLAG: int + CAN_SFF_MASK: int + + CAN_BCM: int + CAN_BCM_TX_SETUP: int + CAN_BCM_TX_DELETE: int + CAN_BCM_TX_READ: int + CAN_BCM_TX_SEND: int + CAN_BCM_RX_SETUP: int + CAN_BCM_RX_DELETE: int + CAN_BCM_RX_READ: int + CAN_BCM_TX_STATUS: int + CAN_BCM_TX_EXPIRED: int + 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 + CAN_BCM_TX_ANNOUNCE: int + CAN_BCM_TX_CP_CAN_ID: int + CAN_BCM_RX_FILTER_ID: int + CAN_BCM_RX_CHECK_DLC: int + CAN_BCM_RX_NO_AUTOTIMER: int + CAN_BCM_RX_ANNOUNCE_RESUME: int + CAN_BCM_TX_RESET_MULTI_IDX: int + CAN_BCM_RX_RTR_FRAME: int + CAN_BCM_CAN_FD_FRAME: int + +if sys.platform == "linux" and sys.version_info >= (3, 7): + CAN_ISOTP: int + +if sys.platform == "linux" and sys.version_info >= (3, 9): + CAN_J1939: int + + J1939_MAX_UNICAST_ADDR: int + J1939_IDLE_ADDR: int + J1939_NO_ADDR: int + J1939_NO_NAME: int + J1939_PGN_REQUEST: int + J1939_PGN_ADDRESS_CLAIMED: int + J1939_PGN_ADDRESS_COMMANDED: int + J1939_PGN_PDU1_MAX: int + J1939_PGN_MAX: int + J1939_NO_PGN: int + + SO_J1939_FILTER: int + SO_J1939_PROMISC: int + SO_J1939_SEND_PRIO: int + SO_J1939_ERRQUEUE: int + + SCM_J1939_DEST_ADDR: int + SCM_J1939_DEST_NAME: int + SCM_J1939_PRIO: int + SCM_J1939_ERRQUEUE: int + + 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": + AF_PACKET: int + PF_PACKET: int + PACKET_BROADCAST: int + PACKET_FASTROUTE: int + PACKET_HOST: int + PACKET_LOOPBACK: int + PACKET_MULTICAST: int + PACKET_OTHERHOST: int + PACKET_OUTGOING: int + +if sys.platform == "linux": + AF_RDS: int + PF_RDS: int + SOL_RDS: int + RDS_CANCEL_SENT_TO: int + RDS_CMSG_RDMA_ARGS: int + RDS_CMSG_RDMA_DEST: int + RDS_CMSG_RDMA_MAP: int + RDS_CMSG_RDMA_STATUS: int + RDS_CMSG_RDMA_UPDATE: int + RDS_CONG_MONITOR: int + RDS_FREE_MR: int + RDS_GET_MR: int + RDS_GET_MR_FOR_DEST: int + RDS_RDMA_DONTWAIT: int + RDS_RDMA_FENCE: int + RDS_RDMA_INVALIDATE: int + RDS_RDMA_NOTIFY_ME: int + RDS_RDMA_READWRITE: int + RDS_RDMA_SILENT: int + RDS_RDMA_USE_ONCE: int + RDS_RECVERR: int + +if sys.platform == "win32": + SIO_RCVALL: int + SIO_KEEPALIVE_VALS: int + SIO_LOOPBACK_FAST_PATH: int + RCVALL_IPLEVEL: int + RCVALL_MAX: int + RCVALL_OFF: int + RCVALL_ON: int + RCVALL_SOCKETLEVELONLY: int + +if sys.platform == "linux": + AF_TIPC: int + SOL_TIPC: int + TIPC_ADDR_ID: int + TIPC_ADDR_NAME: int + TIPC_ADDR_NAMESEQ: int + TIPC_CFG_SRV: int + TIPC_CLUSTER_SCOPE: int + TIPC_CONN_TIMEOUT: int + TIPC_CRITICAL_IMPORTANCE: int + TIPC_DEST_DROPPABLE: int + TIPC_HIGH_IMPORTANCE: int + TIPC_IMPORTANCE: int + TIPC_LOW_IMPORTANCE: int + TIPC_MEDIUM_IMPORTANCE: int + TIPC_NODE_SCOPE: int + TIPC_PUBLISHED: int + TIPC_SRC_DROPPABLE: int + TIPC_SUBSCR_TIMEOUT: int + TIPC_SUB_CANCEL: int + TIPC_SUB_PORTS: int + TIPC_SUB_SERVICE: int + TIPC_TOP_SRV: int + TIPC_WAIT_FOREVER: int + TIPC_WITHDRAWN: int + TIPC_ZONE_SCOPE: int + +if sys.platform == "linux": + AF_ALG: int + SOL_ALG: int + ALG_OP_DECRYPT: int + ALG_OP_ENCRYPT: int + ALG_OP_SIGN: int + ALG_OP_VERIFY: int + ALG_SET_AEAD_ASSOCLEN: int + ALG_SET_AEAD_AUTHSIZE: int + ALG_SET_IV: int + ALG_SET_KEY: int + ALG_SET_OP: int + ALG_SET_PUBKEY: int + +if sys.platform == "linux" and sys.version_info >= (3, 7): + AF_VSOCK: int + IOCTL_VM_SOCKETS_GET_LOCAL_CID: int + VMADDR_CID_ANY: int + VMADDR_CID_HOST: int + VMADDR_PORT_ANY: int + 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 + +AF_LINK: int # Availability: BSD, macOS + +# BDADDR_* and HCI_* listed with other bluetooth constants below + +SO_DOMAIN: int +SO_PASSSEC: int +SO_PEERSEC: int +SO_PROTOCOL: int +TCP_CONGESTION: int +TCP_USER_TIMEOUT: int + +if sys.platform == "linux" and sys.version_info >= (3, 8): + AF_QIPCRTR: int + +# Semi-documented constants +# (Listed under "Socket families" in the docs, but not "Constants") + +if sys.platform == "linux": + # Netlink is defined by Linux + AF_NETLINK: int + NETLINK_ARPD: int + NETLINK_CRYPTO: int + NETLINK_DNRTMSG: int + NETLINK_FIREWALL: int + NETLINK_IP6_FW: int + NETLINK_NFLOG: int + NETLINK_ROUTE6: int + NETLINK_ROUTE: int + NETLINK_SKIP: int + NETLINK_TAPBASE: int + NETLINK_TCPDIAG: int + NETLINK_USERSOCK: int + NETLINK_W1: int + NETLINK_XFRM: int + +if sys.platform != "win32" and sys.platform != "darwin": + # Linux and some BSD support is explicit in the docs + # Windows and macOS do not support in practice + AF_BLUETOOTH: int + BTPROTO_HCI: int + BTPROTO_L2CAP: int + BTPROTO_RFCOMM: int + BTPROTO_SCO: int # not in FreeBSD + + BDADDR_ANY: str + BDADDR_LOCAL: str + + 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": + # PF_SYSTEM is defined by macOS + PF_SYSTEM: int + SYSPROTO_CONTROL: int + +# ----- Exceptions ----- + +error = OSError + +class herror(error): ... +class gaierror(error): ... + +if sys.version_info >= (3, 10): + timeout = TimeoutError +else: + class timeout(error): ... + +# ----- Classes ----- + +class socket: + family: int + type: int + proto: int + def __init__(self, family: int = ..., type: int = ..., proto: int = ..., fileno: _FD | None = ...) -> None: ... + def bind(self, __address: _Address | bytes) -> None: ... + def close(self) -> None: ... + def connect(self, __address: _Address | bytes) -> None: ... + def connect_ex(self, __address: _Address | bytes) -> int: ... + def detach(self) -> int: ... + def fileno(self) -> int: ... + def getpeername(self) -> _RetAddress: ... + def getsockname(self) -> _RetAddress: ... + @overload + def getsockopt(self, __level: int, __optname: int) -> int: ... + @overload + def getsockopt(self, __level: int, __optname: int, __buflen: int) -> bytes: ... + if sys.version_info >= (3, 7): + def getblocking(self) -> bool: ... + def gettimeout(self) -> Optional[float]: ... + if sys.platform == "win32": + def ioctl(self, __control: int, __option: int | tuple[int, int, int] | bool) -> None: ... + def listen(self, __backlog: int = ...) -> None: ... + def recv(self, __bufsize: int, __flags: int = ...) -> bytes: ... + def recvfrom(self, __bufsize: int, __flags: int = ...) -> tuple[bytes, _RetAddress]: ... + if sys.platform != "win32": + def recvmsg(self, __bufsize: int, __ancbufsize: int = ..., __flags: int = ...) -> tuple[bytes, list[_CMSG], int, Any]: ... + def recvmsg_into( + self, __buffers: Iterable[WriteableBuffer], __ancbufsize: int = ..., __flags: int = ... + ) -> tuple[int, list[_CMSG], int, Any]: ... + def recvfrom_into(self, buffer: WriteableBuffer, nbytes: int = ..., flags: int = ...) -> tuple[int, _RetAddress]: ... + def recv_into(self, buffer: WriteableBuffer, nbytes: int = ..., flags: int = ...) -> int: ... + def send(self, __data: ReadableBuffer, __flags: int = ...) -> int: ... + def sendall(self, __data: ReadableBuffer, __flags: int = ...) -> None: ... + @overload + def sendto(self, __data: ReadableBuffer, __address: _Address) -> int: ... + @overload + def sendto(self, __data: ReadableBuffer, __flags: int, __address: _Address) -> int: ... + if sys.platform != "win32": + def sendmsg( + self, + __buffers: Iterable[ReadableBuffer], + __ancdata: Iterable[_CMSGArg] = ..., + __flags: int = ..., + __address: _Address = ..., + ) -> int: ... + if sys.platform == "linux": + def sendmsg_afalg( + self, msg: Iterable[ReadableBuffer] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = ... + ) -> int: ... + def setblocking(self, __flag: bool) -> None: ... + def settimeout(self, __value: float | None) -> None: ... + @overload + def setsockopt(self, __level: int, __optname: int, __value: int | bytes) -> None: ... + @overload + def setsockopt(self, __level: int, __optname: int, __value: None, __optlen: int) -> None: ... + if sys.platform == "win32": + def share(self, __process_id: int) -> bytes: ... + def shutdown(self, __how: int) -> None: ... + +SocketType = socket + +# ----- Functions ----- + +if sys.version_info >= (3, 7): + def close(__fd: _FD) -> None: ... + +def dup(__fd: _FD) -> int: ... + +# the 5th tuple item is an address +def getaddrinfo( + host: bytes | str | None, + port: bytes | str | int | None, + family: int = ..., + type: int = ..., + proto: int = ..., + flags: int = ..., +) -> list[tuple[int, int, int, str, Union[tuple[str, int], tuple[str, int, int, int]]]]: ... +def gethostbyname(__hostname: str) -> str: ... +def gethostbyname_ex(__hostname: str) -> tuple[str, list[str], list[str]]: ... +def gethostname() -> str: ... +def gethostbyaddr(__ip_address: str) -> tuple[str, list[str], list[str]]: ... +def getnameinfo(__sockaddr: tuple[str, int] | tuple[str, int, int, int], __flags: int) -> tuple[str, str]: ... +def getprotobyname(__protocolname: str) -> int: ... +def getservbyname(__servicename: str, __protocolname: str = ...) -> int: ... +def getservbyport(__port: int, __protocolname: str = ...) -> str: ... +def ntohl(__x: int) -> int: ... # param & ret val are 32-bit ints +def ntohs(__x: int) -> int: ... # param & ret val are 16-bit ints +def htonl(__x: int) -> int: ... # param & ret val are 32-bit ints +def htons(__x: int) -> int: ... # param & ret val are 16-bit ints +def inet_aton(__ip_string: str) -> bytes: ... # ret val 4 bytes in length +def inet_ntoa(__packed_ip: bytes) -> str: ... +def inet_pton(__address_family: int, __ip_string: str) -> bytes: ... +def inet_ntop(__address_family: int, __packed_ip: bytes) -> str: ... +def CMSG_LEN(__length: int) -> int: ... +def CMSG_SPACE(__length: int) -> int: ... +def getdefaulttimeout() -> Optional[float]: ... +def setdefaulttimeout(__timeout: float | None) -> None: ... +def socketpair(__family: int = ..., __type: int = ..., __proto: int = ...) -> tuple[socket, socket]: ... + +if sys.platform != "win32": + def sethostname(__name: str) -> None: ... + +# 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: ... diff --git a/mypy/typeshed/stdlib/_typeshed/__init__.pyi b/mypy/typeshed/stdlib/_typeshed/__init__.pyi index 60719553b46b..69d1c7c1618e 100644 --- a/mypy/typeshed/stdlib/_typeshed/__init__.pyi +++ b/mypy/typeshed/stdlib/_typeshed/__init__.pyi @@ -18,6 +18,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: ... +Self = TypeVar("Self") # noqa Y001 + # stable class IdentityFunction(Protocol): def __call__(self, __x: _T) -> _T: ... @@ -57,7 +61,6 @@ class SupportsItemAccess(SupportsGetItem[_KT_contra, _VT], Protocol[_KT_contra, StrPath = Union[str, PathLike[str]] # stable BytesPath = Union[bytes, PathLike[bytes]] # stable StrOrBytesPath = Union[str, bytes, PathLike[str], PathLike[bytes]] # stable -AnyPath = StrOrBytesPath # obsolete, will be removed soon OpenTextModeUpdating = Literal[ "r+", diff --git a/mypy/typeshed/stdlib/_typeshed/tkinter.pyi b/mypy/typeshed/stdlib/_typeshed/tkinter.pyi deleted file mode 100644 index 2fe0c4255e03..000000000000 --- a/mypy/typeshed/stdlib/_typeshed/tkinter.pyi +++ /dev/null @@ -1,7 +0,0 @@ -# See the README.md file in this directory for more information. - -from tkinter import Event, Misc, Widget -from typing import Optional, Protocol - -class DndSource(Protocol): - def dnd_end(self, target: Optional[Widget], event: Optional[Event[Misc]]) -> None: ... diff --git a/mypy/typeshed/stdlib/abc.pyi b/mypy/typeshed/stdlib/abc.pyi index 5dd21763a9ce..bf98d5364101 100644 --- a/mypy/typeshed/stdlib/abc.pyi +++ b/mypy/typeshed/stdlib/abc.pyi @@ -1,10 +1,16 @@ -from typing import Any, Callable, Type, TypeVar +from _typeshed import SupportsWrite +from typing import Any, Callable, Dict, Tuple, Type, TypeVar _T = TypeVar("_T") _FuncT = TypeVar("_FuncT", bound=Callable[..., Any]) # These definitions have special processing in mypy class ABCMeta(type): + __abstractmethods__: frozenset[str] + def __init__(self, name: str, bases: Tuple[type, ...], namespace: Dict[str, Any]) -> None: ... + def __instancecheck__(cls: ABCMeta, instance: Any) -> Any: ... + def __subclasscheck__(cls: ABCMeta, subclass: Any) -> Any: ... + def _dump_registry(cls: ABCMeta, file: SupportsWrite[str] | None = ...) -> None: ... def register(cls: ABCMeta, subclass: Type[_T]) -> Type[_T]: ... def abstractmethod(funcobj: _FuncT) -> _FuncT: ... diff --git a/mypy/typeshed/stdlib/aifc.pyi b/mypy/typeshed/stdlib/aifc.pyi index b43af47ff5e8..25df252fe30e 100644 --- a/mypy/typeshed/stdlib/aifc.pyi +++ b/mypy/typeshed/stdlib/aifc.pyi @@ -1,4 +1,5 @@ import sys +from _typeshed import Self from types import TracebackType from typing import IO, Any, List, NamedTuple, Optional, Tuple, Type, Union, overload from typing_extensions import Literal @@ -18,7 +19,7 @@ _Marker = Tuple[int, int, bytes] class Aifc_read: def __init__(self, f: _File) -> None: ... - def __enter__(self) -> Aifc_read: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> None: ... @@ -42,7 +43,7 @@ class Aifc_read: class Aifc_write: def __init__(self, f: _File) -> None: ... def __del__(self) -> None: ... - def __enter__(self) -> Aifc_write: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> None: ... diff --git a/mypy/typeshed/stdlib/argparse.pyi b/mypy/typeshed/stdlib/argparse.pyi index 2d5efdf4e98a..ec9ce24bc25b 100644 --- a/mypy/typeshed/stdlib/argparse.pyi +++ b/mypy/typeshed/stdlib/argparse.pyi @@ -69,7 +69,7 @@ class _ActionsContainer: const: Any = ..., default: Any = ..., type: Union[Callable[[str], _T], Callable[[str], _T], FileType] = ..., - choices: Iterable[_T] = ..., + choices: Optional[Iterable[_T]] = ..., required: bool = ..., help: Optional[str] = ..., metavar: Optional[Union[str, Tuple[str, ...]]] = ..., diff --git a/mypy/typeshed/stdlib/asyncio/base_events.pyi b/mypy/typeshed/stdlib/asyncio/base_events.pyi index 4c171f0ce9db..a0848da5b250 100644 --- a/mypy/typeshed/stdlib/asyncio/base_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/base_events.pyi @@ -7,6 +7,7 @@ from asyncio.futures import Future from asyncio.protocols import BaseProtocol from asyncio.tasks import Task from asyncio.transports import BaseTransport +from collections.abc import Iterable from socket import AddressFamily, SocketKind, _Address, _RetAddress, socket from typing import IO, Any, Awaitable, Callable, Dict, Generator, List, Optional, Sequence, Tuple, TypeVar, Union, overload from typing_extensions import Literal @@ -26,14 +27,22 @@ class Server(AbstractServer): def __init__( self, loop: AbstractEventLoop, - sockets: List[socket], + sockets: Iterable[socket], protocol_factory: _ProtocolFactory, ssl_context: _SSLContext, backlog: int, ssl_handshake_timeout: Optional[float], ) -> None: ... else: - def __init__(self, loop: AbstractEventLoop, sockets: List[socket]) -> None: ... + def __init__(self, loop: AbstractEventLoop, sockets: list[socket]) -> None: ... + if sys.version_info >= (3, 8): + @property + def sockets(self) -> Tuple[socket, ...]: ... + elif sys.version_info >= (3, 7): + @property + def sockets(self) -> list[socket]: ... + else: + sockets: Optional[list[socket]] class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): def run_forever(self) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/events.pyi b/mypy/typeshed/stdlib/asyncio/events.pyi index 9159af4eb20b..61aecbf6a698 100644 --- a/mypy/typeshed/stdlib/asyncio/events.pyi +++ b/mypy/typeshed/stdlib/asyncio/events.pyi @@ -1,16 +1,18 @@ import ssl import sys -from _typeshed import FileDescriptorLike +from _typeshed import FileDescriptorLike, Self from abc import ABCMeta, abstractmethod -from asyncio.futures import Future -from asyncio.protocols import BaseProtocol -from asyncio.tasks import Task -from asyncio.transports import BaseTransport -from asyncio.unix_events import AbstractChildWatcher from socket import AddressFamily, SocketKind, _Address, _RetAddress, socket from typing import IO, Any, Awaitable, Callable, Dict, Generator, List, Optional, Sequence, Tuple, TypeVar, Union, overload from typing_extensions import Literal +from .base_events import Server +from .futures import Future +from .protocols import BaseProtocol +from .tasks import Task +from .transports import BaseTransport +from .unix_events import AbstractChildWatcher + if sys.version_info >= (3, 7): from contextvars import Context @@ -53,10 +55,9 @@ class TimerHandle(Handle): def when(self) -> float: ... class AbstractServer: - sockets: Optional[List[socket]] def close(self) -> None: ... if sys.version_info >= (3, 7): - async def __aenter__(self: _T) -> _T: ... + async def __aenter__(self: Self) -> Self: ... async def __aexit__(self, *exc: Any) -> None: ... def get_loop(self) -> AbstractEventLoop: ... def is_serving(self) -> bool: ... @@ -262,7 +263,7 @@ class AbstractEventLoop(metaclass=ABCMeta): reuse_port: Optional[bool] = ..., ssl_handshake_timeout: Optional[float] = ..., start_serving: bool = ..., - ) -> AbstractServer: ... + ) -> Server: ... @overload @abstractmethod async def create_server( @@ -280,7 +281,7 @@ class AbstractEventLoop(metaclass=ABCMeta): reuse_port: Optional[bool] = ..., ssl_handshake_timeout: Optional[float] = ..., start_serving: bool = ..., - ) -> AbstractServer: ... + ) -> Server: ... async def create_unix_connection( self, protocol_factory: _ProtocolFactory, @@ -301,7 +302,7 @@ class AbstractEventLoop(metaclass=ABCMeta): ssl: _SSLContext = ..., ssl_handshake_timeout: Optional[float] = ..., start_serving: bool = ..., - ) -> AbstractServer: ... + ) -> Server: ... @abstractmethod async def sendfile( self, @@ -339,7 +340,7 @@ class AbstractEventLoop(metaclass=ABCMeta): ssl: _SSLContext = ..., reuse_address: Optional[bool] = ..., reuse_port: Optional[bool] = ..., - ) -> AbstractServer: ... + ) -> Server: ... @overload @abstractmethod async def create_server( @@ -355,7 +356,7 @@ class AbstractEventLoop(metaclass=ABCMeta): ssl: _SSLContext = ..., reuse_address: Optional[bool] = ..., reuse_port: Optional[bool] = ..., - ) -> AbstractServer: ... + ) -> Server: ... async def create_unix_connection( self, protocol_factory: _ProtocolFactory, @@ -373,7 +374,7 @@ class AbstractEventLoop(metaclass=ABCMeta): sock: Optional[socket] = ..., backlog: int = ..., ssl: _SSLContext = ..., - ) -> AbstractServer: ... + ) -> Server: ... @abstractmethod async def create_datagram_endpoint( self, diff --git a/mypy/typeshed/stdlib/asyncio/streams.pyi b/mypy/typeshed/stdlib/asyncio/streams.pyi index f0879b8daa33..770baa9fb4af 100644 --- a/mypy/typeshed/stdlib/asyncio/streams.pyi +++ b/mypy/typeshed/stdlib/asyncio/streams.pyi @@ -3,6 +3,7 @@ from _typeshed import StrPath from typing import Any, AsyncIterator, Awaitable, Callable, Iterable, Optional, Tuple, Union from . import events, protocols, transports +from .base_events import Server _ClientConnectedCallback = Callable[[StreamReader, StreamWriter], Optional[Awaitable[None]]] @@ -33,7 +34,7 @@ async def start_server( limit: int = ..., ssl_handshake_timeout: Optional[float] = ..., **kwds: Any, -) -> events.AbstractServer: ... +) -> Server: ... if sys.platform != "win32": if sys.version_info >= (3, 7): @@ -50,7 +51,7 @@ if sys.platform != "win32": loop: Optional[events.AbstractEventLoop] = ..., limit: int = ..., **kwds: Any, - ) -> events.AbstractServer: ... + ) -> Server: ... class FlowControlMixin(protocols.Protocol): def __init__(self, loop: Optional[events.AbstractEventLoop] = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/tasks.pyi b/mypy/typeshed/stdlib/asyncio/tasks.pyi index 0ff0e3895252..c306e9655daa 100644 --- a/mypy/typeshed/stdlib/asyncio/tasks.pyi +++ b/mypy/typeshed/stdlib/asyncio/tasks.pyi @@ -285,7 +285,7 @@ class Task(Future[_T], Generic[_T]): ) -> None: ... def __repr__(self) -> str: ... if sys.version_info >= (3, 8): - def get_coro(self) -> Any: ... + def get_coro(self) -> Union[Generator[_TaskYieldType, None, _T], Awaitable[_T]]: ... def get_name(self) -> str: ... def set_name(self, __value: object) -> None: ... def get_stack(self, *, limit: Optional[int] = ...) -> List[FrameType]: ... diff --git a/mypy/typeshed/stdlib/asyncio/unix_events.pyi b/mypy/typeshed/stdlib/asyncio/unix_events.pyi index 855fca43469b..d845acf5f338 100644 --- a/mypy/typeshed/stdlib/asyncio/unix_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/unix_events.pyi @@ -1,21 +1,19 @@ import sys import types +from _typeshed import Self from socket import socket -from typing import Any, Callable, Optional, Type, TypeVar +from typing import Any, Callable, Optional, Type -from .events import AbstractEventLoop, AbstractServer, BaseDefaultEventLoopPolicy, _ProtocolFactory, _SSLContext +from .base_events import Server +from .events import AbstractEventLoop, BaseDefaultEventLoopPolicy, _ProtocolFactory, _SSLContext from .selector_events import BaseSelectorEventLoop -_T1 = TypeVar("_T1", bound=AbstractChildWatcher) -_T2 = TypeVar("_T2", bound=SafeChildWatcher) -_T3 = TypeVar("_T3", bound=FastChildWatcher) - class AbstractChildWatcher: def add_child_handler(self, pid: int, callback: Callable[..., Any], *args: Any) -> None: ... def remove_child_handler(self, pid: int) -> bool: ... def attach_loop(self, loop: Optional[AbstractEventLoop]) -> None: ... def close(self) -> None: ... - def __enter__(self: _T1) -> _T1: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, typ: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[types.TracebackType] ) -> None: ... @@ -26,10 +24,10 @@ class BaseChildWatcher(AbstractChildWatcher): def __init__(self) -> None: ... class SafeChildWatcher(BaseChildWatcher): - def __enter__(self: _T2) -> _T2: ... + def __enter__(self: Self) -> Self: ... class FastChildWatcher(BaseChildWatcher): - def __enter__(self: _T3) -> _T3: ... + def __enter__(self: Self) -> Self: ... class _UnixSelectorEventLoop(BaseSelectorEventLoop): if sys.version_info < (3, 7): @@ -41,7 +39,7 @@ class _UnixSelectorEventLoop(BaseSelectorEventLoop): sock: Optional[socket] = ..., backlog: int = ..., ssl: _SSLContext = ..., - ) -> AbstractServer: ... + ) -> Server: ... class _UnixDefaultEventLoopPolicy(BaseDefaultEventLoopPolicy): def get_child_watcher(self) -> AbstractChildWatcher: ... @@ -54,15 +52,12 @@ DefaultEventLoopPolicy = _UnixDefaultEventLoopPolicy if sys.version_info >= (3, 8): from typing import Protocol - - _T4 = TypeVar("_T4", bound=MultiLoopChildWatcher) - _T5 = TypeVar("_T5", bound=ThreadedChildWatcher) class _Warn(Protocol): def __call__( self, message: str, category: Optional[Type[Warning]] = ..., stacklevel: int = ..., source: Optional[Any] = ... ) -> None: ... class MultiLoopChildWatcher(AbstractChildWatcher): - def __enter__(self: _T4) -> _T4: ... + def __enter__(self: Self) -> Self: ... class ThreadedChildWatcher(AbstractChildWatcher): - def __enter__(self: _T5) -> _T5: ... + def __enter__(self: Self) -> Self: ... def __del__(self, _warn: _Warn = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/windows_events.pyi b/mypy/typeshed/stdlib/asyncio/windows_events.pyi index 8b12a9f3539c..ca76772f3d6d 100644 --- a/mypy/typeshed/stdlib/asyncio/windows_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/windows_events.pyi @@ -1,5 +1,6 @@ import socket import sys +from _typeshed import WriteableBuffer from typing import IO, Any, Callable, ClassVar, List, NoReturn, Optional, Tuple, Type from . import events, futures, proactor_events, selector_events, streams, windows_utils @@ -45,8 +46,8 @@ class IocpProactor: def select(self, timeout: Optional[int] = ...) -> List[futures.Future[Any]]: ... def recv(self, conn: socket.socket, nbytes: int, flags: int = ...) -> futures.Future[bytes]: ... if sys.version_info >= (3, 7): - def recv_into(self, conn: socket.socket, buf: socket._WriteBuffer, flags: int = ...) -> futures.Future[Any]: ... - def send(self, conn: socket.socket, buf: socket._WriteBuffer, flags: int = ...) -> futures.Future[Any]: ... + def recv_into(self, conn: socket.socket, buf: WriteableBuffer, flags: int = ...) -> futures.Future[Any]: ... + def send(self, conn: socket.socket, buf: WriteableBuffer, flags: int = ...) -> futures.Future[Any]: ... def accept(self, listener: socket.socket) -> futures.Future[Any]: ... def connect(self, conn: socket.socket, address: bytes) -> futures.Future[Any]: ... if sys.version_info >= (3, 7): diff --git a/mypy/typeshed/stdlib/asyncio/windows_utils.pyi b/mypy/typeshed/stdlib/asyncio/windows_utils.pyi index e6009d58ebc7..1d16127a5ebe 100644 --- a/mypy/typeshed/stdlib/asyncio/windows_utils.pyi +++ b/mypy/typeshed/stdlib/asyncio/windows_utils.pyi @@ -1,4 +1,5 @@ import sys +from _typeshed import Self from types import TracebackType from typing import Callable, Optional, Protocol, Tuple, Type @@ -18,7 +19,7 @@ class PipeHandle: def __del__(self, _warn: _WarnFunction = ...) -> None: ... else: def __del__(self) -> None: ... - def __enter__(self) -> PipeHandle: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, t: Optional[type], v: Optional[BaseException], tb: Optional[TracebackType]) -> None: ... @property def handle(self) -> int: ... diff --git a/mypy/typeshed/stdlib/asyncore.pyi b/mypy/typeshed/stdlib/asyncore.pyi index 629b28752a0d..2754d5efbb36 100644 --- a/mypy/typeshed/stdlib/asyncore.pyi +++ b/mypy/typeshed/stdlib/asyncore.pyi @@ -1,10 +1,11 @@ import sys from _typeshed import FileDescriptorLike -from socket import SocketType +from socket import socket from typing import Any, Dict, Optional, Tuple, Union, overload # cyclic dependence with asynchat _maptype = Dict[int, Any] +_socket = socket socket_map: _maptype = ... # Undocumented @@ -30,19 +31,19 @@ class dispatcher: connecting: bool closing: bool ignore_log_types: frozenset[str] - socket: Optional[SocketType] - def __init__(self, sock: Optional[SocketType] = ..., map: Optional[_maptype] = ...) -> None: ... + socket: Optional[_socket] + def __init__(self, sock: Optional[_socket] = ..., map: Optional[_maptype] = ...) -> None: ... def add_channel(self, map: Optional[_maptype] = ...) -> None: ... def del_channel(self, map: Optional[_maptype] = ...) -> None: ... def create_socket(self, family: int = ..., type: int = ...) -> None: ... - def set_socket(self, sock: SocketType, map: Optional[_maptype] = ...) -> None: ... + def set_socket(self, sock: _socket, map: Optional[_maptype] = ...) -> None: ... def set_reuse_addr(self) -> None: ... def readable(self) -> bool: ... def writable(self) -> bool: ... def listen(self, num: int) -> None: ... def bind(self, addr: Union[Tuple[Any, ...], str]) -> None: ... def connect(self, address: Union[Tuple[Any, ...], str]) -> None: ... - def accept(self) -> Optional[Tuple[SocketType, Any]]: ... + def accept(self) -> Optional[Tuple[_socket, Any]]: ... def send(self, data: bytes) -> int: ... def recv(self, buffer_size: int) -> bytes: ... def close(self) -> None: ... @@ -61,7 +62,7 @@ class dispatcher: def handle_close(self) -> None: ... class dispatcher_with_send(dispatcher): - def __init__(self, sock: SocketType = ..., map: Optional[_maptype] = ...) -> None: ... + def __init__(self, sock: Optional[socket] = ..., map: Optional[_maptype] = ...) -> None: ... def initiate_send(self) -> None: ... def handle_write(self) -> None: ... # incompatible signature: diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index 752755d2bf92..d898a36299e8 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -7,6 +7,7 @@ from _typeshed import ( OpenBinaryModeWriting, OpenTextMode, ReadableBuffer, + Self, StrOrBytesPath, SupportsDivMod, SupportsKeysAndGetItem, @@ -105,7 +106,10 @@ class object: def __delattr__(self, name: str) -> None: ... def __sizeof__(self) -> int: ... def __reduce__(self) -> Union[str, Tuple[Any, ...]]: ... - def __reduce_ex__(self, protocol: int) -> Union[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 __dir__(self) -> Iterable[str]: ... def __init_subclass__(cls) -> None: ... @@ -170,7 +174,7 @@ class int: @overload def __new__(cls: Type[_T], x: Union[str, bytes, SupportsInt, SupportsIndex, _SupportsTrunc] = ...) -> _T: ... @overload - def __new__(cls: Type[_T], x: Union[str, bytes, bytearray], base: int) -> _T: ... + def __new__(cls: Type[_T], x: Union[str, bytes, bytearray], base: SupportsIndex) -> _T: ... if sys.version_info >= (3, 8): def as_integer_ratio(self) -> Tuple[int, Literal[1]]: ... @property @@ -185,10 +189,10 @@ class int: def bit_length(self) -> int: ... if sys.version_info >= (3, 10): def bit_count(self) -> int: ... - def to_bytes(self, length: int, byteorder: str, *, signed: bool = ...) -> bytes: ... + def to_bytes(self, length: SupportsIndex, byteorder: Literal["little", "big"], *, signed: bool = ...) -> bytes: ... @classmethod def from_bytes( - cls, bytes: Union[Iterable[int], SupportsBytes], byteorder: str, *, signed: bool = ... + cls, bytes: Iterable[SupportsIndex] | SupportsBytes, byteorder: Literal["little", "big"], *, signed: bool = ... ) -> int: ... # TODO buffer object argument def __add__(self, x: int) -> int: ... def __sub__(self, x: int) -> int: ... @@ -225,7 +229,7 @@ class int: def __trunc__(self) -> int: ... def __ceil__(self) -> int: ... def __floor__(self) -> int: ... - def __round__(self, ndigits: Optional[int] = ...) -> int: ... + def __round__(self, ndigits: SupportsIndex = ...) -> int: ... def __getnewargs__(self) -> Tuple[int]: ... def __eq__(self, x: object) -> bool: ... def __ne__(self, x: object) -> bool: ... @@ -279,7 +283,7 @@ class float: @overload def __round__(self, ndigits: None = ...) -> int: ... @overload - def __round__(self, ndigits: int) -> float: ... + def __round__(self, ndigits: SupportsIndex) -> float: ... def __eq__(self, x: object) -> bool: ... def __ne__(self, x: object) -> bool: ... def __lt__(self, x: float) -> bool: ... @@ -299,7 +303,7 @@ class complex: @overload def __new__(cls: Type[_T], real: float = ..., imag: float = ...) -> _T: ... @overload - def __new__(cls: Type[_T], real: Union[str, SupportsComplex, SupportsIndex]) -> _T: ... + def __new__(cls: Type[_T], real: Union[str, SupportsComplex, SupportsIndex, complex]) -> _T: ... @property def real(self) -> float: ... @property @@ -334,13 +338,16 @@ class str(Sequence[str]): def __new__(cls: Type[_T], o: bytes, encoding: str = ..., errors: str = ...) -> _T: ... def capitalize(self) -> str: ... def casefold(self) -> str: ... - def center(self, __width: int, __fillchar: str = ...) -> str: ... + def center(self, __width: SupportsIndex, __fillchar: str = ...) -> str: ... def count(self, x: str, __start: Optional[SupportsIndex] = ..., __end: Optional[SupportsIndex] = ...) -> int: ... def encode(self, encoding: str = ..., errors: str = ...) -> bytes: ... def endswith( self, __suffix: Union[str, Tuple[str, ...]], __start: Optional[SupportsIndex] = ..., __end: Optional[SupportsIndex] = ... ) -> bool: ... - def expandtabs(self, tabsize: int = ...) -> str: ... + if sys.version_info >= (3, 8): + def expandtabs(self, tabsize: SupportsIndex = ...) -> str: ... + else: + def expandtabs(self, tabsize: int = ...) -> str: ... def find(self, __sub: str, __start: Optional[SupportsIndex] = ..., __end: Optional[SupportsIndex] = ...) -> int: ... def format(self, *args: object, **kwargs: object) -> str: ... def format_map(self, map: _FormatMapMapping) -> str: ... @@ -359,21 +366,21 @@ class str(Sequence[str]): def istitle(self) -> bool: ... def isupper(self) -> bool: ... def join(self, __iterable: Iterable[str]) -> str: ... - def ljust(self, __width: int, __fillchar: str = ...) -> str: ... + def ljust(self, __width: SupportsIndex, __fillchar: str = ...) -> str: ... def lower(self) -> str: ... def lstrip(self, __chars: Optional[str] = ...) -> str: ... def partition(self, __sep: str) -> Tuple[str, str, str]: ... - def replace(self, __old: str, __new: str, __count: int = ...) -> str: ... + def replace(self, __old: str, __new: str, __count: SupportsIndex = ...) -> str: ... if sys.version_info >= (3, 9): def removeprefix(self, __prefix: str) -> str: ... def removesuffix(self, __suffix: str) -> str: ... def rfind(self, __sub: str, __start: Optional[SupportsIndex] = ..., __end: Optional[SupportsIndex] = ...) -> int: ... def rindex(self, __sub: str, __start: Optional[SupportsIndex] = ..., __end: Optional[SupportsIndex] = ...) -> int: ... - def rjust(self, __width: int, __fillchar: str = ...) -> str: ... + def rjust(self, __width: SupportsIndex, __fillchar: str = ...) -> str: ... def rpartition(self, __sep: str) -> Tuple[str, str, str]: ... - def rsplit(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... + def rsplit(self, sep: Optional[str] = ..., maxsplit: SupportsIndex = ...) -> List[str]: ... def rstrip(self, __chars: Optional[str] = ...) -> str: ... - def split(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... + def split(self, sep: Optional[str] = ..., maxsplit: SupportsIndex = ...) -> List[str]: ... def splitlines(self, keepends: bool = ...) -> List[str]: ... def startswith( self, __prefix: Union[str, Tuple[str, ...]], __start: Optional[SupportsIndex] = ..., __end: Optional[SupportsIndex] = ... @@ -383,7 +390,7 @@ class str(Sequence[str]): def title(self) -> str: ... def translate(self, __table: Union[Mapping[int, Union[int, str, None]], Sequence[Union[int, str, None]]]) -> str: ... def upper(self) -> str: ... - def zfill(self, __width: int) -> str: ... + def zfill(self, __width: SupportsIndex) -> str: ... @staticmethod @overload def maketrans(__x: Union[Dict[int, _T], Dict[str, _T], Dict[Union[str, int], _T]]) -> Dict[int, _T]: ... @@ -403,28 +410,28 @@ class str(Sequence[str]): def __len__(self) -> int: ... def __lt__(self, x: str) -> bool: ... def __mod__(self, x: Any) -> str: ... - def __mul__(self, n: int) -> str: ... + def __mul__(self, n: SupportsIndex) -> str: ... def __ne__(self, x: object) -> bool: ... def __repr__(self) -> str: ... - def __rmul__(self, n: int) -> str: ... + def __rmul__(self, n: SupportsIndex) -> str: ... def __str__(self) -> str: ... def __getnewargs__(self) -> Tuple[str]: ... class bytes(ByteString): @overload - def __new__(cls: Type[_T], ints: Iterable[int]) -> _T: ... + def __new__(cls: Type[_T], ints: Iterable[SupportsIndex]) -> _T: ... @overload def __new__(cls: Type[_T], string: str, encoding: str, errors: str = ...) -> _T: ... @overload - def __new__(cls: Type[_T], length: int) -> _T: ... + def __new__(cls: Type[_T], length: SupportsIndex) -> _T: ... @overload def __new__(cls: Type[_T]) -> _T: ... @overload def __new__(cls: Type[_T], o: SupportsBytes) -> _T: ... def capitalize(self) -> bytes: ... - def center(self, __width: int, __fillchar: bytes = ...) -> bytes: ... + def center(self, __width: SupportsIndex, __fillchar: bytes = ...) -> bytes: ... def count( - self, __sub: Union[bytes, int], __start: Optional[SupportsIndex] = ..., __end: Optional[SupportsIndex] = ... + self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> int: ... def decode(self, encoding: str = ..., errors: str = ...) -> str: ... def endswith( @@ -433,16 +440,19 @@ class bytes(ByteString): __start: Optional[SupportsIndex] = ..., __end: Optional[SupportsIndex] = ..., ) -> bool: ... - def expandtabs(self, tabsize: int = ...) -> bytes: ... + if sys.version_info >= (3, 8): + def expandtabs(self, tabsize: SupportsIndex = ...) -> bytes: ... + else: + def expandtabs(self, tabsize: int = ...) -> bytes: ... def find( - self, __sub: Union[bytes, int], __start: Optional[SupportsIndex] = ..., __end: Optional[SupportsIndex] = ... + self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> int: ... if sys.version_info >= (3, 8): - def hex(self, sep: Union[str, bytes] = ..., bytes_per_sep: int = ...) -> str: ... + def hex(self, sep: Union[str, bytes] = ..., bytes_per_sep: SupportsIndex = ...) -> str: ... else: def hex(self) -> str: ... def index( - self, __sub: Union[bytes, int], __start: Optional[SupportsIndex] = ..., __end: Optional[SupportsIndex] = ... + self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> int: ... def isalnum(self) -> bool: ... def isalpha(self) -> bool: ... @@ -454,25 +464,25 @@ class bytes(ByteString): def istitle(self) -> bool: ... def isupper(self) -> bool: ... def join(self, __iterable_of_bytes: Iterable[Union[ByteString, memoryview]]) -> bytes: ... - def ljust(self, __width: int, __fillchar: bytes = ...) -> bytes: ... + def ljust(self, __width: SupportsIndex, __fillchar: bytes = ...) -> bytes: ... def lower(self) -> bytes: ... def lstrip(self, __bytes: Optional[bytes] = ...) -> bytes: ... def partition(self, __sep: bytes) -> Tuple[bytes, bytes, bytes]: ... - def replace(self, __old: bytes, __new: bytes, __count: int = ...) -> bytes: ... + def replace(self, __old: bytes, __new: bytes, __count: SupportsIndex = ...) -> bytes: ... if sys.version_info >= (3, 9): def removeprefix(self, __prefix: bytes) -> bytes: ... def removesuffix(self, __suffix: bytes) -> bytes: ... def rfind( - self, __sub: Union[bytes, int], __start: Optional[SupportsIndex] = ..., __end: Optional[SupportsIndex] = ... + self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> int: ... def rindex( - self, __sub: Union[bytes, int], __start: Optional[SupportsIndex] = ..., __end: Optional[SupportsIndex] = ... + self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> int: ... - def rjust(self, __width: int, __fillchar: bytes = ...) -> bytes: ... + def rjust(self, __width: SupportsIndex, __fillchar: bytes = ...) -> bytes: ... def rpartition(self, __sep: bytes) -> Tuple[bytes, bytes, bytes]: ... - def rsplit(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytes]: ... + def rsplit(self, sep: Optional[bytes] = ..., maxsplit: SupportsIndex = ...) -> List[bytes]: ... def rstrip(self, __bytes: Optional[bytes] = ...) -> bytes: ... - def split(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytes]: ... + def split(self, sep: Optional[bytes] = ..., maxsplit: SupportsIndex = ...) -> List[bytes]: ... def splitlines(self, keepends: bool = ...) -> List[bytes]: ... def startswith( self, @@ -485,7 +495,7 @@ class bytes(ByteString): def title(self) -> bytes: ... def translate(self, __table: Optional[bytes], delete: bytes = ...) -> bytes: ... def upper(self) -> bytes: ... - def zfill(self, __width: int) -> bytes: ... + def zfill(self, __width: SupportsIndex) -> bytes: ... @classmethod def fromhex(cls, __s: str) -> bytes: ... @staticmethod @@ -496,15 +506,15 @@ class bytes(ByteString): def __repr__(self) -> str: ... def __hash__(self) -> int: ... @overload - def __getitem__(self, i: int) -> int: ... + def __getitem__(self, i: SupportsIndex) -> int: ... @overload def __getitem__(self, s: slice) -> bytes: ... def __add__(self, s: bytes) -> bytes: ... - def __mul__(self, n: int) -> bytes: ... - def __rmul__(self, n: int) -> bytes: ... + def __mul__(self, n: SupportsIndex) -> bytes: ... + def __rmul__(self, n: SupportsIndex) -> bytes: ... def __mod__(self, value: Any) -> bytes: ... # Incompatible with Sequence.__contains__ - def __contains__(self, o: Union[int, bytes]) -> bool: ... # type: ignore + def __contains__(self, o: SupportsIndex | bytes) -> bool: ... # type: ignore def __eq__(self, x: object) -> bool: ... def __ne__(self, x: object) -> bool: ... def __lt__(self, x: bytes) -> bool: ... @@ -517,16 +527,16 @@ class bytearray(MutableSequence[int], ByteString): @overload def __init__(self) -> None: ... @overload - def __init__(self, ints: Iterable[int]) -> None: ... + def __init__(self, ints: Iterable[SupportsIndex]) -> None: ... @overload def __init__(self, string: str, encoding: str, errors: str = ...) -> None: ... @overload - def __init__(self, length: int) -> None: ... - def append(self, __item: int) -> None: ... + def __init__(self, length: SupportsIndex) -> None: ... + def append(self, __item: SupportsIndex) -> None: ... def capitalize(self) -> bytearray: ... - def center(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... + def center(self, __width: SupportsIndex, __fillchar: bytes = ...) -> bytearray: ... def count( - self, __sub: Union[bytes, int], __start: Optional[SupportsIndex] = ..., __end: Optional[SupportsIndex] = ... + self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> int: ... def copy(self) -> bytearray: ... def decode(self, encoding: str = ..., errors: str = ...) -> str: ... @@ -536,19 +546,22 @@ class bytearray(MutableSequence[int], ByteString): __start: Optional[SupportsIndex] = ..., __end: Optional[SupportsIndex] = ..., ) -> bool: ... - def expandtabs(self, tabsize: int = ...) -> bytearray: ... - def extend(self, __iterable_of_ints: Iterable[int]) -> None: ... + if sys.version_info >= (3, 8): + def expandtabs(self, tabsize: SupportsIndex = ...) -> bytearray: ... + else: + def expandtabs(self, tabsize: int = ...) -> bytearray: ... + def extend(self, __iterable_of_ints: Iterable[SupportsIndex]) -> None: ... def find( - self, __sub: Union[bytes, int], __start: Optional[SupportsIndex] = ..., __end: Optional[SupportsIndex] = ... + self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> int: ... if sys.version_info >= (3, 8): - def hex(self, sep: Union[str, bytes] = ..., bytes_per_sep: int = ...) -> str: ... + def hex(self, sep: Union[str, bytes] = ..., bytes_per_sep: SupportsIndex = ...) -> str: ... else: def hex(self) -> str: ... def index( - self, __sub: Union[bytes, int], __start: Optional[SupportsIndex] = ..., __end: Optional[SupportsIndex] = ... + self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> int: ... - def insert(self, __index: int, __item: int) -> None: ... + def insert(self, __index: SupportsIndex, __item: SupportsIndex) -> None: ... def isalnum(self) -> bool: ... def isalpha(self) -> bool: ... if sys.version_info >= (3, 7): @@ -559,25 +572,25 @@ class bytearray(MutableSequence[int], ByteString): def istitle(self) -> bool: ... def isupper(self) -> bool: ... def join(self, __iterable_of_bytes: Iterable[Union[ByteString, memoryview]]) -> bytearray: ... - def ljust(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... + def ljust(self, __width: SupportsIndex, __fillchar: bytes = ...) -> bytearray: ... def lower(self) -> bytearray: ... def lstrip(self, __bytes: Optional[bytes] = ...) -> bytearray: ... def partition(self, __sep: bytes) -> Tuple[bytearray, bytearray, bytearray]: ... if sys.version_info >= (3, 9): def removeprefix(self, __prefix: bytes) -> bytearray: ... def removesuffix(self, __suffix: bytes) -> bytearray: ... - def replace(self, __old: bytes, __new: bytes, __count: int = ...) -> bytearray: ... + def replace(self, __old: bytes, __new: bytes, __count: SupportsIndex = ...) -> bytearray: ... def rfind( - self, __sub: Union[bytes, int], __start: Optional[SupportsIndex] = ..., __end: Optional[SupportsIndex] = ... + self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> int: ... def rindex( - self, __sub: Union[bytes, int], __start: Optional[SupportsIndex] = ..., __end: Optional[SupportsIndex] = ... + self, __sub: bytes | SupportsIndex, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> int: ... - def rjust(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... + def rjust(self, __width: SupportsIndex, __fillchar: bytes = ...) -> bytearray: ... def rpartition(self, __sep: bytes) -> Tuple[bytearray, bytearray, bytearray]: ... - def rsplit(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytearray]: ... + def rsplit(self, sep: Optional[bytes] = ..., maxsplit: SupportsIndex = ...) -> List[bytearray]: ... def rstrip(self, __bytes: Optional[bytes] = ...) -> bytearray: ... - def split(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytearray]: ... + def split(self, sep: Optional[bytes] = ..., maxsplit: SupportsIndex = ...) -> List[bytearray]: ... def splitlines(self, keepends: bool = ...) -> List[bytearray]: ... def startswith( self, @@ -590,7 +603,7 @@ class bytearray(MutableSequence[int], ByteString): def title(self) -> bytearray: ... def translate(self, __table: Optional[bytes], delete: bytes = ...) -> bytearray: ... def upper(self) -> bytearray: ... - def zfill(self, __width: int) -> bytearray: ... + def zfill(self, __width: SupportsIndex) -> bytearray: ... @classmethod def fromhex(cls, __string: str) -> bytearray: ... @staticmethod @@ -601,22 +614,22 @@ class bytearray(MutableSequence[int], ByteString): def __repr__(self) -> str: ... __hash__: None # type: ignore @overload - def __getitem__(self, i: int) -> int: ... + def __getitem__(self, i: SupportsIndex) -> int: ... @overload def __getitem__(self, s: slice) -> bytearray: ... @overload - def __setitem__(self, i: int, x: int) -> None: ... + def __setitem__(self, i: SupportsIndex, x: SupportsIndex) -> None: ... @overload - def __setitem__(self, s: slice, x: Union[Iterable[int], bytes]) -> None: ... - def __delitem__(self, i: Union[int, slice]) -> None: ... + def __setitem__(self, s: slice, x: Iterable[SupportsIndex] | bytes) -> None: ... + def __delitem__(self, i: SupportsIndex | slice) -> None: ... def __add__(self, s: bytes) -> bytearray: ... def __iadd__(self, s: Iterable[int]) -> bytearray: ... - def __mul__(self, n: int) -> bytearray: ... - def __rmul__(self, n: int) -> bytearray: ... - def __imul__(self, n: int) -> bytearray: ... + def __mul__(self, n: SupportsIndex) -> bytearray: ... + def __rmul__(self, n: SupportsIndex) -> bytearray: ... + def __imul__(self, n: SupportsIndex) -> bytearray: ... def __mod__(self, value: Any) -> bytes: ... # Incompatible with Sequence.__contains__ - def __contains__(self, o: Union[int, bytes]) -> bool: ... # type: ignore + def __contains__(self, o: SupportsIndex | bytes) -> bool: ... # type: ignore def __eq__(self, x: object) -> bool: ... def __ne__(self, x: object) -> bool: ... def __lt__(self, x: bytes) -> bool: ... @@ -639,13 +652,13 @@ class memoryview(Sized, Sequence[int]): contiguous: bool nbytes: int def __init__(self, obj: ReadableBuffer) -> None: ... - def __enter__(self) -> memoryview: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> None: ... def cast(self, format: str, shape: Union[List[int], Tuple[int]] = ...) -> memoryview: ... @overload - def __getitem__(self, i: int) -> int: ... + def __getitem__(self, i: SupportsIndex) -> int: ... @overload def __getitem__(self, s: slice) -> memoryview: ... def __contains__(self, x: object) -> bool: ... @@ -654,7 +667,7 @@ class memoryview(Sized, Sequence[int]): @overload def __setitem__(self, s: slice, o: bytes) -> None: ... @overload - def __setitem__(self, i: int, o: int) -> None: ... + def __setitem__(self, i: SupportsIndex, o: SupportsIndex) -> None: ... if sys.version_info >= (3, 8): def tobytes(self, order: Optional[Literal["C", "F", "A"]] = ...) -> bytes: ... else: @@ -664,7 +677,7 @@ class memoryview(Sized, Sequence[int]): def toreadonly(self) -> memoryview: ... def release(self) -> None: ... if sys.version_info >= (3, 8): - def hex(self, sep: Union[str, bytes] = ..., bytes_per_sep: int = ...) -> str: ... + def hex(self, sep: Union[str, bytes] = ..., bytes_per_sep: SupportsIndex = ...) -> str: ... else: def hex(self) -> str: ... @@ -706,7 +719,7 @@ class slice(object): @overload def __init__(self, start: Any, stop: Any, step: Any = ...) -> None: ... __hash__: None # type: ignore - def indices(self, len: int) -> Tuple[int, int, int]: ... + def indices(self, len: SupportsIndex) -> Tuple[int, int, int]: ... class tuple(Sequence[_T_co], Generic[_T_co]): def __new__(cls: Type[_T], iterable: Iterable[_T_co] = ...) -> _T: ... @@ -725,10 +738,10 @@ class tuple(Sequence[_T_co], Generic[_T_co]): def __add__(self, x: Tuple[_T_co, ...]) -> Tuple[_T_co, ...]: ... @overload def __add__(self, x: Tuple[_T, ...]) -> Tuple[Union[_T_co, _T], ...]: ... - def __mul__(self, n: int) -> Tuple[_T_co, ...]: ... - def __rmul__(self, n: int) -> Tuple[_T_co, ...]: ... + def __mul__(self, n: SupportsIndex) -> Tuple[_T_co, ...]: ... + def __rmul__(self, n: SupportsIndex) -> Tuple[_T_co, ...]: ... def count(self, __value: Any) -> int: ... - def index(self, __value: Any, __start: int = ..., __stop: int = ...) -> int: ... + def index(self, __value: Any, __start: SupportsIndex = ..., __stop: SupportsIndex = ...) -> int: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... @@ -749,10 +762,10 @@ class list(MutableSequence[_T], Generic[_T]): def copy(self) -> List[_T]: ... def append(self, __object: _T) -> None: ... def extend(self, __iterable: Iterable[_T]) -> None: ... - def pop(self, __index: int = ...) -> _T: ... - def index(self, __value: _T, __start: int = ..., __stop: int = ...) -> int: ... + def pop(self, __index: SupportsIndex = ...) -> _T: ... + def index(self, __value: _T, __start: SupportsIndex = ..., __stop: SupportsIndex = ...) -> int: ... def count(self, __value: _T) -> int: ... - def insert(self, __index: int, __object: _T) -> None: ... + def insert(self, __index: SupportsIndex, __object: _T) -> None: ... def remove(self, __value: _T) -> None: ... def reverse(self) -> None: ... @overload @@ -774,9 +787,9 @@ class list(MutableSequence[_T], Generic[_T]): def __delitem__(self, i: Union[SupportsIndex, slice]) -> None: ... def __add__(self, x: List[_T]) -> List[_T]: ... def __iadd__(self: _S, x: Iterable[_T]) -> _S: ... - def __mul__(self, n: int) -> List[_T]: ... - def __rmul__(self, n: int) -> List[_T]: ... - def __imul__(self: _S, n: int) -> _S: ... + def __mul__(self, n: SupportsIndex) -> List[_T]: ... + def __rmul__(self, n: SupportsIndex) -> List[_T]: ... + def __imul__(self: _S, n: SupportsIndex) -> _S: ... def __contains__(self, o: object) -> bool: ... def __reversed__(self) -> Iterator[_T]: ... def __gt__(self, x: List[_T]) -> bool: ... @@ -826,9 +839,9 @@ class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): __hash__: None # type: ignore if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... - def __or__(self, __value: Mapping[_KT, _VT]) -> Dict[_KT, _VT]: ... - def __ror__(self, __value: Mapping[_KT, _VT]) -> Dict[_KT, _VT]: ... - def __ior__(self, __value: Mapping[_KT, _VT]) -> Dict[_KT, _VT]: ... + def __or__(self, __value: Mapping[_T1, _T2]) -> Dict[Union[_KT, _T1], Union[_VT, _T2]]: ... + def __ror__(self, __value: Mapping[_T1, _T2]) -> Dict[Union[_KT, _T1], Union[_VT, _T2]]: ... + def __ior__(self, __value: Mapping[_KT, _VT]) -> Dict[_KT, _VT]: ... # type: ignore class set(MutableSet[_T], Generic[_T]): def __init__(self, iterable: Iterable[_T] = ...) -> None: ... @@ -1021,9 +1034,14 @@ class filter(Iterator[_T], Generic[_T]): def format(__value: object, __format_spec: str = ...) -> str: ... # TODO unicode @overload def getattr(__o: Any, name: str) -> Any: ... + +# While technically covered by the last overload, spelling out the types for None and bool +# help mypy out in some tricky situations involving type context (aka bidirectional inference) @overload def getattr(__o: Any, name: str, __default: None) -> Optional[Any]: ... @overload +def getattr(__o: Any, name: str, __default: bool) -> Union[Any, bool]: ... +@overload def getattr(__o: Any, name: str, __default: _T) -> Union[Any, _T]: ... def globals() -> Dict[str, Any]: ... def hasattr(__obj: Any, __name: str) -> bool: ... @@ -1281,7 +1299,7 @@ def round(number: SupportsRound[Any]) -> int: ... @overload def round(number: SupportsRound[Any], ndigits: None) -> int: ... @overload -def round(number: SupportsRound[_T], ndigits: int) -> _T: ... +def round(number: SupportsRound[_T], ndigits: SupportsIndex) -> _T: ... def setattr(__obj: Any, __name: str, __value: Any) -> None: ... @overload def sorted(__iterable: Iterable[SupportsLessThanT], *, key: None = ..., reverse: bool = ...) -> List[SupportsLessThanT]: ... diff --git a/mypy/typeshed/stdlib/bz2.pyi b/mypy/typeshed/stdlib/bz2.pyi index 390024a04184..20fee8aa0b99 100644 --- a/mypy/typeshed/stdlib/bz2.pyi +++ b/mypy/typeshed/stdlib/bz2.pyi @@ -1,22 +1,35 @@ -import io +import _compression import sys -from _typeshed import ReadableBuffer, StrOrBytesPath, WriteableBuffer -from typing import IO, Any, Iterable, List, Optional, TextIO, TypeVar, Union, overload +from _compression import BaseStream +from _typeshed import ReadableBuffer, Self, StrOrBytesPath, WriteableBuffer +from typing import IO, Any, Iterable, List, Optional, Protocol, TextIO, TypeVar, Union, overload from typing_extensions import Literal, SupportsIndex -_PathOrFile = Union[StrOrBytesPath, IO[bytes]] +# The following attributes and methods are optional: +# def fileno(self) -> int: ... +# def close(self) -> object: ... +class _ReadableFileobj(_compression._Reader, Protocol): ... + +class _WritableFileobj(Protocol): + def write(self, __b: bytes) -> object: ... + # The following attributes and methods are optional: + # def fileno(self) -> int: ... + # def close(self) -> object: ... + _T = TypeVar("_T") def compress(data: bytes, compresslevel: int = ...) -> bytes: ... def decompress(data: bytes) -> bytes: ... -_OpenBinaryMode = Literal["r", "rb", "w", "wb", "x", "xb", "a", "ab"] -_OpenTextMode = Literal["rt", "wt", "xt", "at"] +_ReadBinaryMode = Literal["", "r", "rb"] +_WriteBinaryMode = Literal["w", "wb", "x", "xb", "a", "ab"] +_ReadTextMode = Literal["rt"] +_WriteTextMode = Literal["wt", "xt", "at"] @overload def open( - filename: _PathOrFile, - mode: _OpenBinaryMode = ..., + filename: _ReadableFileobj, + mode: _ReadBinaryMode = ..., compresslevel: int = ..., encoding: None = ..., errors: None = ..., @@ -24,8 +37,8 @@ def open( ) -> BZ2File: ... @overload def open( - filename: StrOrBytesPath, - mode: _OpenTextMode, + filename: _ReadableFileobj, + mode: _ReadTextMode, compresslevel: int = ..., encoding: Optional[str] = ..., errors: Optional[str] = ..., @@ -33,21 +46,72 @@ def open( ) -> TextIO: ... @overload def open( - filename: _PathOrFile, - mode: str, + filename: _WritableFileobj, + mode: _WriteBinaryMode, + compresslevel: int = ..., + encoding: None = ..., + errors: None = ..., + newline: None = ..., +) -> BZ2File: ... +@overload +def open( + filename: _WritableFileobj, + mode: _WriteTextMode, compresslevel: int = ..., encoding: Optional[str] = ..., errors: Optional[str] = ..., newline: Optional[str] = ..., -) -> Union[BZ2File, TextIO]: ... +) -> TextIO: ... +@overload +def open( + filename: StrOrBytesPath, + mode: Union[_ReadBinaryMode, _WriteBinaryMode] = ..., + compresslevel: int = ..., + encoding: None = ..., + errors: None = ..., + newline: None = ..., +) -> BZ2File: ... +@overload +def open( + filename: StrOrBytesPath, + mode: Union[_ReadTextMode, _WriteTextMode], + compresslevel: int = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + newline: Optional[str] = ..., +) -> TextIO: ... -class BZ2File(io.BufferedIOBase, IO[bytes]): - def __enter__(self: _T) -> _T: ... +class BZ2File(BaseStream, IO[bytes]): + def __enter__(self: Self) -> Self: ... if sys.version_info >= (3, 9): - def __init__(self, filename: _PathOrFile, mode: str = ..., *, compresslevel: int = ...) -> None: ... + @overload + def __init__(self, filename: _WritableFileobj, mode: _WriteBinaryMode, *, compresslevel: int = ...) -> None: ... + @overload + def __init__(self, filename: _ReadableFileobj, mode: _ReadBinaryMode = ..., *, compresslevel: int = ...) -> None: ... + @overload + def __init__( + self, filename: StrOrBytesPath, mode: Union[_ReadBinaryMode, _WriteBinaryMode] = ..., *, compresslevel: int = ... + ) -> None: ... else: + @overload + def __init__( + self, filename: _WritableFileobj, mode: _WriteBinaryMode, buffering: Optional[Any] = ..., compresslevel: int = ... + ) -> None: ... + @overload + def __init__( + self, + filename: _ReadableFileobj, + mode: _ReadBinaryMode = ..., + buffering: Optional[Any] = ..., + compresslevel: int = ..., + ) -> None: ... + @overload def __init__( - self, filename: _PathOrFile, mode: str = ..., buffering: Optional[Any] = ..., compresslevel: int = ... + self, + filename: StrOrBytesPath, + mode: Union[_ReadBinaryMode, _WriteBinaryMode] = ..., + buffering: Optional[Any] = ..., + compresslevel: int = ..., ) -> None: ... def read(self, size: Optional[int] = ...) -> bytes: ... def read1(self, size: int = ...) -> bytes: ... diff --git a/mypy/typeshed/stdlib/cProfile.pyi b/mypy/typeshed/stdlib/cProfile.pyi index 6648ed5b94a3..a1deb38df4f4 100644 --- a/mypy/typeshed/stdlib/cProfile.pyi +++ b/mypy/typeshed/stdlib/cProfile.pyi @@ -1,5 +1,5 @@ import sys -from _typeshed import StrOrBytesPath +from _typeshed import Self, StrOrBytesPath from types import CodeType from typing import Any, Callable, Dict, Optional, Tuple, TypeVar, Union @@ -8,7 +8,6 @@ def runctx( statement: str, globals: Dict[str, Any], locals: Dict[str, Any], filename: Optional[str] = ..., sort: Union[str, int] = ... ) -> None: ... -_SelfT = TypeVar("_SelfT", bound=Profile) _T = TypeVar("_T") _Label = Tuple[str, int, str] @@ -23,11 +22,11 @@ class Profile: def dump_stats(self, file: StrOrBytesPath) -> None: ... def create_stats(self) -> None: ... def snapshot_stats(self) -> None: ... - def run(self: _SelfT, cmd: str) -> _SelfT: ... - def runctx(self: _SelfT, cmd: str, globals: Dict[str, Any], locals: Dict[str, Any]) -> _SelfT: ... + def run(self: Self, cmd: str) -> Self: ... + def runctx(self: Self, cmd: str, globals: Dict[str, Any], locals: Dict[str, Any]) -> Self: ... def runcall(self, __func: Callable[..., _T], *args: Any, **kw: Any) -> _T: ... if sys.version_info >= (3, 8): - def __enter__(self: _SelfT) -> _SelfT: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, *exc_info: Any) -> None: ... def label(code: Union[str, CodeType]) -> _Label: ... # undocumented diff --git a/mypy/typeshed/stdlib/codecs.pyi b/mypy/typeshed/stdlib/codecs.pyi index 7172d0074c7b..3e61c9eaf50c 100644 --- a/mypy/typeshed/stdlib/codecs.pyi +++ b/mypy/typeshed/stdlib/codecs.pyi @@ -1,4 +1,6 @@ +import sys import types +from _typeshed import Self from abc import abstractmethod from typing import ( IO, @@ -122,6 +124,9 @@ def EncodedFile(file: IO[bytes], data_encoding: str, file_encoding: Optional[str def iterencode(iterator: Iterable[str], encoding: str, errors: str = ...) -> Generator[bytes, None, None]: ... def iterdecode(iterator: Iterable[bytes], encoding: str, errors: str = ...) -> Generator[str, None, None]: ... +if sys.version_info >= (3, 10): + def unregister(__search_function: Callable[[str], Optional[CodecInfo]]) -> None: ... + BOM: bytes BOM_BE: bytes BOM_LE: bytes @@ -184,8 +189,6 @@ class BufferedIncrementalDecoder(IncrementalDecoder): def _buffer_decode(self, input: bytes, errors: str, final: bool) -> Tuple[str, int]: ... def decode(self, input: bytes, final: bool = ...) -> str: ... -_SW = TypeVar("_SW", bound=StreamWriter) - # TODO: it is not possible to specify the requirement that all other # attributes and methods are passed-through from the stream. class StreamWriter(Codec): @@ -194,14 +197,12 @@ class StreamWriter(Codec): def write(self, object: str) -> None: ... def writelines(self, list: Iterable[str]) -> None: ... def reset(self) -> None: ... - def __enter__(self: _SW) -> _SW: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, typ: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[types.TracebackType] ) -> None: ... def __getattr__(self, name: str, getattr: Callable[[str], Any] = ...) -> Any: ... -_SR = TypeVar("_SR", bound=StreamReader) - class StreamReader(Codec): errors: str def __init__(self, stream: IO[bytes], errors: str = ...) -> None: ... @@ -209,7 +210,7 @@ class StreamReader(Codec): def readline(self, size: Optional[int] = ..., keepends: bool = ...) -> str: ... def readlines(self, sizehint: Optional[int] = ..., keepends: bool = ...) -> List[str]: ... def reset(self) -> None: ... - def __enter__(self: _SR) -> _SR: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, typ: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[types.TracebackType] ) -> None: ... @@ -233,7 +234,7 @@ class StreamReaderWriter(TextIO): def reset(self) -> None: ... # Same as write() def seek(self, offset: int, whence: int = ...) -> int: ... - def __enter__(self: _T) -> _T: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, typ: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[types.TracebackType] ) -> None: ... @@ -271,7 +272,7 @@ class StreamRecoder(BinaryIO): def writelines(self, list: Iterable[bytes]) -> int: ... # type: ignore # it's supposed to return None def reset(self) -> None: ... def __getattr__(self, name: str) -> Any: ... - def __enter__(self: _SRT) -> _SRT: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, type: Optional[Type[BaseException]], value: Optional[BaseException], tb: Optional[types.TracebackType] ) -> None: ... diff --git a/mypy/typeshed/stdlib/collections/__init__.pyi b/mypy/typeshed/stdlib/collections/__init__.pyi index 635d32ebd294..a625c2b38b1e 100644 --- a/mypy/typeshed/stdlib/collections/__init__.pyi +++ b/mypy/typeshed/stdlib/collections/__init__.pyi @@ -1,4 +1,5 @@ import sys +from _typeshed import Self from typing import Any, Dict, Generic, List, NoReturn, Optional, Tuple, Type, TypeVar, Union, overload if sys.version_info >= (3, 10): @@ -69,7 +70,7 @@ class UserList(MutableSequence[_T]): @overload def __getitem__(self, i: int) -> _T: ... @overload - def __getitem__(self, i: slice) -> MutableSequence[_T]: ... + def __getitem__(self: Self, i: slice) -> Self: ... @overload def __setitem__(self, i: int, o: _T) -> None: ... @overload diff --git a/mypy/typeshed/stdlib/concurrent/futures/_base.pyi b/mypy/typeshed/stdlib/concurrent/futures/_base.pyi index ca4087948c3e..df2afb9d9b6a 100644 --- a/mypy/typeshed/stdlib/concurrent/futures/_base.pyi +++ b/mypy/typeshed/stdlib/concurrent/futures/_base.pyi @@ -1,5 +1,6 @@ import sys import threading +from _typeshed import Self from abc import abstractmethod from logging import Logger from typing import ( @@ -79,7 +80,7 @@ class Executor: def shutdown(self, wait: bool = ..., *, cancel_futures: bool = ...) -> None: ... else: def shutdown(self, wait: bool = ...) -> None: ... - def __enter__(self: _T) -> _T: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> Optional[bool]: ... def as_completed(fs: Iterable[Future[_T]], timeout: Optional[float] = ...) -> Iterator[Future[_T]]: ... diff --git a/mypy/typeshed/stdlib/contextlib.pyi b/mypy/typeshed/stdlib/contextlib.pyi index 3cadf91df90f..e2a680e4c65e 100644 --- a/mypy/typeshed/stdlib/contextlib.pyi +++ b/mypy/typeshed/stdlib/contextlib.pyi @@ -1,10 +1,12 @@ import sys +from _typeshed import Self from types import TracebackType from typing import ( IO, Any, AsyncContextManager, AsyncIterator, + Awaitable, Callable, ContextManager, Iterator, @@ -13,7 +15,7 @@ from typing import ( TypeVar, overload, ) -from typing_extensions import Protocol +from typing_extensions import ParamSpec, Protocol AbstractContextManager = ContextManager if sys.version_info >= (3, 7): @@ -23,6 +25,7 @@ _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) _T_io = TypeVar("_T_io", bound=Optional[IO[str]]) _F = TypeVar("_F", bound=Callable[..., Any]) +_P = ParamSpec("_P") _ExitFunc = Callable[[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]], bool] _CM_EF = TypeVar("_CM_EF", ContextManager[Any], _ExitFunc) @@ -30,13 +33,14 @@ _CM_EF = TypeVar("_CM_EF", ContextManager[Any], _ExitFunc) class _GeneratorContextManager(ContextManager[_T_co]): def __call__(self, func: _F) -> _F: ... -def contextmanager(func: Callable[..., Iterator[_T]]) -> Callable[..., _GeneratorContextManager[_T]]: ... +# type ignore to deal with incomplete ParamSpec support in mypy +def contextmanager(func: Callable[_P, Iterator[_T]]) -> Callable[_P, _GeneratorContextManager[_T]]: ... # type: ignore if sys.version_info >= (3, 7): - def asynccontextmanager(func: Callable[..., AsyncIterator[_T]]) -> Callable[..., AsyncContextManager[_T]]: ... + def asynccontextmanager(func: Callable[_P, AsyncIterator[_T]]) -> Callable[_P, AsyncContextManager[_T]]: ... # type: ignore class _SupportsClose(Protocol): - def close(self) -> None: ... + def close(self) -> object: ... _SupportsCloseT = TypeVar("_SupportsCloseT", bound=_SupportsClose) @@ -45,10 +49,13 @@ class closing(ContextManager[_SupportsCloseT]): if sys.version_info >= (3, 10): class _SupportsAclose(Protocol): - async def aclose(self) -> None: ... + def aclose(self) -> Awaitable[object]: ... _SupportsAcloseT = TypeVar("_SupportsAcloseT", bound=_SupportsAclose) class aclosing(AsyncContextManager[_SupportsAcloseT]): def __init__(self, thing: _SupportsAcloseT) -> None: ... + _AF = TypeVar("_AF", bound=Callable[..., Awaitable[Any]]) + class AsyncContextDecorator: + def __call__(self, func: _AF) -> _AF: ... class suppress(ContextManager[None]): def __init__(self, *exceptions: Type[BaseException]) -> None: ... @@ -65,16 +72,14 @@ class redirect_stderr(ContextManager[_T_io]): class ContextDecorator: def __call__(self, func: _F) -> _F: ... -_U = TypeVar("_U", bound=ExitStack) - class ExitStack(ContextManager[ExitStack]): def __init__(self) -> None: ... def enter_context(self, cm: ContextManager[_T]) -> _T: ... def push(self, exit: _CM_EF) -> _CM_EF: ... def callback(self, callback: Callable[..., Any], *args: Any, **kwds: Any) -> Callable[..., Any]: ... - def pop_all(self: _U) -> _U: ... + def pop_all(self: Self) -> Self: ... def close(self) -> None: ... - def __enter__(self: _U) -> _U: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, __exc_type: Optional[Type[BaseException]], @@ -83,10 +88,6 @@ class ExitStack(ContextManager[ExitStack]): ) -> bool: ... if sys.version_info >= (3, 7): - from typing import Awaitable - - _S = TypeVar("_S", bound=AsyncExitStack) - _ExitCoroFunc = Callable[[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]], Awaitable[bool]] _CallbackCoroFunc = Callable[..., Awaitable[Any]] _ACM_EF = TypeVar("_ACM_EF", AsyncContextManager[Any], _ExitCoroFunc) @@ -98,9 +99,9 @@ if sys.version_info >= (3, 7): def push_async_exit(self, exit: _ACM_EF) -> _ACM_EF: ... def callback(self, callback: Callable[..., Any], *args: Any, **kwds: Any) -> Callable[..., Any]: ... def push_async_callback(self, callback: _CallbackCoroFunc, *args: Any, **kwds: Any) -> _CallbackCoroFunc: ... - def pop_all(self: _S) -> _S: ... + def pop_all(self: Self) -> Self: ... def aclose(self) -> Awaitable[None]: ... - def __aenter__(self: _S) -> Awaitable[_S]: ... + def __aenter__(self: Self) -> Awaitable[Self]: ... def __aexit__( self, __exc_type: Optional[Type[BaseException]], @@ -108,8 +109,24 @@ if sys.version_info >= (3, 7): __traceback: Optional[TracebackType], ) -> Awaitable[bool]: ... -if sys.version_info >= (3, 7): - @overload - def nullcontext(enter_result: _T) -> ContextManager[_T]: ... - @overload - def nullcontext() -> ContextManager[None]: ... +if sys.version_info >= (3, 10): + class nullcontext(AbstractContextManager[_T], AbstractAsyncContextManager[_T]): + enter_result: _T + @overload + def __init__(self: nullcontext[None], enter_result: None = ...) -> None: ... + @overload + def __init__(self: nullcontext[_T], enter_result: _T) -> None: ... + def __enter__(self) -> _T: ... + def __exit__(self, *exctype: Any) -> None: ... + async def __aenter__(self) -> _T: ... + async def __aexit__(self, *exctype: Any) -> None: ... + +elif sys.version_info >= (3, 7): + class nullcontext(AbstractContextManager[_T]): + enter_result: _T + @overload + def __init__(self: nullcontext[None], enter_result: None = ...) -> None: ... + @overload + def __init__(self: nullcontext[_T], enter_result: _T) -> None: ... + def __enter__(self) -> _T: ... + def __exit__(self, *exctype: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/dataclasses.pyi b/mypy/typeshed/stdlib/dataclasses.pyi index 8d4ab1b1efba..519da6d31dbe 100644 --- a/mypy/typeshed/stdlib/dataclasses.pyi +++ b/mypy/typeshed/stdlib/dataclasses.pyi @@ -1,10 +1,12 @@ import sys from typing import Any, Callable, Dict, Generic, Iterable, List, Mapping, Optional, Tuple, Type, TypeVar, Union, overload +from typing_extensions import Protocol if sys.version_info >= (3, 9): from types import GenericAlias _T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) class _MISSING_TYPE: ... @@ -63,11 +65,15 @@ else: *, init: bool = ..., repr: bool = ..., eq: bool = ..., order: bool = ..., unsafe_hash: bool = ..., frozen: bool = ... ) -> Callable[[Type[_T]], Type[_T]]: ... +# See https://github.com/python/mypy/issues/10750 +class _DefaultFactory(Protocol[_T_co]): + def __call__(self) -> _T_co: ... + class Field(Generic[_T]): name: str type: Type[_T] default: _T - default_factory: Callable[[], _T] + default_factory: _DefaultFactory[_T] repr: bool hash: Optional[bool] init: bool diff --git a/mypy/typeshed/stdlib/datetime.pyi b/mypy/typeshed/stdlib/datetime.pyi index e82b26923571..4426a9eee28f 100644 --- a/mypy/typeshed/stdlib/datetime.pyi +++ b/mypy/typeshed/stdlib/datetime.pyi @@ -179,6 +179,7 @@ class timedelta(SupportsAbs[timedelta]): def __lt__(self, other: timedelta) -> bool: ... def __ge__(self, other: timedelta) -> bool: ... def __gt__(self, other: timedelta) -> bool: ... + def __bool__(self) -> bool: ... def __hash__(self) -> int: ... class datetime(date): diff --git a/mypy/typeshed/stdlib/dbm/__init__.pyi b/mypy/typeshed/stdlib/dbm/__init__.pyi index f2d64446a6a2..7344d7b1b755 100644 --- a/mypy/typeshed/stdlib/dbm/__init__.pyi +++ b/mypy/typeshed/stdlib/dbm/__init__.pyi @@ -1,3 +1,4 @@ +from _typeshed import Self from types import TracebackType from typing import Iterator, MutableMapping, Optional, Tuple, Type, Union from typing_extensions import Literal @@ -79,7 +80,7 @@ class _Database(MutableMapping[_KeyType, bytes]): def __iter__(self) -> Iterator[bytes]: ... def __len__(self) -> int: ... def __del__(self) -> None: ... - def __enter__(self) -> _Database: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> None: ... diff --git a/mypy/typeshed/stdlib/dbm/dumb.pyi b/mypy/typeshed/stdlib/dbm/dumb.pyi index 0b8ee50a79b7..1daa24b7f5b8 100644 --- a/mypy/typeshed/stdlib/dbm/dumb.pyi +++ b/mypy/typeshed/stdlib/dbm/dumb.pyi @@ -1,3 +1,4 @@ +from _typeshed import Self from types import TracebackType from typing import Iterator, MutableMapping, Optional, Type, Union @@ -17,7 +18,7 @@ class _Database(MutableMapping[_KeyType, bytes]): def __iter__(self) -> Iterator[bytes]: ... def __len__(self) -> int: ... def __del__(self) -> None: ... - def __enter__(self) -> _Database: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> None: ... diff --git a/mypy/typeshed/stdlib/dbm/gnu.pyi b/mypy/typeshed/stdlib/dbm/gnu.pyi index 20033ded6373..c694ca96b33f 100644 --- a/mypy/typeshed/stdlib/dbm/gnu.pyi +++ b/mypy/typeshed/stdlib/dbm/gnu.pyi @@ -1,3 +1,4 @@ +from _typeshed import Self from types import TracebackType from typing import List, Optional, Type, TypeVar, Union, overload @@ -19,7 +20,7 @@ class _gdbm: def __delitem__(self, key: _KeyType) -> None: ... def __contains__(self, key: _KeyType) -> bool: ... def __len__(self) -> int: ... - def __enter__(self) -> _gdbm: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> None: ... diff --git a/mypy/typeshed/stdlib/dbm/ndbm.pyi b/mypy/typeshed/stdlib/dbm/ndbm.pyi index 020131543e13..6af8d5c32fd7 100644 --- a/mypy/typeshed/stdlib/dbm/ndbm.pyi +++ b/mypy/typeshed/stdlib/dbm/ndbm.pyi @@ -1,3 +1,4 @@ +from _typeshed import Self from types import TracebackType from typing import List, Optional, Type, TypeVar, Union, overload @@ -17,7 +18,7 @@ class _dbm: def __delitem__(self, key: _KeyType) -> None: ... def __len__(self) -> int: ... def __del__(self) -> None: ... - def __enter__(self) -> _dbm: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> None: ... diff --git a/mypy/typeshed/stdlib/distutils/util.pyi b/mypy/typeshed/stdlib/distutils/util.pyi index 0086d726af65..9b0915570ece 100644 --- a/mypy/typeshed/stdlib/distutils/util.pyi +++ b/mypy/typeshed/stdlib/distutils/util.pyi @@ -1,23 +1,45 @@ -from typing import Any, Callable, List, Mapping, Optional, Tuple +from _typeshed import StrPath +from collections.abc import Callable, Container, Iterable, Mapping +from typing import Any, Tuple def get_platform() -> str: ... def convert_path(pathname: str) -> str: ... def change_root(new_root: str, pathname: str) -> str: ... def check_environ() -> None: ... def subst_vars(s: str, local_vars: Mapping[str, str]) -> None: ... -def split_quoted(s: str) -> List[str]: ... +def split_quoted(s: str) -> list[str]: ... def execute( - func: Callable[..., None], args: Tuple[Any, ...], msg: Optional[str] = ..., verbose: bool = ..., dry_run: bool = ... + func: Callable[..., None], args: Tuple[Any, ...], msg: str | None = ..., verbose: bool = ..., dry_run: bool = ... ) -> None: ... def strtobool(val: str) -> bool: ... def byte_compile( - py_files: List[str], + py_files: list[str], optimize: int = ..., force: bool = ..., - prefix: Optional[str] = ..., - base_dir: Optional[str] = ..., + prefix: str | None = ..., + base_dir: str | None = ..., verbose: bool = ..., dry_run: bool = ..., - direct: Optional[bool] = ..., + direct: bool | None = ..., ) -> None: ... def rfc822_escape(header: str) -> str: ... +def run_2to3( + files: Iterable[str], + fixer_names: Iterable[str] | None = ..., + options: Mapping[str, Any] | None = ..., + explicit: Container[str] | None = ..., # unused +) -> None: ... +def copydir_run_2to3( + src: StrPath, + dest: StrPath, + template: str | None = ..., + fixer_names: Iterable[str] | None = ..., + options: Mapping[str, Any] | None = ..., + explicit: Container[str] | None = ..., +) -> list[str]: ... + +class Mixin2to3: + fixer_names: Iterable[str] | None + options: Mapping[str, Any] | None + explicit: Container[str] | None + def run_2to3(self, files: Iterable[str]) -> None: ... diff --git a/mypy/typeshed/stdlib/enum.pyi b/mypy/typeshed/stdlib/enum.pyi index b5549253afc7..1ab8ea5a0553 100644 --- a/mypy/typeshed/stdlib/enum.pyi +++ b/mypy/typeshed/stdlib/enum.pyi @@ -58,6 +58,8 @@ class auto(IntFlag): def __new__(cls: Type[_T]) -> _T: ... class Flag(Enum): + name: str | None # type: ignore + value: int def __contains__(self: _T, other: _T) -> bool: ... def __repr__(self) -> str: ... def __str__(self) -> str: ... diff --git a/mypy/typeshed/stdlib/fileinput.pyi b/mypy/typeshed/stdlib/fileinput.pyi index ed07ebecde86..9614ce10892c 100644 --- a/mypy/typeshed/stdlib/fileinput.pyi +++ b/mypy/typeshed/stdlib/fileinput.pyi @@ -1,8 +1,20 @@ import sys -from _typeshed import StrOrBytesPath -from typing import IO, Any, AnyStr, Callable, Generic, Iterable, Iterator, Optional, Union +from _typeshed import Self, StrOrBytesPath +from typing import IO, Any, AnyStr, Callable, Generic, Iterable, Iterator, Union -if sys.version_info >= (3, 8): +if sys.version_info >= (3, 10): + def input( + files: Union[StrOrBytesPath, Iterable[StrOrBytesPath], None] = ..., + inplace: bool = ..., + backup: str = ..., + *, + mode: str = ..., + openhook: Callable[[StrOrBytesPath, str], IO[AnyStr]] = ..., + encoding: str | None = ..., + errors: str | None = ..., + ) -> FileInput[AnyStr]: ... + +elif sys.version_info >= (3, 8): def input( files: Union[StrOrBytesPath, Iterable[StrOrBytesPath], None] = ..., inplace: bool = ..., @@ -32,7 +44,19 @@ def isfirstline() -> bool: ... def isstdin() -> bool: ... class FileInput(Iterable[AnyStr], Generic[AnyStr]): - if sys.version_info >= (3, 8): + if sys.version_info >= (3, 10): + def __init__( + self, + files: Union[None, StrOrBytesPath, Iterable[StrOrBytesPath]] = ..., + inplace: bool = ..., + backup: str = ..., + *, + mode: str = ..., + openhook: Callable[[StrOrBytesPath, str], IO[AnyStr]] = ..., + encoding: str | None = ..., + errors: str | None = ..., + ) -> None: ... + elif sys.version_info >= (3, 8): def __init__( self, files: Union[None, StrOrBytesPath, Iterable[StrOrBytesPath]] = ..., @@ -54,7 +78,7 @@ class FileInput(Iterable[AnyStr], Generic[AnyStr]): ) -> None: ... def __del__(self) -> None: ... def close(self) -> None: ... - def __enter__(self) -> FileInput[AnyStr]: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, type: Any, value: Any, traceback: Any) -> None: ... def __iter__(self) -> Iterator[AnyStr]: ... def __next__(self) -> AnyStr: ... @@ -68,5 +92,12 @@ class FileInput(Iterable[AnyStr], Generic[AnyStr]): def isfirstline(self) -> bool: ... def isstdin(self) -> bool: ... -def hook_compressed(filename: StrOrBytesPath, mode: str) -> IO[Any]: ... -def hook_encoded(encoding: str, errors: Optional[str] = ...) -> Callable[[StrOrBytesPath, str], IO[Any]]: ... +if sys.version_info >= (3, 10): + def hook_compressed( + filename: StrOrBytesPath, mode: str, *, encoding: str | None = ..., errors: str | None = ... + ) -> IO[Any]: ... + +else: + def hook_compressed(filename: StrOrBytesPath, mode: str) -> IO[Any]: ... + +def hook_encoded(encoding: str, errors: str | None = ...) -> Callable[[StrOrBytesPath, str], IO[Any]]: ... diff --git a/mypy/typeshed/stdlib/ftplib.pyi b/mypy/typeshed/stdlib/ftplib.pyi index c474da2e3a37..ba2c458c4a46 100644 --- a/mypy/typeshed/stdlib/ftplib.pyi +++ b/mypy/typeshed/stdlib/ftplib.pyi @@ -1,12 +1,10 @@ -from _typeshed import SupportsRead, SupportsReadline +from _typeshed import Self, SupportsRead, SupportsReadline from socket import socket from ssl import SSLContext from types import TracebackType -from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional, TextIO, Tuple, Type, TypeVar, Union +from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional, TextIO, Tuple, Type, Union from typing_extensions import Literal -_T = TypeVar("_T") - MSG_OOB: int FTP_PORT: int MAXLINE: int @@ -34,7 +32,7 @@ class FTP: lastresp: str file: Optional[TextIO] encoding: str - def __enter__(self: _T) -> _T: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> None: ... diff --git a/mypy/typeshed/stdlib/http/client.pyi b/mypy/typeshed/stdlib/http/client.pyi index c35228928d77..59e64d873e23 100644 --- a/mypy/typeshed/stdlib/http/client.pyi +++ b/mypy/typeshed/stdlib/http/client.pyi @@ -3,7 +3,7 @@ import io import ssl import sys import types -from _typeshed import WriteableBuffer +from _typeshed import Self, WriteableBuffer from socket import socket from typing import ( IO, @@ -90,7 +90,8 @@ NETWORK_AUTHENTICATION_REQUIRED: int responses: Dict[int, str] -class HTTPMessage(email.message.Message): ... +class HTTPMessage(email.message.Message): + def getallmatchingheaders(self, name: str) -> list[str]: ... # undocumented def parse_headers(fp: io.BufferedIOBase, _class: Callable[[], email.message.Message] = ...) -> HTTPMessage: ... @@ -103,6 +104,7 @@ class HTTPResponse(io.BufferedIOBase, BinaryIO): status: int reason: str def __init__(self, sock: socket, debuglevel: int = ..., method: Optional[str] = ..., url: Optional[str] = ...) -> None: ... + def peek(self, n: int = ...) -> bytes: ... def read(self, amt: Optional[int] = ...) -> bytes: ... def read1(self, n: int = ...) -> bytes: ... def readinto(self, b: WriteableBuffer) -> int: ... @@ -115,7 +117,7 @@ class HTTPResponse(io.BufferedIOBase, BinaryIO): def fileno(self) -> int: ... def isclosed(self) -> bool: ... def __iter__(self) -> Iterator[bytes]: ... - def __enter__(self) -> HTTPResponse: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[types.TracebackType] ) -> Optional[bool]: ... @@ -142,6 +144,10 @@ class _HTTPConnectionProtocol(Protocol): ) -> HTTPConnection: ... class HTTPConnection: + auto_open: int = ... # undocumented + debuglevel: int = ... + default_port: int = ... # undocumented + response_class: Type[HTTPResponse] = ... # undocumented timeout: Optional[float] host: str port: int diff --git a/mypy/typeshed/stdlib/http/cookiejar.pyi b/mypy/typeshed/stdlib/http/cookiejar.pyi index 094cebe49ca0..685717af7032 100644 --- a/mypy/typeshed/stdlib/http/cookiejar.pyi +++ b/mypy/typeshed/stdlib/http/cookiejar.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import StrPath from http.client import HTTPResponse -from typing import Dict, Iterable, Iterator, Optional, Sequence, Tuple, TypeVar, Union, overload +from typing import ClassVar, Dict, Iterable, Iterator, Optional, Pattern, Sequence, Tuple, TypeVar, Union, overload from urllib.request import Request _T = TypeVar("_T") @@ -9,6 +9,12 @@ _T = TypeVar("_T") class LoadError(OSError): ... class CookieJar(Iterable[Cookie]): + non_word_re: ClassVar[Pattern[str]] = ... # undocumented + quote_re: ClassVar[Pattern[str]] = ... # undocumented + strict_domain_re: ClassVar[Pattern[str]] = ... # undocumented + domain_re: ClassVar[Pattern[str]] = ... # undocumented + dots_re: ClassVar[Pattern[str]] = ... # undocumented + magic_re: ClassVar[Pattern[str]] = ... # undocumented def __init__(self, policy: Optional[CookiePolicy] = ...) -> None: ... def add_cookie_header(self, request: Request) -> None: ... def extract_cookies(self, response: HTTPResponse, request: Request) -> None: ... @@ -18,8 +24,11 @@ class CookieJar(Iterable[Cookie]): def set_cookie_if_ok(self, cookie: Cookie, request: Request) -> None: ... def clear(self, domain: Optional[str] = ..., path: Optional[str] = ..., name: Optional[str] = ...) -> None: ... def clear_session_cookies(self) -> None: ... + def clear_expired_cookies(self) -> None: ... # undocumented def __iter__(self) -> Iterator[Cookie]: ... def __len__(self) -> int: ... + def __repr__(self) -> str: ... + def __str__(self) -> str: ... class FileCookieJar(CookieJar): filename: str @@ -36,7 +45,8 @@ class FileCookieJar(CookieJar): def load(self, filename: Optional[str] = ..., ignore_discard: bool = ..., ignore_expires: bool = ...) -> None: ... def revert(self, filename: Optional[str] = ..., ignore_discard: bool = ..., ignore_expires: bool = ...) -> None: ... -class MozillaCookieJar(FileCookieJar): ... +class MozillaCookieJar(FileCookieJar): + header: ClassVar[str] = ... # undocumented class LWPCookieJar(FileCookieJar): def as_lwp_str(self, ignore_discard: bool = ..., ignore_expires: bool = ...) -> str: ... # undocumented @@ -58,11 +68,11 @@ class DefaultCookiePolicy(CookiePolicy): strict_ns_domain: int strict_ns_set_initial_dollar: bool strict_ns_set_path: bool - DomainStrictNoDots: int - DomainStrictNonDomain: int - DomainRFC2965Match: int - DomainLiberal: int - DomainStrict: int + DomainStrictNoDots: ClassVar[int] + DomainStrictNonDomain: ClassVar[int] + DomainRFC2965Match: ClassVar[int] + DomainLiberal: ClassVar[int] + DomainStrict: ClassVar[int] if sys.version_info >= (3, 8): def __init__( self, @@ -102,6 +112,18 @@ class DefaultCookiePolicy(CookiePolicy): def allowed_domains(self) -> Optional[Tuple[str, ...]]: ... def set_allowed_domains(self, allowed_domains: Optional[Sequence[str]]) -> None: ... def is_not_allowed(self, domain: str) -> bool: ... + def set_ok_version(self, cookie: Cookie, request: Request) -> bool: ... # undocumented + def set_ok_verifiability(self, cookie: Cookie, request: Request) -> bool: ... # undocumented + def set_ok_name(self, cookie: Cookie, request: Request) -> bool: ... # undocumented + def set_ok_path(self, cookie: Cookie, request: Request) -> bool: ... # undocumented + def set_ok_domain(self, cookie: Cookie, request: Request) -> bool: ... # undocumented + def set_ok_port(self, cookie: Cookie, request: Request) -> bool: ... # undocumented + def return_ok_version(self, cookie: Cookie, request: Request) -> bool: ... # undocumented + def return_ok_verifiability(self, cookie: Cookie, request: Request) -> bool: ... # undocumented + def return_ok_secure(self, cookie: Cookie, request: Request) -> bool: ... # undocumented + def return_ok_expires(self, cookie: Cookie, request: Request) -> bool: ... # undocumented + def return_ok_port(self, cookie: Cookie, request: Request) -> bool: ... # undocumented + def return_ok_domain(self, cookie: Cookie, request: Request) -> bool: ... # undocumented class Cookie: version: Optional[int] diff --git a/mypy/typeshed/stdlib/http/server.pyi b/mypy/typeshed/stdlib/http/server.pyi index 5d06bd5c700f..bd97fe165c04 100644 --- a/mypy/typeshed/stdlib/http/server.pyi +++ b/mypy/typeshed/stdlib/http/server.pyi @@ -1,8 +1,9 @@ import email.message +import io import socketserver import sys -from _typeshed import StrPath -from typing import Any, ClassVar, Dict, List, Mapping, Optional, Sequence, Tuple, Union +from _typeshed import StrPath, SupportsRead, SupportsWrite +from typing import Any, AnyStr, BinaryIO, ClassVar, Dict, List, Mapping, Optional, Sequence, Tuple, Union class HTTPServer(socketserver.TCPServer): server_name: str @@ -28,6 +29,7 @@ class BaseHTTPRequestHandler(socketserver.StreamRequestHandler): protocol_version: str MessageClass: type responses: Mapping[int, Tuple[str, str]] + default_request_version: str # undocumented weekdayname: ClassVar[Sequence[str]] = ... # Undocumented monthname: ClassVar[Sequence[Optional[str]]] = ... # Undocumented def __init__(self, request: bytes, client_address: Tuple[str, int], server: socketserver.BaseServer) -> None: ... @@ -50,20 +52,29 @@ class BaseHTTPRequestHandler(socketserver.StreamRequestHandler): def parse_request(self) -> bool: ... # Undocumented class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): + server_version: str extensions_map: Dict[str, str] if sys.version_info >= (3, 7): def __init__( - self, - request: bytes, - client_address: Tuple[str, int], - server: socketserver.BaseServer, - directory: Optional[StrPath] = ..., + self, request: bytes, client_address: Tuple[str, int], server: socketserver.BaseServer, directory: str | None = ... ) -> None: ... else: def __init__(self, request: bytes, client_address: Tuple[str, int], server: socketserver.BaseServer) -> None: ... def do_GET(self) -> None: ... def do_HEAD(self) -> None: ... + def send_head(self) -> io.BytesIO | BinaryIO | None: ... # undocumented + def list_directory(self, path: StrPath) -> io.BytesIO | None: ... # undocumented + def translate_path(self, path: str) -> str: ... # undocumented + def copyfile(self, source: SupportsRead[AnyStr], outputfile: SupportsWrite[AnyStr]) -> None: ... # undocumented + def guess_type(self, path: StrPath) -> str: ... # undocumented + +def executable(path: StrPath) -> bool: ... # undocumented class CGIHTTPRequestHandler(SimpleHTTPRequestHandler): cgi_directories: List[str] + have_fork: bool # undocumented def do_POST(self) -> None: ... + def is_cgi(self) -> bool: ... # undocumented + def is_executable(self, path: StrPath) -> bool: ... # undocumented + def is_python(self, path: StrPath) -> bool: ... # undocumented + def run_cgi(self) -> None: ... # undocumented diff --git a/mypy/typeshed/stdlib/imaplib.pyi b/mypy/typeshed/stdlib/imaplib.pyi index 9fc3a740c463..8ad242cca0f7 100644 --- a/mypy/typeshed/stdlib/imaplib.pyi +++ b/mypy/typeshed/stdlib/imaplib.pyi @@ -1,6 +1,7 @@ import subprocess import sys import time +from _typeshed import Self from socket import socket as _socket from ssl import SSLContext, SSLSocket from types import TracebackType @@ -59,7 +60,7 @@ class IMAP4: def delete(self, mailbox: str) -> _CommandResults: ... def deleteacl(self, mailbox: str, who: str) -> _CommandResults: ... def enable(self, capability: str) -> _CommandResults: ... - def __enter__(self) -> IMAP4: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, t: Optional[Type[BaseException]], v: Optional[BaseException], tb: Optional[TracebackType]) -> None: ... def expunge(self) -> _CommandResults: ... def fetch(self, message_set: str, message_parts: str) -> Tuple[str, _AnyResponseData]: ... diff --git a/mypy/typeshed/stdlib/importlib/metadata.pyi b/mypy/typeshed/stdlib/importlib/metadata.pyi index 47c2825b70bf..90d1062583d9 100644 --- a/mypy/typeshed/stdlib/importlib/metadata.pyi +++ b/mypy/typeshed/stdlib/importlib/metadata.pyi @@ -2,12 +2,16 @@ import abc import pathlib import sys from _typeshed import StrPath +from collections.abc import Mapping from email.message import Message from importlib.abc import MetaPathFinder from os import PathLike from pathlib import Path from typing import Any, Dict, Iterable, List, NamedTuple, Optional, Tuple, overload +if sys.version_info >= (3, 10): + def packages_distributions() -> Mapping[str, List[str]]: ... + if sys.version_info >= (3, 8): class PackageNotFoundError(ModuleNotFoundError): ... class _EntryPointBase(NamedTuple): diff --git a/mypy/typeshed/stdlib/importlib/util.pyi b/mypy/typeshed/stdlib/importlib/util.pyi index 7dea5a718179..0fb786e9361c 100644 --- a/mypy/typeshed/stdlib/importlib/util.pyi +++ b/mypy/typeshed/stdlib/importlib/util.pyi @@ -7,7 +7,7 @@ from typing import Any, Callable, List, Optional def module_for_loader(fxn: Callable[..., types.ModuleType]) -> Callable[..., types.ModuleType]: ... def set_loader(fxn: Callable[..., types.ModuleType]) -> Callable[..., types.ModuleType]: ... def set_package(fxn: Callable[..., types.ModuleType]) -> Callable[..., types.ModuleType]: ... -def resolve_name(name: str, package: str) -> str: ... +def resolve_name(name: str, package: str | None) -> str: ... MAGIC_NUMBER: bytes diff --git a/mypy/typeshed/stdlib/inspect.pyi b/mypy/typeshed/stdlib/inspect.pyi index fa49e4493b28..18038ad999b0 100644 --- a/mypy/typeshed/stdlib/inspect.pyi +++ b/mypy/typeshed/stdlib/inspect.pyi @@ -1,24 +1,22 @@ import enum import sys +from _typeshed import Self from collections import OrderedDict -from types import CodeType, FrameType, FunctionType, MethodType, ModuleType, TracebackType -from typing import ( - AbstractSet, - Any, - Callable, - ClassVar, - Dict, - Generator, - List, - Mapping, - NamedTuple, - Optional, - Sequence, - Tuple, - Type, - Union, +from collections.abc import Awaitable, Callable, Generator, Mapping, Sequence, Set +from types import ( + AsyncGeneratorType, + BuiltinFunctionType, + CodeType, + CoroutineType, + FrameType, + FunctionType, + GeneratorType, + MethodType, + ModuleType, + TracebackType, ) -from typing_extensions import Literal +from typing import Any, ClassVar, NamedTuple, Optional, Tuple, Type, Union +from typing_extensions import Literal, TypeGuard # # Types and members @@ -47,12 +45,14 @@ CO_ITERABLE_COROUTINE: int CO_ASYNC_GENERATOR: int TPFLAGS_IS_ABSTRACT: int -def getmembers(object: object, predicate: Optional[Callable[[Any], bool]] = ...) -> List[Tuple[str, Any]]: ... +def getmembers(object: object, predicate: Optional[Callable[[Any], bool]] = ...) -> list[Tuple[str, Any]]: ... def getmodulename(path: str) -> Optional[str]: ... -def ismodule(object: object) -> bool: ... +def ismodule(object: object) -> TypeGuard[ModuleType]: ... + +# TODO: use TypeGuard[Type[Any]] after python/mypy#10486 is resolved def isclass(object: object) -> bool: ... -def ismethod(object: object) -> bool: ... -def isfunction(object: object) -> bool: ... +def ismethod(object: object) -> TypeGuard[MethodType]: ... +def isfunction(object: object) -> TypeGuard[FunctionType]: ... if sys.version_info >= (3, 8): def isgeneratorfunction(obj: object) -> bool: ... @@ -62,9 +62,9 @@ else: def isgeneratorfunction(object: object) -> bool: ... def iscoroutinefunction(object: object) -> bool: ... -def isgenerator(object: object) -> bool: ... -def iscoroutine(object: object) -> bool: ... -def isawaitable(object: object) -> bool: ... +def isgenerator(object: object) -> TypeGuard[GeneratorType[Any, Any, Any]]: ... +def iscoroutine(object: object) -> TypeGuard[CoroutineType]: ... +def isawaitable(object: object) -> TypeGuard[Awaitable[Any]]: ... if sys.version_info >= (3, 8): def isasyncgenfunction(obj: object) -> bool: ... @@ -72,11 +72,11 @@ if sys.version_info >= (3, 8): else: def isasyncgenfunction(object: object) -> bool: ... -def isasyncgen(object: object) -> bool: ... -def istraceback(object: object) -> bool: ... -def isframe(object: object) -> bool: ... -def iscode(object: object) -> bool: ... -def isbuiltin(object: object) -> bool: ... +def isasyncgen(object: object) -> TypeGuard[AsyncGeneratorType[Any, Any]]: ... +def istraceback(object: object) -> TypeGuard[TracebackType]: ... +def isframe(object: object) -> TypeGuard[FrameType]: ... +def iscode(object: object) -> TypeGuard[CodeType]: ... +def isbuiltin(object: object) -> TypeGuard[BuiltinFunctionType]: ... def isroutine(object: object) -> bool: ... def isabstract(object: object) -> bool: ... def ismethoddescriptor(object: object) -> bool: ... @@ -89,7 +89,7 @@ def ismemberdescriptor(object: object) -> bool: ... # _SourceObjectType = Union[ModuleType, Type[Any], MethodType, FunctionType, TracebackType, FrameType, CodeType, Callable[..., Any]] -def findsource(object: _SourceObjectType) -> Tuple[List[str], int]: ... +def findsource(object: _SourceObjectType) -> Tuple[list[str], int]: ... def getabsfile(object: _SourceObjectType, _filename: Optional[str] = ...) -> str: ... def getblock(lines: Sequence[str]) -> Sequence[str]: ... def getdoc(object: object) -> Optional[str]: ... @@ -97,7 +97,7 @@ def getcomments(object: object) -> Optional[str]: ... def getfile(object: _SourceObjectType) -> str: ... def getmodule(object: object, _filename: Optional[str] = ...) -> Optional[ModuleType]: ... def getsourcefile(object: _SourceObjectType) -> Optional[str]: ... -def getsourcelines(object: _SourceObjectType) -> Tuple[List[str], int]: ... +def getsourcelines(object: _SourceObjectType) -> Tuple[list[str], int]: ... def getsource(object: _SourceObjectType) -> str: ... def cleandoc(doc: str) -> str: ... def indentsize(line: str) -> int: ... @@ -129,7 +129,7 @@ class Signature: return_annotation: Any def bind(self, *args: Any, **kwargs: Any) -> BoundArguments: ... def bind_partial(self, *args: Any, **kwargs: Any) -> BoundArguments: ... - def replace(self, *, parameters: Optional[Sequence[Parameter]] = ..., return_annotation: Any = ...) -> Signature: ... + def replace(self: Self, *, parameters: Optional[Sequence[Parameter]] = ..., return_annotation: Any = ...) -> Self: ... if sys.version_info >= (3, 10): @classmethod def from_callable( @@ -152,7 +152,7 @@ if sys.version_info >= (3, 10): globals: Optional[Mapping[str, Any]] = ..., locals: Optional[Mapping[str, Any]] = ..., eval_str: bool = ..., - ) -> Dict[str, Any]: ... + ) -> dict[str, Any]: ... # The name is the same as the enum's name in CPython class _ParameterKind(enum.IntEnum): @@ -179,13 +179,13 @@ class Parameter: KEYWORD_ONLY: ClassVar[Literal[_ParameterKind.KEYWORD_ONLY]] VAR_KEYWORD: ClassVar[Literal[_ParameterKind.VAR_KEYWORD]] def replace( - self, *, name: Optional[str] = ..., kind: Optional[_ParameterKind] = ..., default: Any = ..., annotation: Any = ... - ) -> Parameter: ... + self: Self, *, name: Optional[str] = ..., kind: Optional[_ParameterKind] = ..., default: Any = ..., annotation: Any = ... + ) -> Self: ... class BoundArguments: arguments: OrderedDict[str, Any] args: Tuple[Any, ...] - kwargs: Dict[str, Any] + kwargs: dict[str, Any] signature: Signature def __init__(self, signature: Signature, arguments: OrderedDict[str, Any]) -> None: ... def apply_defaults(self) -> None: ... @@ -194,20 +194,20 @@ class BoundArguments: # Classes and functions # -# TODO: The actual return type should be List[_ClassTreeItem] but mypy doesn't +# TODO: The actual return type should be list[_ClassTreeItem] but mypy doesn't # seem to be supporting this at the moment: -# _ClassTreeItem = Union[List[_ClassTreeItem], Tuple[type, Tuple[type, ...]]] -def getclasstree(classes: List[type], unique: bool = ...) -> List[Any]: ... -def walktree(classes: List[type], children: Dict[Type[Any], List[type]], parent: Optional[Type[Any]]) -> List[Any]: ... +# _ClassTreeItem = Union[list[_ClassTreeItem], Tuple[type, Tuple[type, ...]]] +def getclasstree(classes: list[type], unique: bool = ...) -> list[Any]: ... +def walktree(classes: list[type], children: dict[Type[Any], list[type]], parent: Optional[Type[Any]]) -> list[Any]: ... class ArgSpec(NamedTuple): - args: List[str] + args: list[str] varargs: Optional[str] keywords: Optional[str] defaults: Tuple[Any, ...] class Arguments(NamedTuple): - args: List[str] + args: list[str] varargs: Optional[str] varkw: Optional[str] @@ -215,33 +215,33 @@ def getargs(co: CodeType) -> Arguments: ... def getargspec(func: object) -> ArgSpec: ... class FullArgSpec(NamedTuple): - args: List[str] + args: list[str] varargs: Optional[str] varkw: Optional[str] defaults: Optional[Tuple[Any, ...]] - kwonlyargs: List[str] - kwonlydefaults: Optional[Dict[str, Any]] - annotations: Dict[str, Any] + kwonlyargs: list[str] + kwonlydefaults: Optional[dict[str, Any]] + annotations: dict[str, Any] def getfullargspec(func: object) -> FullArgSpec: ... class ArgInfo(NamedTuple): - args: List[str] + args: list[str] varargs: Optional[str] keywords: Optional[str] - locals: Dict[str, Any] + locals: dict[str, Any] def getargvalues(frame: FrameType) -> ArgInfo: ... def formatannotation(annotation: object, base_module: Optional[str] = ...) -> str: ... def formatannotationrelativeto(object: object) -> Callable[[object], str]: ... def formatargspec( - args: List[str], + args: list[str], varargs: Optional[str] = ..., varkw: Optional[str] = ..., defaults: Optional[Tuple[Any, ...]] = ..., kwonlyargs: Optional[Sequence[str]] = ..., - kwonlydefaults: Optional[Dict[str, Any]] = ..., - annotations: Dict[str, Any] = ..., + kwonlydefaults: Optional[dict[str, Any]] = ..., + annotations: dict[str, Any] = ..., formatarg: Callable[[str], str] = ..., formatvarargs: Callable[[str], str] = ..., formatvarkw: Callable[[str], str] = ..., @@ -250,23 +250,23 @@ def formatargspec( formatannotation: Callable[[Any], str] = ..., ) -> str: ... def formatargvalues( - args: List[str], + args: list[str], varargs: Optional[str], varkw: Optional[str], - locals: Optional[Dict[str, Any]], + locals: Optional[dict[str, Any]], formatarg: Optional[Callable[[str], str]] = ..., formatvarargs: Optional[Callable[[str], str]] = ..., formatvarkw: Optional[Callable[[str], str]] = ..., formatvalue: Optional[Callable[[Any], str]] = ..., ) -> str: ... def getmro(cls: type) -> Tuple[type, ...]: ... -def getcallargs(__func: Callable[..., Any], *args: Any, **kwds: Any) -> Dict[str, Any]: ... +def getcallargs(__func: Callable[..., Any], *args: Any, **kwds: Any) -> dict[str, Any]: ... class ClosureVars(NamedTuple): nonlocals: Mapping[str, Any] globals: Mapping[str, Any] builtins: Mapping[str, Any] - unbound: AbstractSet[str] + unbound: Set[str] def getclosurevars(func: Callable[..., Any]) -> ClosureVars: ... def unwrap(func: Callable[..., Any], *, stop: Optional[Callable[[Any], Any]] = ...) -> Any: ... @@ -279,7 +279,7 @@ class Traceback(NamedTuple): filename: str lineno: int function: str - code_context: Optional[List[str]] + code_context: Optional[list[str]] index: Optional[int] # type: ignore class FrameInfo(NamedTuple): @@ -287,16 +287,16 @@ class FrameInfo(NamedTuple): filename: str lineno: int function: str - code_context: Optional[List[str]] + code_context: Optional[list[str]] index: Optional[int] # type: ignore def getframeinfo(frame: Union[FrameType, TracebackType], context: int = ...) -> Traceback: ... -def getouterframes(frame: Any, context: int = ...) -> List[FrameInfo]: ... -def getinnerframes(tb: TracebackType, context: int = ...) -> List[FrameInfo]: ... +def getouterframes(frame: Any, context: int = ...) -> list[FrameInfo]: ... +def getinnerframes(tb: TracebackType, context: int = ...) -> list[FrameInfo]: ... def getlineno(frame: FrameType) -> int: ... def currentframe() -> Optional[FrameType]: ... -def stack(context: int = ...) -> List[FrameInfo]: ... -def trace(context: int = ...) -> List[FrameInfo]: ... +def stack(context: int = ...) -> list[FrameInfo]: ... +def trace(context: int = ...) -> list[FrameInfo]: ... # # Fetching attributes statically @@ -324,10 +324,10 @@ CORO_SUSPENDED: str CORO_CLOSED: str # TODO can we be more specific than "object"? def getcoroutinestate(coroutine: object) -> str: ... -def getgeneratorlocals(generator: Generator[Any, Any, Any]) -> Dict[str, Any]: ... +def getgeneratorlocals(generator: Generator[Any, Any, Any]) -> dict[str, Any]: ... # TODO can we be more specific than "object"? -def getcoroutinelocals(coroutine: object) -> Dict[str, Any]: ... +def getcoroutinelocals(coroutine: object) -> dict[str, Any]: ... # Create private type alias to avoid conflict with symbol of same # name created in Attribute class. @@ -339,7 +339,7 @@ class Attribute(NamedTuple): defining_class: type object: _Object -def classify_class_attrs(cls: type) -> List[Attribute]: ... +def classify_class_attrs(cls: type) -> list[Attribute]: ... if sys.version_info >= (3, 9): class ClassFoundException(Exception): ... diff --git a/mypy/typeshed/stdlib/io.pyi b/mypy/typeshed/stdlib/io.pyi index f03a9a8740fe..5092d0ee39d1 100644 --- a/mypy/typeshed/stdlib/io.pyi +++ b/mypy/typeshed/stdlib/io.pyi @@ -1,9 +1,10 @@ import builtins import codecs import sys -from _typeshed import ReadableBuffer, WriteableBuffer +from _typeshed import ReadableBuffer, Self, StrOrBytesPath, WriteableBuffer +from os import _Opener from types import TracebackType -from typing import IO, Any, BinaryIO, Callable, Iterable, Iterator, List, Optional, TextIO, Tuple, Type, TypeVar, Union +from typing import IO, Any, BinaryIO, Callable, Iterable, Iterator, List, Optional, TextIO, Tuple, Type, Union DEFAULT_BUFFER_SIZE: int @@ -11,8 +12,6 @@ SEEK_SET: int SEEK_CUR: int SEEK_END: int -_T = TypeVar("_T", bound=IOBase) - open = builtins.open if sys.version_info >= (3, 8): @@ -25,7 +24,7 @@ class UnsupportedOperation(OSError, ValueError): ... class IOBase: def __iter__(self) -> Iterator[bytes]: ... def __next__(self) -> bytes: ... - def __enter__(self: _T) -> _T: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> Optional[bool]: ... @@ -66,20 +65,15 @@ class BufferedIOBase(IOBase): class FileIO(RawIOBase, BinaryIO): mode: str - # Technically this is whatever is passed in as file, either a str, a bytes, or an int. - name: Union[int, str] # type: ignore + name: StrOrBytesPath | int # type: ignore def __init__( - self, - file: Union[str, bytes, int], - mode: str = ..., - closefd: bool = ..., - opener: Optional[Callable[[Union[int, str], str], int]] = ..., + self, file: StrOrBytesPath | int, mode: str = ..., closefd: bool = ..., opener: _Opener | None = ... ) -> None: ... @property def closefd(self) -> bool: ... def write(self, __b: ReadableBuffer) -> int: ... def read(self, __size: int = ...) -> bytes: ... - def __enter__(self: _T) -> _T: ... + def __enter__(self: Self) -> Self: ... class BytesIO(BufferedIOBase, BinaryIO): def __init__(self, initial_bytes: bytes = ...) -> None: ... @@ -87,7 +81,7 @@ class BytesIO(BufferedIOBase, BinaryIO): # to allow BytesIO sub-classes to add this field, as it is defined # as a read-only property on IO[]. name: Any - def __enter__(self: _T) -> _T: ... + def __enter__(self: Self) -> Self: ... def getvalue(self) -> bytes: ... def getbuffer(self) -> memoryview: ... if sys.version_info >= (3, 7): @@ -96,7 +90,7 @@ class BytesIO(BufferedIOBase, BinaryIO): def read1(self, __size: Optional[int]) -> bytes: ... # type: ignore class BufferedReader(BufferedIOBase, BinaryIO): - def __enter__(self: _T) -> _T: ... + def __enter__(self: Self) -> Self: ... def __init__(self, raw: RawIOBase, buffer_size: int = ...) -> None: ... def peek(self, __size: int = ...) -> bytes: ... if sys.version_info >= (3, 7): @@ -105,12 +99,12 @@ class BufferedReader(BufferedIOBase, BinaryIO): def read1(self, __size: int) -> bytes: ... # type: ignore class BufferedWriter(BufferedIOBase, BinaryIO): - def __enter__(self: _T) -> _T: ... + def __enter__(self: Self) -> Self: ... def __init__(self, raw: RawIOBase, buffer_size: int = ...) -> None: ... def write(self, __buffer: ReadableBuffer) -> int: ... class BufferedRandom(BufferedReader, BufferedWriter): - def __enter__(self: _T) -> _T: ... + def __enter__(self: Self) -> Self: ... def __init__(self, raw: RawIOBase, buffer_size: int = ...) -> None: ... def seek(self, __target: int, __whence: int = ...) -> int: ... if sys.version_info >= (3, 7): @@ -165,7 +159,7 @@ class TextIOWrapper(TextIOBase, TextIO): write_through: Optional[bool] = ..., ) -> None: ... # These are inherited from TextIOBase, but must exist in the stub to satisfy mypy. - def __enter__(self: _T) -> _T: ... + def __enter__(self: Self) -> Self: ... def __iter__(self) -> Iterator[str]: ... # type: ignore def __next__(self) -> str: ... # type: ignore def writelines(self, __lines: Iterable[str]) -> None: ... # type: ignore diff --git a/mypy/typeshed/stdlib/json/encoder.pyi b/mypy/typeshed/stdlib/json/encoder.pyi index 7d520149ba4a..4155abd028dc 100644 --- a/mypy/typeshed/stdlib/json/encoder.pyi +++ b/mypy/typeshed/stdlib/json/encoder.pyi @@ -1,5 +1,8 @@ from typing import Any, Callable, Iterator, Optional, Tuple +def py_encode_basestring(s: str) -> str: ... # undocumented +def py_encode_basestring_ascii(s: str) -> str: ... # undocumented + class JSONEncoder: item_separator: str key_separator: str diff --git a/mypy/typeshed/stdlib/lib2to3/refactor.pyi b/mypy/typeshed/stdlib/lib2to3/refactor.pyi new file mode 100644 index 000000000000..6687092d862c --- /dev/null +++ b/mypy/typeshed/stdlib/lib2to3/refactor.pyi @@ -0,0 +1,70 @@ +from collections.abc import Container, Generator, Iterable, Mapping +from logging import Logger +from typing import Any, ClassVar, NoReturn + +from .pgen2.grammar import Grammar + +_Driver = Any # really lib2to3.driver.Driver +_BottomMatcher = Any # really lib2to3.btm_matcher.BottomMatcher + +def get_all_fix_names(fixer_pkg: str, remove_prefix: bool = ...) -> list[str]: ... +def get_fixers_from_package(pkg_name: str) -> list[str]: ... + +class FixerError(Exception): ... + +class RefactoringTool: + CLASS_PREFIX: ClassVar[str] + FILE_PREFIX: ClassVar[str] + fixers: Iterable[str] + explicit: Container[str] + options: dict[str, Any] + grammar: Grammar + write_unchanged_files: bool + errors: list[Any] + logger: Logger + fixer_log: list[Any] + wrote: bool + driver: _Driver + pre_order: Any + post_order: Any + files: list[Any] + BM: _BottomMatcher + bmi_pre_order: list[Any] + bmi_post_order: list[Any] + def __init__( + self, fixer_names: Iterable[str], options: Mapping[str, Any] | None = ..., explicit: Container[str] | None = ... + ) -> None: ... + def get_fixers(self) -> tuple[list[Any], list[Any]]: ... + def log_error(self, msg: str, *args: Any, **kwds: Any) -> NoReturn: ... + def log_message(self, msg: str, *args: Any) -> None: ... + def log_debug(self, msg: str, *args: Any) -> None: ... + def print_output(self, old_text: str, new_text: str, filename: str, equal): ... + def refactor(self, items: Iterable[str], write: bool = ..., doctests_only: bool = ...) -> None: ... + def refactor_dir(self, dir_name: str, write: bool = ..., doctests_only: bool = ...) -> None: ... + def _read_python_source(self, filename: str) -> tuple[str, str]: ... + def refactor_file(self, filename: str, write: bool = ..., doctests_only: bool = ...) -> None: ... + def refactor_string(self, data: str, name: str): ... + def refactor_stdin(self, doctests_only: bool = ...) -> None: ... + def refactor_tree(self, tree, name: str) -> bool: ... + def traverse_by(self, fixers, traversal) -> None: ... + def processed_file( + self, new_text: str, filename: str, old_text: str | None = ..., write: bool = ..., encoding: str | None = ... + ) -> None: ... + def write_file(self, new_text: str, filename: str, old_text: str, encoding: str | None = ...) -> None: ... + PS1: ClassVar[str] + PS2: ClassVar[str] + def refactor_docstring(self, input: str, filename: str) -> str: ... + def refactor_doctest(self, block: list[str], lineno: int, indent: int, filename: str) -> list[str]: ... + def summarize(self) -> None: ... + def parse_block(self, block: Iterable[str], lineno: int, indent: int): ... + def wrap_toks( + self, block: Iterable[str], lineno: int, indent: int + ) -> Generator[tuple[Any, Any, tuple[int, int], tuple[int, int], str], None, None]: ... + def gen_lines(self, block: Iterable[str], indent: int) -> Generator[str, None, None]: ... + +class MultiprocessingUnsupported(Exception): ... + +class MultiprocessRefactoringTool(RefactoringTool): + queue: Any | None + output_lock: Any | None + def refactor(self, items: Iterable[str], write: bool = ..., doctests_only: bool = ..., num_processes: int = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/logging/__init__.pyi b/mypy/typeshed/stdlib/logging/__init__.pyi index 1cce244e5798..f117175dec54 100644 --- a/mypy/typeshed/stdlib/logging/__init__.pyi +++ b/mypy/typeshed/stdlib/logging/__init__.pyi @@ -2,16 +2,19 @@ import sys import threading from _typeshed import StrPath, SupportsWrite from collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence +from io import TextIOWrapper from string import Template from time import struct_time from types import FrameType, TracebackType -from typing import IO, Any, ClassVar, Optional, Pattern, Tuple, Type, Union +from typing import Any, ClassVar, Generic, Optional, Pattern, TextIO, Tuple, Type, TypeVar, Union, overload +from typing_extensions import Literal _SysExcInfoType = Union[Tuple[Type[BaseException], BaseException, Optional[TracebackType]], Tuple[None, None, None]] _ExcInfoType = Union[None, bool, _SysExcInfoType, BaseException] _ArgsType = Union[Tuple[Any, ...], Mapping[str, Any]] _FilterType = Union[Filter, Callable[[LogRecord], int]] _Level = Union[int, str] +_FormatStyle = Literal["%", "{", "$"] raiseExceptions: bool logThreads: bool @@ -300,10 +303,10 @@ class Formatter: if sys.version_info >= (3, 8): def __init__( - self, fmt: Optional[str] = ..., datefmt: Optional[str] = ..., style: str = ..., validate: bool = ... + self, fmt: Optional[str] = ..., datefmt: Optional[str] = ..., style: _FormatStyle = ..., validate: bool = ... ) -> None: ... else: - def __init__(self, fmt: Optional[str] = ..., datefmt: Optional[str] = ..., style: str = ...) -> None: ... + def __init__(self, fmt: Optional[str] = ..., datefmt: Optional[str] = ..., style: _FormatStyle = ...) -> None: ... def format(self, record: LogRecord) -> str: ... def formatTime(self, record: LogRecord, datefmt: Optional[str] = ...) -> str: ... def formatException(self, ei: _SysExcInfoType) -> str: ... @@ -325,7 +328,9 @@ class Filter: def filter(self, record: LogRecord) -> bool: ... class LogRecord: - args: _ArgsType + # args can be set to None by logging.handlers.QueueHandler + # (see https://bugs.python.org/issue44473) + args: _ArgsType | None asctime: str created: float exc_info: Optional[_SysExcInfoType] @@ -354,7 +359,7 @@ class LogRecord: pathname: str, lineno: int, msg: Any, - args: _ArgsType, + args: _ArgsType | None, exc_info: Optional[_SysExcInfoType], func: Optional[str] = ..., sinfo: Optional[str] = ..., @@ -362,14 +367,14 @@ class LogRecord: def getMessage(self) -> str: ... class LoggerAdapter: - logger: Logger + logger: Logger | LoggerAdapter manager: Manager # undocumented if sys.version_info >= (3, 10): extra: Optional[Mapping[str, Any]] - def __init__(self, logger: Logger, extra: Optional[Mapping[str, Any]]) -> None: ... + def __init__(self, logger: Logger | LoggerAdapter, extra: Optional[Mapping[str, Any]]) -> None: ... else: extra: Mapping[str, Any] - def __init__(self, logger: Logger, extra: Mapping[str, Any]) -> None: ... + def __init__(self, logger: Logger | LoggerAdapter, extra: Mapping[str, Any]) -> None: ... def process(self, msg: Any, kwargs: MutableMapping[str, Any]) -> tuple[Any, MutableMapping[str, Any]]: ... if sys.version_info >= (3, 8): def debug( @@ -701,14 +706,30 @@ def addLevelName(level: int, levelName: str) -> None: ... def getLevelName(level: _Level) -> Any: ... def makeLogRecord(dict: Mapping[str, Any]) -> LogRecord: ... -if sys.version_info >= (3, 8): +if sys.version_info >= (3, 9): def basicConfig( *, filename: Optional[StrPath] = ..., filemode: str = ..., format: str = ..., datefmt: Optional[str] = ..., - style: str = ..., + style: _FormatStyle = ..., + level: Optional[_Level] = ..., + stream: Optional[SupportsWrite[str]] = ..., + handlers: Optional[Iterable[Handler]] = ..., + force: Optional[bool] = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + ) -> None: ... + +elif sys.version_info >= (3, 8): + def basicConfig( + *, + filename: Optional[StrPath] = ..., + filemode: str = ..., + format: str = ..., + datefmt: Optional[str] = ..., + style: _FormatStyle = ..., level: Optional[_Level] = ..., stream: Optional[SupportsWrite[str]] = ..., handlers: Optional[Iterable[Handler]] = ..., @@ -722,7 +743,7 @@ else: filemode: str = ..., format: str = ..., datefmt: Optional[str] = ..., - style: str = ..., + style: _FormatStyle = ..., level: Optional[_Level] = ..., stream: Optional[SupportsWrite[str]] = ..., handlers: Optional[Iterable[Handler]] = ..., @@ -733,33 +754,33 @@ def setLoggerClass(klass: Type[Logger]) -> None: ... def captureWarnings(capture: bool) -> None: ... def setLogRecordFactory(factory: Callable[..., LogRecord]) -> None: ... -lastResort: Optional[StreamHandler] +lastResort: StreamHandler[Any] | None + +_StreamT = TypeVar("_StreamT", bound=SupportsWrite[str]) -class StreamHandler(Handler): - stream: SupportsWrite[str] # undocumented +class StreamHandler(Handler, Generic[_StreamT]): + stream: _StreamT # undocumented terminator: str - def __init__(self, stream: Optional[SupportsWrite[str]] = ...) -> None: ... + @overload + def __init__(self: StreamHandler[TextIO], stream: None = ...) -> None: ... + @overload + def __init__(self: StreamHandler[_StreamT], stream: _StreamT) -> None: ... if sys.version_info >= (3, 7): - def setStream(self, stream: SupportsWrite[str]) -> Optional[SupportsWrite[str]]: ... + def setStream(self, stream: _StreamT) -> _StreamT | None: ... -class FileHandler(StreamHandler): +class FileHandler(StreamHandler[TextIOWrapper]): baseFilename: str # undocumented mode: str # undocumented - encoding: Optional[str] # undocumented + encoding: str | None # undocumented delay: bool # undocumented if sys.version_info >= (3, 9): - errors: Optional[str] # undocumented + errors: str | None # undocumented def __init__( - self, - filename: StrPath, - mode: str = ..., - encoding: Optional[str] = ..., - delay: bool = ..., - errors: Optional[str] = ..., + self, filename: StrPath, mode: str = ..., encoding: str | None = ..., delay: bool = ..., errors: str | None = ... ) -> None: ... else: - def __init__(self, filename: StrPath, mode: str = ..., encoding: Optional[str] = ..., delay: bool = ...) -> None: ... - def _open(self) -> IO[Any]: ... + def __init__(self, filename: StrPath, mode: str = ..., encoding: str | None = ..., delay: bool = ...) -> None: ... + def _open(self) -> TextIOWrapper: ... # undocumented class NullHandler(Handler): ... diff --git a/mypy/typeshed/stdlib/logging/handlers.pyi b/mypy/typeshed/stdlib/logging/handlers.pyi index a60190ee5bce..9f0755c2a966 100644 --- a/mypy/typeshed/stdlib/logging/handlers.pyi +++ b/mypy/typeshed/stdlib/logging/handlers.pyi @@ -5,7 +5,7 @@ import sys from _typeshed import StrPath from collections.abc import Callable from logging import FileHandler, Handler, LogRecord -from socket import SocketKind, SocketType +from socket import SocketKind, socket from typing import Any, ClassVar, Optional, Pattern, Union if sys.version_info >= (3, 7): @@ -120,20 +120,20 @@ class SocketHandler(Handler): host: str # undocumented port: Optional[int] # undocumented address: Union[tuple[str, int], str] # undocumented - sock: Optional[SocketType] # undocumented + sock: Optional[socket] # undocumented closeOnError: bool # undocumented retryTime: Optional[float] # undocumented retryStart: float # undocumented retryFactor: float # undocumented retryMax: float # undocumented def __init__(self, host: str, port: Optional[int]) -> None: ... - def makeSocket(self, timeout: float = ...) -> SocketType: ... # timeout is undocumented + def makeSocket(self, timeout: float = ...) -> socket: ... # timeout is undocumented def makePickle(self, record: LogRecord) -> bytes: ... def send(self, s: bytes) -> None: ... def createSocket(self) -> None: ... class DatagramHandler(SocketHandler): - def makeSocket(self) -> SocketType: ... # type: ignore + def makeSocket(self) -> socket: ... # type: ignore class SysLogHandler(Handler): LOG_EMERG: int diff --git a/mypy/typeshed/stdlib/lzma.pyi b/mypy/typeshed/stdlib/lzma.pyi index 0228b9d12d55..1e4efd42a1a0 100644 --- a/mypy/typeshed/stdlib/lzma.pyi +++ b/mypy/typeshed/stdlib/lzma.pyi @@ -1,6 +1,6 @@ import io -from _typeshed import ReadableBuffer, StrOrBytesPath -from typing import IO, Any, Mapping, Optional, Sequence, TextIO, TypeVar, Union, overload +from _typeshed import ReadableBuffer, Self, StrOrBytesPath +from typing import IO, Any, Mapping, Optional, Sequence, TextIO, Union, overload from typing_extensions import Literal _OpenBinaryWritingMode = Literal["w", "wb", "x", "xb", "a", "ab"] @@ -9,7 +9,6 @@ _OpenTextWritingMode = Literal["wt", "xt", "at"] _PathOrFile = Union[StrOrBytesPath, IO[bytes]] _FilterChain = Sequence[Mapping[str, Any]] -_T = TypeVar("_T") FORMAT_AUTO: int FORMAT_XZ: int @@ -76,7 +75,7 @@ class LZMAFile(io.BufferedIOBase, IO[bytes]): preset: Optional[int] = ..., filters: Optional[_FilterChain] = ..., ) -> None: ... - def __enter__(self: _T) -> _T: ... + def __enter__(self: Self) -> Self: ... def close(self) -> None: ... @property def closed(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/mailbox.pyi b/mypy/typeshed/stdlib/mailbox.pyi index 1abe616fdc18..a5e9322347d6 100644 --- a/mypy/typeshed/stdlib/mailbox.pyi +++ b/mypy/typeshed/stdlib/mailbox.pyi @@ -1,6 +1,6 @@ import email.message import sys -from _typeshed import StrOrBytesPath +from _typeshed import Self, StrOrBytesPath from types import TracebackType from typing import ( IO, @@ -189,7 +189,7 @@ class _ProxyFile(Generic[AnyStr]): def tell(self) -> int: ... def seek(self, offset: int, whence: int = ...) -> None: ... def close(self) -> None: ... - def __enter__(self) -> _ProxyFile[AnyStr]: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[TracebackType] ) -> None: ... diff --git a/mypy/typeshed/stdlib/mmap.pyi b/mypy/typeshed/stdlib/mmap.pyi index 691d4f621a1b..b942ade9cab2 100644 --- a/mypy/typeshed/stdlib/mmap.pyi +++ b/mypy/typeshed/stdlib/mmap.pyi @@ -1,6 +1,6 @@ import sys from _typeshed import ReadableBuffer -from typing import AnyStr, ContextManager, Generic, Iterable, Iterator, Optional, Sized, Union, overload +from typing import ContextManager, Iterable, Iterator, NoReturn, Optional, Sized, Union, overload ACCESS_DEFAULT: int ACCESS_READ: int @@ -24,7 +24,7 @@ if sys.platform != "win32": PAGESIZE: int -class _mmap(Generic[AnyStr]): +class mmap(ContextManager[mmap], Iterable[int], Sized): if sys.platform == "win32": def __init__( self, fileno: int, length: int, tagname: Optional[str] = ..., access: int = ..., offset: int = ... @@ -39,16 +39,14 @@ class _mmap(Generic[AnyStr]): else: def flush(self, offset: int = ..., size: int = ...) -> int: ... def move(self, dest: int, src: int, count: int) -> None: ... - def read_byte(self) -> AnyStr: ... - def readline(self) -> AnyStr: ... + def read_byte(self) -> int: ... + def readline(self) -> bytes: ... def resize(self, newsize: int) -> None: ... def seek(self, pos: int, whence: int = ...) -> None: ... def size(self) -> int: ... def tell(self) -> int: ... - def write_byte(self, byte: AnyStr) -> None: ... + def write_byte(self, byte: int) -> None: ... def __len__(self) -> int: ... - -class mmap(_mmap[bytes], ContextManager[mmap], Iterable[bytes], Sized): closed: bool if sys.version_info >= (3, 8) and sys.platform != "win32": def madvise(self, option: int, start: int = ..., length: int = ...) -> None: ... @@ -60,14 +58,14 @@ class mmap(_mmap[bytes], ContextManager[mmap], Iterable[bytes], Sized): def __getitem__(self, index: int) -> int: ... @overload def __getitem__(self, index: slice) -> bytes: ... - def __delitem__(self, index: Union[int, slice]) -> None: ... + def __delitem__(self, index: Union[int, slice]) -> NoReturn: ... @overload def __setitem__(self, index: int, object: int) -> None: ... @overload - def __setitem__(self, index: slice, object: bytes) -> None: ... + def __setitem__(self, index: slice, object: ReadableBuffer) -> None: ... # Doesn't actually exist, but the object is actually iterable because it has __getitem__ and # __len__, so we claim that there is also an __iter__ to help type checkers. - def __iter__(self) -> Iterator[bytes]: ... + def __iter__(self) -> Iterator[int]: ... if sys.version_info >= (3, 8) and sys.platform != "win32": MADV_NORMAL: int diff --git a/mypy/typeshed/stdlib/multiprocessing/connection.pyi b/mypy/typeshed/stdlib/multiprocessing/connection.pyi index 15f58a3745f3..ce56bea53bd7 100644 --- a/mypy/typeshed/stdlib/multiprocessing/connection.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/connection.pyi @@ -1,6 +1,7 @@ import socket import sys import types +from _typeshed import Self from typing import Any, Iterable, List, Optional, Tuple, Type, Union if sys.version_info >= (3, 8): @@ -28,7 +29,7 @@ class _ConnectionBase: def recv_bytes_into(self, buf: Any, offset: int = ...) -> int: ... def recv(self) -> Any: ... def poll(self, timeout: Optional[float] = ...) -> bool: ... - def __enter__(self) -> _ConnectionBase: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], exc_tb: Optional[types.TracebackType] ) -> None: ... @@ -48,7 +49,7 @@ class Listener: def address(self) -> _Address: ... @property def last_accepted(self) -> Optional[_Address]: ... - def __enter__(self) -> Listener: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], exc_tb: Optional[types.TracebackType] ) -> None: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/dummy/connection.pyi b/mypy/typeshed/stdlib/multiprocessing/dummy/connection.pyi index 01733e59c763..d3abec749cde 100644 --- a/mypy/typeshed/stdlib/multiprocessing/dummy/connection.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/dummy/connection.pyi @@ -1,11 +1,10 @@ +from _typeshed import Self from queue import Queue from types import TracebackType -from typing import Any, List, Optional, Tuple, Type, TypeVar, Union +from typing import Any, List, Optional, Tuple, Type, Union families: List[None] -_ConnectionT = TypeVar("_ConnectionT", bound=Connection) -_ListenerT = TypeVar("_ListenerT", bound=Listener) _Address = Union[str, Tuple[str, int]] class Connection(object): @@ -15,7 +14,7 @@ class Connection(object): recv_bytes: Any send: Any send_bytes: Any - def __enter__(self: _ConnectionT) -> _ConnectionT: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> None: ... @@ -27,7 +26,7 @@ class Listener(object): _backlog_queue: Optional[Queue[Any]] @property def address(self) -> Optional[Queue[Any]]: ... - def __enter__(self: _ListenerT) -> _ListenerT: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> None: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/pool.pyi b/mypy/typeshed/stdlib/multiprocessing/pool.pyi index d8004655cacf..0f4d33dc376f 100644 --- a/mypy/typeshed/stdlib/multiprocessing/pool.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/pool.pyi @@ -1,4 +1,5 @@ import sys +from _typeshed import Self from typing import Any, Callable, ContextManager, Generic, Iterable, Iterator, List, Mapping, Optional, TypeVar if sys.version_info >= (3, 9): @@ -77,7 +78,7 @@ class Pool(ContextManager[Pool]): def close(self) -> None: ... def terminate(self) -> None: ... def join(self) -> None: ... - def __enter__(self: _PT) -> _PT: ... + def __enter__(self: Self) -> Self: ... class ThreadPool(Pool, ContextManager[ThreadPool]): def __init__( diff --git a/mypy/typeshed/stdlib/nntplib.pyi b/mypy/typeshed/stdlib/nntplib.pyi index 36fe063c8486..c3c981626fd9 100644 --- a/mypy/typeshed/stdlib/nntplib.pyi +++ b/mypy/typeshed/stdlib/nntplib.pyi @@ -2,9 +2,9 @@ import datetime import socket import ssl import sys -from typing import IO, Any, Dict, Iterable, List, NamedTuple, Optional, Tuple, TypeVar, Union +from _typeshed import Self +from typing import IO, Any, Dict, Iterable, List, NamedTuple, Optional, Tuple, Union -_SelfT = TypeVar("_SelfT", bound=_NNTPBase) _File = Union[IO[bytes], bytes, str, None] class NNTPError(Exception): @@ -46,7 +46,7 @@ class _NNTPBase: nntp_implementation: str nntp_version: int def __init__(self, file: IO[bytes], host: str, readermode: Optional[bool] = ..., timeout: float = ...) -> None: ... - def __enter__(self: _SelfT) -> _SelfT: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, *args: Any) -> None: ... def getwelcome(self) -> str: ... def getcapabilities(self) -> Dict[str, List[str]]: ... diff --git a/mypy/typeshed/stdlib/os/__init__.pyi b/mypy/typeshed/stdlib/os/__init__.pyi index 5de46ca031d7..24c6d7000e58 100644 --- a/mypy/typeshed/stdlib/os/__init__.pyi +++ b/mypy/typeshed/stdlib/os/__init__.pyi @@ -6,6 +6,7 @@ from _typeshed import ( OpenBinaryModeUpdating, OpenBinaryModeWriting, OpenTextMode, + Self, StrOrBytesPath, StrPath, ) @@ -860,7 +861,7 @@ if sys.version_info >= (3, 8): path: Optional[str] def __init__(self, path: Optional[str], cookie: _T, remove_dll_directory: Callable[[_T], Any]) -> None: ... def close(self) -> None: ... - def __enter__(self: _T) -> _T: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, *args: Any) -> None: ... def add_dll_directory(path: str) -> _AddedDllDirectory: ... if sys.platform == "linux": diff --git a/mypy/typeshed/stdlib/pathlib.pyi b/mypy/typeshed/stdlib/pathlib.pyi index b4624c3bea73..11c96fae6093 100644 --- a/mypy/typeshed/stdlib/pathlib.pyi +++ b/mypy/typeshed/stdlib/pathlib.pyi @@ -1,5 +1,13 @@ import sys -from _typeshed import OpenBinaryMode, OpenBinaryModeReading, OpenBinaryModeUpdating, OpenBinaryModeWriting, OpenTextMode, StrPath +from _typeshed import ( + OpenBinaryMode, + OpenBinaryModeReading, + OpenBinaryModeUpdating, + OpenBinaryModeWriting, + OpenTextMode, + Self, + StrPath, +) from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper from os import PathLike, stat_result from types import TracebackType @@ -54,7 +62,7 @@ class PureWindowsPath(PurePath): ... class Path(PurePath): def __new__(cls: Type[_P], *args: StrPath, **kwargs: Any) -> _P: ... - def __enter__(self: _P) -> _P: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType] ) -> Optional[bool]: ... diff --git a/mypy/typeshed/stdlib/pwd.pyi b/mypy/typeshed/stdlib/pwd.pyi index 83020c1576dd..3585cc235a58 100644 --- a/mypy/typeshed/stdlib/pwd.pyi +++ b/mypy/typeshed/stdlib/pwd.pyi @@ -1,4 +1,4 @@ -from typing import List, Tuple +from typing import ClassVar, List, Tuple class struct_passwd(Tuple[str, str, int, int, str, str, str]): pw_name: str @@ -9,6 +9,10 @@ class struct_passwd(Tuple[str, str, int, int, str, str, str]): pw_dir: str pw_shell: str + n_fields: ClassVar[int] + n_sequence_fields: ClassVar[int] + n_unnamed_fields: ClassVar[int] + def getpwall() -> List[struct_passwd]: ... def getpwuid(__uid: int) -> struct_passwd: ... def getpwnam(__name: str) -> struct_passwd: ... diff --git a/mypy/typeshed/stdlib/random.pyi b/mypy/typeshed/stdlib/random.pyi index 0f1e280490ac..152dc906eab1 100644 --- a/mypy/typeshed/stdlib/random.pyi +++ b/mypy/typeshed/stdlib/random.pyi @@ -1,6 +1,7 @@ import _random import sys from collections.abc import Callable, Iterable, MutableSequence, Sequence, Set +from fractions import Fraction from typing import Any, NoReturn, Optional, Tuple, TypeVar, Union _T = TypeVar("_T") @@ -19,9 +20,9 @@ class Random(_random.Random): def choices( self, population: Sequence[_T], - weights: Optional[Sequence[float]] = ..., + weights: Optional[Sequence[Union[float, Fraction]]] = ..., *, - cum_weights: Optional[Sequence[float]] = ..., + cum_weights: Optional[Sequence[Union[float, Fraction]]] = ..., k: int = ..., ) -> list[_T]: ... def shuffle(self, x: MutableSequence[Any], random: Optional[Callable[[], float]] = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/runpy.pyi b/mypy/typeshed/stdlib/runpy.pyi index d40c3668ad2f..7df9bee7b557 100644 --- a/mypy/typeshed/stdlib/runpy.pyi +++ b/mypy/typeshed/stdlib/runpy.pyi @@ -1,19 +1,18 @@ +from _typeshed import Self from types import ModuleType -from typing import Any, Dict, Optional, TypeVar - -_T = TypeVar("_T") +from typing import Any, Dict, Optional class _TempModule: mod_name: str = ... module: ModuleType = ... def __init__(self, mod_name: str) -> None: ... - def __enter__(self: _T) -> _T: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, *args: Any) -> None: ... class _ModifiedArgv0: value: Any = ... def __init__(self, value: Any) -> None: ... - def __enter__(self: _T) -> _T: ... + def __enter__(self) -> None: ... def __exit__(self, *args: Any) -> None: ... def run_module( diff --git a/mypy/typeshed/stdlib/select.pyi b/mypy/typeshed/stdlib/select.pyi index 1a046c7b9bc3..0cdbaa5f735a 100644 --- a/mypy/typeshed/stdlib/select.pyi +++ b/mypy/typeshed/stdlib/select.pyi @@ -1,5 +1,5 @@ import sys -from _typeshed import FileDescriptorLike +from _typeshed import FileDescriptorLike, Self from types import TracebackType from typing import Any, Iterable, List, Optional, Tuple, Type @@ -101,7 +101,7 @@ if sys.platform != "linux" and sys.platform != "win32": if sys.platform == "linux": class epoll(object): def __init__(self, sizehint: int = ..., flags: int = ...) -> None: ... - def __enter__(self) -> epoll: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: Optional[Type[BaseException]] = ..., diff --git a/mypy/typeshed/stdlib/selectors.pyi b/mypy/typeshed/stdlib/selectors.pyi index 94690efadbf8..ade59f47e1bf 100644 --- a/mypy/typeshed/stdlib/selectors.pyi +++ b/mypy/typeshed/stdlib/selectors.pyi @@ -1,5 +1,5 @@ import sys -from _typeshed import FileDescriptor, FileDescriptorLike +from _typeshed import FileDescriptor, FileDescriptorLike, Self from abc import ABCMeta, abstractmethod from typing import Any, List, Mapping, NamedTuple, Optional, Tuple @@ -26,7 +26,7 @@ class BaseSelector(metaclass=ABCMeta): def get_key(self, fileobj: FileDescriptorLike) -> SelectorKey: ... @abstractmethod def get_map(self) -> Mapping[FileDescriptorLike, SelectorKey]: ... - def __enter__(self) -> BaseSelector: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, *args: Any) -> None: ... class SelectSelector(BaseSelector): diff --git a/mypy/typeshed/stdlib/shelve.pyi b/mypy/typeshed/stdlib/shelve.pyi index ed062f62b49b..2e36338dba70 100644 --- a/mypy/typeshed/stdlib/shelve.pyi +++ b/mypy/typeshed/stdlib/shelve.pyi @@ -1,4 +1,5 @@ import collections.abc +from _typeshed import Self from typing import Any, Dict, Iterator, Optional, Tuple class Shelf(collections.abc.MutableMapping[Any, Any]): @@ -12,7 +13,7 @@ class Shelf(collections.abc.MutableMapping[Any, Any]): def __getitem__(self, key: str) -> Any: ... def __setitem__(self, key: str, value: Any) -> None: ... def __delitem__(self, key: str) -> None: ... - def __enter__(self) -> Shelf: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, type: Any, value: Any, traceback: Any) -> None: ... def close(self) -> None: ... def __del__(self) -> None: ... diff --git a/mypy/typeshed/stdlib/signal.pyi b/mypy/typeshed/stdlib/signal.pyi index aa0bbf2bffd1..d54b22d57c0a 100644 --- a/mypy/typeshed/stdlib/signal.pyi +++ b/mypy/typeshed/stdlib/signal.pyi @@ -80,7 +80,7 @@ if sys.platform != "win32": SIG_SETMASK = Sigmasks.SIG_SETMASK _SIGNUM = Union[int, Signals] -_HANDLER = Union[Callable[[Signals, FrameType], Any], int, Handlers, None] +_HANDLER = Union[Callable[[int, Optional[FrameType]], Any], int, Handlers, None] SIGABRT: Signals if sys.platform != "win32": diff --git a/mypy/typeshed/stdlib/smtplib.pyi b/mypy/typeshed/stdlib/smtplib.pyi index 48a35f8e3b67..5d0ab420ee28 100644 --- a/mypy/typeshed/stdlib/smtplib.pyi +++ b/mypy/typeshed/stdlib/smtplib.pyi @@ -1,3 +1,4 @@ +from _typeshed import Self from email.message import Message as _Message from socket import socket from ssl import SSLContext @@ -75,7 +76,7 @@ class SMTP: timeout: float = ..., source_address: Optional[_SourceAddress] = ..., ) -> None: ... - def __enter__(self) -> SMTP: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], tb: Optional[TracebackType] ) -> None: ... diff --git a/mypy/typeshed/stdlib/socket.pyi b/mypy/typeshed/stdlib/socket.pyi index 06adfe49e93a..6bc1ae62fa16 100644 --- a/mypy/typeshed/stdlib/socket.pyi +++ b/mypy/typeshed/stdlib/socket.pyi @@ -1,509 +1,389 @@ import sys +from _typeshed import ReadableBuffer, Self, WriteableBuffer +from collections.abc import Iterable from enum import IntEnum, IntFlag -from typing import Any, BinaryIO, Iterable, List, Optional, TextIO, Tuple, TypeVar, Union, overload +from io import RawIOBase +from typing import Any, BinaryIO, Optional, TextIO, TypeVar, Union, overload from typing_extensions import Literal -# ----- 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. +# Ideally, we'd just do "from _socket import *". Unfortunately, socket +# overrides some definitions from _socket incompatibly. mypy incorrectly +# prefers the definitions from _socket over those defined here. +import _socket +from _socket import ( + _FD, + CMSG_LEN as CMSG_LEN, + CMSG_SPACE as CMSG_SPACE, + EAI_ADDRFAMILY as EAI_ADDRFAMILY, + EAI_AGAIN as EAI_AGAIN, + EAI_BADFLAGS as EAI_BADFLAGS, + EAI_BADHINTS as EAI_BADHINTS, + EAI_FAIL as EAI_FAIL, + EAI_FAMILY as EAI_FAMILY, + EAI_MAX as EAI_MAX, + EAI_MEMORY as EAI_MEMORY, + EAI_NODATA as EAI_NODATA, + EAI_NONAME as EAI_NONAME, + EAI_OVERFLOW as EAI_OVERFLOW, + EAI_PROTOCOL as EAI_PROTOCOL, + EAI_SERVICE as EAI_SERVICE, + EAI_SOCKTYPE as EAI_SOCKTYPE, + EAI_SYSTEM as EAI_SYSTEM, + INADDR_ALLHOSTS_GROUP as INADDR_ALLHOSTS_GROUP, + INADDR_ANY as INADDR_ANY, + INADDR_BROADCAST as INADDR_BROADCAST, + INADDR_LOOPBACK as INADDR_LOOPBACK, + INADDR_MAX_LOCAL_GROUP as INADDR_MAX_LOCAL_GROUP, + INADDR_NONE as INADDR_NONE, + INADDR_UNSPEC_GROUP as INADDR_UNSPEC_GROUP, + IP_ADD_MEMBERSHIP as IP_ADD_MEMBERSHIP, + IP_DEFAULT_MULTICAST_LOOP as IP_DEFAULT_MULTICAST_LOOP, + IP_DEFAULT_MULTICAST_TTL as IP_DEFAULT_MULTICAST_TTL, + IP_DROP_MEMBERSHIP as IP_DROP_MEMBERSHIP, + IP_HDRINCL as IP_HDRINCL, + IP_MAX_MEMBERSHIPS as IP_MAX_MEMBERSHIPS, + IP_MULTICAST_IF as IP_MULTICAST_IF, + IP_MULTICAST_LOOP as IP_MULTICAST_LOOP, + IP_MULTICAST_TTL as IP_MULTICAST_TTL, + IP_OPTIONS as IP_OPTIONS, + IP_RECVDSTADDR as IP_RECVDSTADDR, + IP_RECVOPTS as IP_RECVOPTS, + IP_RECVRETOPTS as IP_RECVRETOPTS, + IP_RETOPTS as IP_RETOPTS, + IP_TOS as IP_TOS, + IP_TRANSPARENT as IP_TRANSPARENT, + IP_TTL as IP_TTL, + IPPORT_RESERVED as IPPORT_RESERVED, + IPPORT_USERRESERVED as IPPORT_USERRESERVED, + IPPROTO_AH as IPPROTO_AH, + IPPROTO_BIP as IPPROTO_BIP, + IPPROTO_DSTOPTS as IPPROTO_DSTOPTS, + IPPROTO_EGP as IPPROTO_EGP, + IPPROTO_EON as IPPROTO_EON, + IPPROTO_ESP as IPPROTO_ESP, + IPPROTO_FRAGMENT as IPPROTO_FRAGMENT, + IPPROTO_GGP as IPPROTO_GGP, + IPPROTO_GRE as IPPROTO_GRE, + IPPROTO_HELLO as IPPROTO_HELLO, + 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_IPCOMP as IPPROTO_IPCOMP, + IPPROTO_IPIP as IPPROTO_IPIP, + IPPROTO_IPV4 as IPPROTO_IPV4, + IPPROTO_IPV6 as IPPROTO_IPV6, + IPPROTO_MAX as IPPROTO_MAX, + IPPROTO_MOBILE as IPPROTO_MOBILE, + 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_RSVP as IPPROTO_RSVP, + IPPROTO_SCTP as IPPROTO_SCTP, + IPPROTO_TCP as IPPROTO_TCP, + IPPROTO_TP as IPPROTO_TP, + IPPROTO_UDP as IPPROTO_UDP, + IPPROTO_VRRP as IPPROTO_VRRP, + IPPROTO_XTP as IPPROTO_XTP, + IPV6_CHECKSUM as IPV6_CHECKSUM, + IPV6_DONTFRAG as IPV6_DONTFRAG, + IPV6_DSTOPTS as IPV6_DSTOPTS, + IPV6_HOPLIMIT as IPV6_HOPLIMIT, + IPV6_HOPOPTS as IPV6_HOPOPTS, + IPV6_JOIN_GROUP as IPV6_JOIN_GROUP, + IPV6_LEAVE_GROUP as IPV6_LEAVE_GROUP, + IPV6_MULTICAST_HOPS as IPV6_MULTICAST_HOPS, + IPV6_MULTICAST_IF as IPV6_MULTICAST_IF, + IPV6_MULTICAST_LOOP as IPV6_MULTICAST_LOOP, + IPV6_NEXTHOP as IPV6_NEXTHOP, + IPV6_PATHMTU as IPV6_PATHMTU, + IPV6_PKTINFO as IPV6_PKTINFO, + IPV6_RECVDSTOPTS as IPV6_RECVDSTOPTS, + IPV6_RECVHOPLIMIT as IPV6_RECVHOPLIMIT, + IPV6_RECVHOPOPTS as IPV6_RECVHOPOPTS, + IPV6_RECVPATHMTU as IPV6_RECVPATHMTU, + IPV6_RECVPKTINFO as IPV6_RECVPKTINFO, + IPV6_RECVRTHDR as IPV6_RECVRTHDR, + IPV6_RECVTCLASS as IPV6_RECVTCLASS, + IPV6_RTHDR as IPV6_RTHDR, + IPV6_RTHDR_TYPE_0 as IPV6_RTHDR_TYPE_0, + IPV6_RTHDRDSTOPTS as IPV6_RTHDRDSTOPTS, + IPV6_TCLASS as IPV6_TCLASS, + IPV6_UNICAST_HOPS as IPV6_UNICAST_HOPS, + IPV6_USE_MIN_MTU as IPV6_USE_MIN_MTU, + IPV6_V6ONLY as IPV6_V6ONLY, + IPX_TYPE as IPX_TYPE, + LOCAL_PEERCRED as LOCAL_PEERCRED, + NI_DGRAM as NI_DGRAM, + NI_MAXHOST as NI_MAXHOST, + NI_MAXSERV as NI_MAXSERV, + NI_NAMEREQD as NI_NAMEREQD, + NI_NOFQDN as NI_NOFQDN, + NI_NUMERICHOST as NI_NUMERICHOST, + NI_NUMERICSERV as NI_NUMERICSERV, + SCM_CREDENTIALS as SCM_CREDENTIALS, + SCM_CREDS as SCM_CREDS, + SCM_RIGHTS as SCM_RIGHTS, + SHUT_RD as SHUT_RD, + SHUT_RDWR as SHUT_RDWR, + SHUT_WR as SHUT_WR, + SO_ACCEPTCONN as SO_ACCEPTCONN, + SO_BINDTODEVICE as SO_BINDTODEVICE, + SO_BROADCAST as SO_BROADCAST, + SO_DEBUG as SO_DEBUG, + SO_DONTROUTE as SO_DONTROUTE, + SO_ERROR as SO_ERROR, + SO_EXCLUSIVEADDRUSE as SO_EXCLUSIVEADDRUSE, + SO_KEEPALIVE as SO_KEEPALIVE, + SO_LINGER as SO_LINGER, + SO_MARK as SO_MARK, + SO_OOBINLINE as SO_OOBINLINE, + SO_PASSCRED as SO_PASSCRED, + SO_PEERCRED as SO_PEERCRED, + SO_PRIORITY as SO_PRIORITY, + SO_RCVBUF as SO_RCVBUF, + SO_RCVLOWAT as SO_RCVLOWAT, + SO_RCVTIMEO as SO_RCVTIMEO, + SO_REUSEADDR as SO_REUSEADDR, + SO_REUSEPORT as SO_REUSEPORT, + SO_SETFIB as SO_SETFIB, + SO_SNDBUF as SO_SNDBUF, + SO_SNDLOWAT as SO_SNDLOWAT, + SO_SNDTIMEO as SO_SNDTIMEO, + SO_TYPE as SO_TYPE, + SO_USELOOPBACK as SO_USELOOPBACK, + SOL_ATALK as SOL_ATALK, + SOL_AX25 as SOL_AX25, + SOL_HCI as SOL_HCI, + SOL_IP as SOL_IP, + SOL_IPX as SOL_IPX, + SOL_NETROM as SOL_NETROM, + SOL_ROSE as SOL_ROSE, + SOL_SOCKET as SOL_SOCKET, + SOL_TCP as SOL_TCP, + SOL_UDP as SOL_UDP, + SOMAXCONN as SOMAXCONN, + TCP_CORK as TCP_CORK, + TCP_DEFER_ACCEPT as TCP_DEFER_ACCEPT, + TCP_FASTOPEN as TCP_FASTOPEN, + TCP_INFO as TCP_INFO, + TCP_KEEPCNT as TCP_KEEPCNT, + TCP_KEEPIDLE as TCP_KEEPIDLE, + TCP_KEEPINTVL as TCP_KEEPINTVL, + TCP_LINGER2 as TCP_LINGER2, + TCP_MAXSEG as TCP_MAXSEG, + TCP_NODELAY as TCP_NODELAY, + TCP_QUICKACK as TCP_QUICKACK, + TCP_SYNCNT as TCP_SYNCNT, + TCP_WINDOW_CLAMP as TCP_WINDOW_CLAMP, + SocketType as SocketType, + _Address as _Address, + _RetAddress as _RetAddress, + dup as dup, + error as error, + gaierror as gaierror, + getdefaulttimeout as getdefaulttimeout, + gethostbyaddr as gethostbyaddr, + gethostbyname as gethostbyname, + gethostbyname_ex as gethostbyname_ex, + gethostname as gethostname, + getnameinfo as getnameinfo, + getprotobyname as getprotobyname, + getservbyname as getservbyname, + getservbyport as getservbyport, + has_ipv6 as has_ipv6, + herror as herror, + htonl as htonl, + htons as htons, + inet_aton as inet_aton, + inet_ntoa as inet_ntoa, + inet_ntop as inet_ntop, + inet_pton as inet_pton, + ntohl as ntohl, + ntohs as ntohs, + setdefaulttimeout as setdefaulttimeout, + timeout as timeout, +) -# Constants defined by Python (i.e. not OS constants re-exported from C) -has_ipv6: bool -SocketType: Any -SocketIO: Any - -# Re-exported errno -EAGAIN: int -EBADF: int -EINTR: int -EWOULDBLOCK: int - -# Constants re-exported from C - -# Per socketmodule.c, only these three families are portable -AF_UNIX: AddressFamily -AF_INET: AddressFamily -AF_INET6: AddressFamily - -SOCK_STREAM: SocketKind -SOCK_DGRAM: SocketKind -SOCK_RAW: SocketKind -SOCK_RDM: SocketKind -SOCK_SEQPACKET: SocketKind - -if sys.platform == "linux": - SOCK_CLOEXEC: SocketKind - SOCK_NONBLOCK: SocketKind - -# Address families not mentioned in the docs -AF_AAL5: AddressFamily -AF_APPLETALK: AddressFamily -AF_ASH: AddressFamily -AF_ATMPVC: AddressFamily -AF_ATMSVC: AddressFamily -AF_AX25: AddressFamily -AF_BRIDGE: AddressFamily -AF_DECnet: AddressFamily -AF_ECONET: AddressFamily -AF_IPX: AddressFamily -AF_IRDA: AddressFamily -AF_KEY: AddressFamily -AF_LLC: AddressFamily -AF_NETBEUI: AddressFamily -AF_NETROM: AddressFamily -AF_PPPOX: AddressFamily -AF_ROSE: AddressFamily -AF_ROUTE: AddressFamily -AF_SECURITY: AddressFamily -AF_SNA: AddressFamily -AF_SYSTEM: AddressFamily -AF_UNSPEC: AddressFamily -AF_WANPIPE: AddressFamily -AF_X25: AddressFamily - -# The "many constants" referenced by the docs -SOMAXCONN: int -AI_ADDRCONFIG: AddressInfo -AI_ALL: AddressInfo -AI_CANONNAME: AddressInfo -AI_DEFAULT: AddressInfo -AI_MASK: AddressInfo -AI_NUMERICHOST: AddressInfo -AI_NUMERICSERV: AddressInfo -AI_PASSIVE: AddressInfo -AI_V4MAPPED: AddressInfo -AI_V4MAPPED_CFG: AddressInfo -EAI_ADDRFAMILY: int -EAI_AGAIN: int -EAI_BADFLAGS: int -EAI_BADHINTS: int -EAI_FAIL: int -EAI_FAMILY: int -EAI_MAX: int -EAI_MEMORY: int -EAI_NODATA: int -EAI_NONAME: int -EAI_OVERFLOW: int -EAI_PROTOCOL: int -EAI_SERVICE: int -EAI_SOCKTYPE: int -EAI_SYSTEM: 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 -IPPROTO_AH: int -IPPROTO_BIP: int -IPPROTO_DSTOPTS: int -IPPROTO_EGP: int -IPPROTO_EON: int -IPPROTO_ESP: int -IPPROTO_FRAGMENT: int -IPPROTO_GGP: int -IPPROTO_GRE: int -IPPROTO_HELLO: int -IPPROTO_HOPOPTS: int -IPPROTO_ICMP: int -IPPROTO_ICMPV6: int -IPPROTO_IDP: int -IPPROTO_IGMP: int -IPPROTO_IP: int -IPPROTO_IPCOMP: int -IPPROTO_IPIP: int -IPPROTO_IPV4: int -IPPROTO_IPV6: int -IPPROTO_MAX: int -IPPROTO_MOBILE: int -IPPROTO_ND: int -IPPROTO_NONE: int -IPPROTO_PIM: int -IPPROTO_PUP: int -IPPROTO_RAW: int -IPPROTO_ROUTING: int -IPPROTO_RSVP: int -IPPROTO_SCTP: int -IPPROTO_TCP: int -IPPROTO_TP: int -IPPROTO_UDP: int -IPPROTO_VRRP: int -IPPROTO_XTP: int -IPV6_CHECKSUM: int -IPV6_DONTFRAG: int -IPV6_DSTOPTS: int -IPV6_HOPLIMIT: int -IPV6_HOPOPTS: int -IPV6_JOIN_GROUP: int -IPV6_LEAVE_GROUP: int -IPV6_MULTICAST_HOPS: int -IPV6_MULTICAST_IF: int -IPV6_MULTICAST_LOOP: int -IPV6_NEXTHOP: int -IPV6_PATHMTU: int -IPV6_PKTINFO: int -IPV6_RECVDSTOPTS: int -IPV6_RECVHOPLIMIT: int -IPV6_RECVHOPOPTS: int -IPV6_RECVPATHMTU: int -IPV6_RECVPKTINFO: int -IPV6_RECVRTHDR: int -IPV6_RECVTCLASS: int -IPV6_RTHDR: int -IPV6_RTHDRDSTOPTS: int -IPV6_RTHDR_TYPE_0: int -IPV6_TCLASS: int -IPV6_UNICAST_HOPS: int -IPV6_USE_MIN_MTU: int -IPV6_V6ONLY: int -IPX_TYPE: int -IP_ADD_MEMBERSHIP: int -IP_DEFAULT_MULTICAST_LOOP: int -IP_DEFAULT_MULTICAST_TTL: int -IP_DROP_MEMBERSHIP: int -IP_HDRINCL: int -IP_MAX_MEMBERSHIPS: int -IP_MULTICAST_IF: int -IP_MULTICAST_LOOP: int -IP_MULTICAST_TTL: int -IP_OPTIONS: int -IP_RECVDSTADDR: int -IP_RECVOPTS: int -IP_RECVRETOPTS: int -IP_RETOPTS: int -IP_TOS: int -IP_TRANSPARENT: int -IP_TTL: int -LOCAL_PEERCRED: int -MSG_BCAST: MsgFlag -MSG_BTAG: MsgFlag -MSG_CMSG_CLOEXEC: MsgFlag -MSG_CONFIRM: MsgFlag -MSG_CTRUNC: MsgFlag -MSG_DONTROUTE: MsgFlag -MSG_DONTWAIT: MsgFlag -MSG_EOF: MsgFlag -MSG_EOR: MsgFlag -MSG_ERRQUEUE: MsgFlag -MSG_ETAG: MsgFlag -MSG_FASTOPEN: MsgFlag -MSG_MCAST: MsgFlag -MSG_MORE: MsgFlag -MSG_NOSIGNAL: MsgFlag -MSG_NOTIFICATION: MsgFlag -MSG_OOB: MsgFlag -MSG_PEEK: MsgFlag -MSG_TRUNC: MsgFlag -MSG_WAITALL: MsgFlag -NI_DGRAM: int -NI_MAXHOST: int -NI_MAXSERV: int -NI_NAMEREQD: int -NI_NOFQDN: int -NI_NUMERICHOST: int -NI_NUMERICSERV: int -SCM_CREDENTIALS: int -SCM_CREDS: int -SCM_RIGHTS: int -SHUT_RD: int -SHUT_RDWR: int -SHUT_WR: int -SOL_ATALK: int -SOL_AX25: int -SOL_HCI: int -SOL_IP: int -SOL_IPX: int -SOL_NETROM: int -SOL_ROSE: int -SOL_SOCKET: int -SOL_TCP: int -SOL_UDP: int -SO_ACCEPTCONN: int -SO_BINDTODEVICE: int -SO_BROADCAST: int -SO_DEBUG: int -SO_DONTROUTE: int -SO_ERROR: int -SO_EXCLUSIVEADDRUSE: int -SO_KEEPALIVE: int -SO_LINGER: int -SO_MARK: int -SO_OOBINLINE: int -SO_PASSCRED: int -SO_PEERCRED: int -SO_PRIORITY: int -SO_RCVBUF: int -SO_RCVLOWAT: int -SO_RCVTIMEO: int -SO_REUSEADDR: int -SO_REUSEPORT: int -SO_SETFIB: int -SO_SNDBUF: int -SO_SNDLOWAT: int -SO_SNDTIMEO: int -SO_TYPE: int -SO_USELOOPBACK: int -TCP_CORK: int -TCP_DEFER_ACCEPT: int -TCP_FASTOPEN: int -TCP_INFO: int -TCP_KEEPCNT: int -TCP_KEEPIDLE: int -TCP_KEEPINTVL: int -TCP_LINGER2: int -TCP_MAXSEG: int -TCP_NODELAY: int -TCP_QUICKACK: int -TCP_SYNCNT: int -TCP_WINDOW_CLAMP: int if sys.version_info >= (3, 7): - TCP_NOTSENT_LOWAT: int - -# Specifically-documented constants - + from _socket import close as close +if sys.platform != "win32": + from _socket import sethostname as sethostname +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 == "linux": - AF_CAN: AddressFamily - PF_CAN: int - SOL_CAN_BASE: int - SOL_CAN_RAW: int - CAN_EFF_FLAG: int - CAN_EFF_MASK: int - CAN_ERR_FLAG: int - CAN_ERR_MASK: int - CAN_RAW: int - CAN_RAW_ERR_FILTER: int - CAN_RAW_FILTER: int - CAN_RAW_LOOPBACK: int - CAN_RAW_RECV_OWN_MSGS: int - CAN_RTR_FLAG: int - CAN_SFF_MASK: int - - CAN_BCM: int - CAN_BCM_TX_SETUP: int - CAN_BCM_TX_DELETE: int - CAN_BCM_TX_READ: int - CAN_BCM_TX_SEND: int - CAN_BCM_RX_SETUP: int - CAN_BCM_RX_DELETE: int - CAN_BCM_RX_READ: int - CAN_BCM_TX_STATUS: int - CAN_BCM_TX_EXPIRED: int - 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 - CAN_BCM_TX_ANNOUNCE: int - CAN_BCM_TX_CP_CAN_ID: int - CAN_BCM_RX_FILTER_ID: int - CAN_BCM_RX_CHECK_DLC: int - CAN_BCM_RX_NO_AUTOTIMER: int - CAN_BCM_RX_ANNOUNCE_RESUME: int - CAN_BCM_TX_RESET_MULTI_IDX: int - CAN_BCM_RX_RTR_FRAME: int - CAN_BCM_CAN_FD_FRAME: int - + from _socket import ( + ALG_OP_DECRYPT as ALG_OP_DECRYPT, + ALG_OP_ENCRYPT as ALG_OP_ENCRYPT, + ALG_OP_SIGN as ALG_OP_SIGN, + ALG_OP_VERIFY as ALG_OP_VERIFY, + ALG_SET_AEAD_ASSOCLEN as ALG_SET_AEAD_ASSOCLEN, + ALG_SET_AEAD_AUTHSIZE as ALG_SET_AEAD_AUTHSIZE, + ALG_SET_IV as ALG_SET_IV, + ALG_SET_KEY as ALG_SET_KEY, + ALG_SET_OP as ALG_SET_OP, + ALG_SET_PUBKEY as ALG_SET_PUBKEY, + CAN_BCM as CAN_BCM, + CAN_BCM_RX_CHANGED as CAN_BCM_RX_CHANGED, + CAN_BCM_RX_DELETE as CAN_BCM_RX_DELETE, + CAN_BCM_RX_READ as CAN_BCM_RX_READ, + 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_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_SEND as CAN_BCM_TX_SEND, + CAN_BCM_TX_SETUP as CAN_BCM_TX_SETUP, + CAN_BCM_TX_STATUS as CAN_BCM_TX_STATUS, + CAN_EFF_FLAG as CAN_EFF_FLAG, + CAN_EFF_MASK as CAN_EFF_MASK, + CAN_ERR_FLAG as CAN_ERR_FLAG, + CAN_ERR_MASK as CAN_ERR_MASK, + CAN_RAW as CAN_RAW, + CAN_RAW_ERR_FILTER as CAN_RAW_ERR_FILTER, + CAN_RAW_FD_FRAMES as CAN_RAW_FD_FRAMES, + CAN_RAW_FILTER as CAN_RAW_FILTER, + CAN_RAW_LOOPBACK as CAN_RAW_LOOPBACK, + 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, + PACKET_BROADCAST as PACKET_BROADCAST, + PACKET_FASTROUTE as PACKET_FASTROUTE, + PACKET_HOST as PACKET_HOST, + PACKET_LOOPBACK as PACKET_LOOPBACK, + PACKET_MULTICAST as PACKET_MULTICAST, + PACKET_OTHERHOST as PACKET_OTHERHOST, + PACKET_OUTGOING as PACKET_OUTGOING, + PF_CAN as PF_CAN, + PF_PACKET as PF_PACKET, + PF_RDS as PF_RDS, + RDS_CANCEL_SENT_TO as RDS_CANCEL_SENT_TO, + RDS_CMSG_RDMA_ARGS as RDS_CMSG_RDMA_ARGS, + RDS_CMSG_RDMA_DEST as RDS_CMSG_RDMA_DEST, + RDS_CMSG_RDMA_MAP as RDS_CMSG_RDMA_MAP, + RDS_CMSG_RDMA_STATUS as RDS_CMSG_RDMA_STATUS, + RDS_CMSG_RDMA_UPDATE as RDS_CMSG_RDMA_UPDATE, + RDS_CONG_MONITOR as RDS_CONG_MONITOR, + RDS_FREE_MR as RDS_FREE_MR, + RDS_GET_MR as RDS_GET_MR, + RDS_GET_MR_FOR_DEST as RDS_GET_MR_FOR_DEST, + RDS_RDMA_DONTWAIT as RDS_RDMA_DONTWAIT, + RDS_RDMA_FENCE as RDS_RDMA_FENCE, + RDS_RDMA_INVALIDATE as RDS_RDMA_INVALIDATE, + RDS_RDMA_NOTIFY_ME as RDS_RDMA_NOTIFY_ME, + RDS_RDMA_READWRITE as RDS_RDMA_READWRITE, + RDS_RDMA_SILENT as RDS_RDMA_SILENT, + RDS_RDMA_USE_ONCE as RDS_RDMA_USE_ONCE, + RDS_RECVERR as RDS_RECVERR, + SOL_ALG as SOL_ALG, + SOL_CAN_BASE as SOL_CAN_BASE, + SOL_CAN_RAW as SOL_CAN_RAW, + SOL_RDS as SOL_RDS, + SOL_TIPC as SOL_TIPC, + TIPC_ADDR_ID as TIPC_ADDR_ID, + TIPC_ADDR_NAME as TIPC_ADDR_NAME, + TIPC_ADDR_NAMESEQ as TIPC_ADDR_NAMESEQ, + TIPC_CFG_SRV as TIPC_CFG_SRV, + TIPC_CLUSTER_SCOPE as TIPC_CLUSTER_SCOPE, + TIPC_CONN_TIMEOUT as TIPC_CONN_TIMEOUT, + TIPC_CRITICAL_IMPORTANCE as TIPC_CRITICAL_IMPORTANCE, + TIPC_DEST_DROPPABLE as TIPC_DEST_DROPPABLE, + TIPC_HIGH_IMPORTANCE as TIPC_HIGH_IMPORTANCE, + TIPC_IMPORTANCE as TIPC_IMPORTANCE, + TIPC_LOW_IMPORTANCE as TIPC_LOW_IMPORTANCE, + TIPC_MEDIUM_IMPORTANCE as TIPC_MEDIUM_IMPORTANCE, + TIPC_NODE_SCOPE as TIPC_NODE_SCOPE, + TIPC_PUBLISHED as TIPC_PUBLISHED, + TIPC_SRC_DROPPABLE as TIPC_SRC_DROPPABLE, + TIPC_SUB_CANCEL as TIPC_SUB_CANCEL, + TIPC_SUB_PORTS as TIPC_SUB_PORTS, + TIPC_SUB_SERVICE as TIPC_SUB_SERVICE, + TIPC_SUBSCR_TIMEOUT as TIPC_SUBSCR_TIMEOUT, + TIPC_TOP_SRV as TIPC_TOP_SRV, + TIPC_WAIT_FOREVER as TIPC_WAIT_FOREVER, + TIPC_WITHDRAWN as TIPC_WITHDRAWN, + TIPC_ZONE_SCOPE as TIPC_ZONE_SCOPE, + ) if sys.platform == "linux" and sys.version_info >= (3, 7): - CAN_ISOTP: int - + 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, + TCP_NOTSENT_LOWAT as TCP_NOTSENT_LOWAT, + 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 == "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): - CAN_J1939: int - - J1939_MAX_UNICAST_ADDR: int - J1939_IDLE_ADDR: int - J1939_NO_ADDR: int - J1939_NO_NAME: int - J1939_PGN_REQUEST: int - J1939_PGN_ADDRESS_CLAIMED: int - J1939_PGN_ADDRESS_COMMANDED: int - J1939_PGN_PDU1_MAX: int - J1939_PGN_MAX: int - J1939_NO_PGN: int - - SO_J1939_FILTER: int - SO_J1939_PROMISC: int - SO_J1939_SEND_PRIO: int - SO_J1939_ERRQUEUE: int - - SCM_J1939_DEST_ADDR: int - SCM_J1939_DEST_NAME: int - SCM_J1939_PRIO: int - SCM_J1939_ERRQUEUE: int - - 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": - AF_PACKET: AddressFamily - PF_PACKET: int - PACKET_BROADCAST: int - PACKET_FASTROUTE: int - PACKET_HOST: int - PACKET_LOOPBACK: int - PACKET_MULTICAST: int - PACKET_OTHERHOST: int - PACKET_OUTGOING: int - -if sys.platform == "linux": - AF_RDS: AddressFamily - PF_RDS: int - SOL_RDS: int - RDS_CANCEL_SENT_TO: int - RDS_CMSG_RDMA_ARGS: int - RDS_CMSG_RDMA_DEST: int - RDS_CMSG_RDMA_MAP: int - RDS_CMSG_RDMA_STATUS: int - RDS_CMSG_RDMA_UPDATE: int - RDS_CONG_MONITOR: int - RDS_FREE_MR: int - RDS_GET_MR: int - RDS_GET_MR_FOR_DEST: int - RDS_RDMA_DONTWAIT: int - RDS_RDMA_FENCE: int - RDS_RDMA_INVALIDATE: int - RDS_RDMA_NOTIFY_ME: int - RDS_RDMA_READWRITE: int - RDS_RDMA_SILENT: int - RDS_RDMA_USE_ONCE: int - RDS_RECVERR: int - + from _socket import ( + CAN_J1939 as CAN_J1939, + J1939_EE_INFO_NONE as J1939_EE_INFO_NONE, + J1939_EE_INFO_TX_ABORT as J1939_EE_INFO_TX_ABORT, + J1939_FILTER_MAX as J1939_FILTER_MAX, + J1939_IDLE_ADDR as J1939_IDLE_ADDR, + J1939_MAX_UNICAST_ADDR as J1939_MAX_UNICAST_ADDR, + J1939_NLA_BYTES_ACKED as J1939_NLA_BYTES_ACKED, + J1939_NLA_PAD as J1939_NLA_PAD, + J1939_NO_ADDR as J1939_NO_ADDR, + J1939_NO_NAME as J1939_NO_NAME, + J1939_NO_PGN as J1939_NO_PGN, + J1939_PGN_ADDRESS_CLAIMED as J1939_PGN_ADDRESS_CLAIMED, + J1939_PGN_ADDRESS_COMMANDED as J1939_PGN_ADDRESS_COMMANDED, + J1939_PGN_MAX as J1939_PGN_MAX, + J1939_PGN_PDU1_MAX as J1939_PGN_PDU1_MAX, + J1939_PGN_REQUEST as J1939_PGN_REQUEST, + SCM_J1939_DEST_ADDR as SCM_J1939_DEST_ADDR, + SCM_J1939_DEST_NAME as SCM_J1939_DEST_NAME, + SCM_J1939_ERRQUEUE as SCM_J1939_ERRQUEUE, + SCM_J1939_PRIO as SCM_J1939_PRIO, + SO_J1939_ERRQUEUE as SO_J1939_ERRQUEUE, + SO_J1939_FILTER as SO_J1939_FILTER, + SO_J1939_PROMISC as SO_J1939_PROMISC, + SO_J1939_SEND_PRIO as SO_J1939_SEND_PRIO, + ) if sys.platform == "win32": - SIO_RCVALL: int - SIO_KEEPALIVE_VALS: int - SIO_LOOPBACK_FAST_PATH: int - RCVALL_IPLEVEL: int - RCVALL_MAX: int - RCVALL_OFF: int - RCVALL_ON: int - RCVALL_SOCKETLEVELONLY: int - -if sys.platform == "linux": - AF_TIPC: AddressFamily - SOL_TIPC: int - TIPC_ADDR_ID: int - TIPC_ADDR_NAME: int - TIPC_ADDR_NAMESEQ: int - TIPC_CFG_SRV: int - TIPC_CLUSTER_SCOPE: int - TIPC_CONN_TIMEOUT: int - TIPC_CRITICAL_IMPORTANCE: int - TIPC_DEST_DROPPABLE: int - TIPC_HIGH_IMPORTANCE: int - TIPC_IMPORTANCE: int - TIPC_LOW_IMPORTANCE: int - TIPC_MEDIUM_IMPORTANCE: int - TIPC_NODE_SCOPE: int - TIPC_PUBLISHED: int - TIPC_SRC_DROPPABLE: int - TIPC_SUBSCR_TIMEOUT: int - TIPC_SUB_CANCEL: int - TIPC_SUB_PORTS: int - TIPC_SUB_SERVICE: int - TIPC_TOP_SRV: int - TIPC_WAIT_FOREVER: int - TIPC_WITHDRAWN: int - TIPC_ZONE_SCOPE: int - -if sys.platform == "linux": - AF_ALG: AddressFamily - SOL_ALG: int - ALG_OP_DECRYPT: int - ALG_OP_ENCRYPT: int - ALG_OP_SIGN: int - ALG_OP_VERIFY: int - ALG_SET_AEAD_ASSOCLEN: int - ALG_SET_AEAD_AUTHSIZE: int - ALG_SET_IV: int - ALG_SET_KEY: int - ALG_SET_OP: int - ALG_SET_PUBKEY: int - -if sys.platform == "linux" and sys.version_info >= (3, 7): - AF_VSOCK: AddressFamily - IOCTL_VM_SOCKETS_GET_LOCAL_CID: int - VMADDR_CID_ANY: int - VMADDR_CID_HOST: int - VMADDR_PORT_ANY: int - 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 - -AF_LINK: AddressFamily # Availability: BSD, macOS - -# BDADDR_* and HCI_* listed with other bluetooth constants below - -SO_DOMAIN: int -SO_PASSSEC: int -SO_PEERSEC: int -SO_PROTOCOL: int -TCP_CONGESTION: int -TCP_USER_TIMEOUT: int - -if sys.platform == "linux" and sys.version_info >= (3, 8): - AF_QIPCRTR: AddressFamily - -# Semi-documented constants -# (Listed under "Socket families" in the docs, but not "Constants") - -if sys.platform == "linux": - # Netlink is defined by Linux - AF_NETLINK: AddressFamily - NETLINK_ARPD: int - NETLINK_CRYPTO: int - NETLINK_DNRTMSG: int - NETLINK_FIREWALL: int - NETLINK_IP6_FW: int - NETLINK_NFLOG: int - NETLINK_ROUTE6: int - NETLINK_ROUTE: int - NETLINK_SKIP: int - NETLINK_TAPBASE: int - NETLINK_TCPDIAG: int - NETLINK_USERSOCK: int - NETLINK_W1: int - NETLINK_XFRM: int - -if sys.platform != "win32" and sys.platform != "darwin": - # Linux and some BSD support is explicit in the docs - # Windows and macOS do not support in practice - AF_BLUETOOTH: AddressFamily - BTPROTO_HCI: int - BTPROTO_L2CAP: int - BTPROTO_RFCOMM: int - BTPROTO_SCO: int # not in FreeBSD - - BDADDR_ANY: str - BDADDR_LOCAL: str - - 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": - # PF_SYSTEM is defined by macOS - PF_SYSTEM: int - SYSPROTO_CONTROL: int + from _socket import ( + RCVALL_IPLEVEL as RCVALL_IPLEVEL, + 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, + ) + +_T = TypeVar("_T") + +# Re-exported from errno +EBADF: int +EAGAIN: int +EWOULDBLOCK: int -# enum versions of above flags class AddressFamily(IntEnum): AF_UNIX: int AF_INET: int @@ -543,6 +423,48 @@ class AddressFamily(IntEnum): AF_WANPIPE: int AF_X25: int +AF_UNIX: AddressFamily +AF_INET: AddressFamily +AF_INET6: AddressFamily +AF_AAL5: AddressFamily +AF_APPLETALK: AddressFamily +AF_ASH: AddressFamily +AF_ATMPVC: AddressFamily +AF_ATMSVC: AddressFamily +AF_AX25: AddressFamily +AF_BRIDGE: AddressFamily +AF_DECnet: AddressFamily +AF_ECONET: AddressFamily +AF_IPX: AddressFamily +AF_IRDA: AddressFamily +AF_KEY: AddressFamily +AF_LLC: AddressFamily +AF_NETBEUI: AddressFamily +AF_NETROM: AddressFamily +AF_PPPOX: AddressFamily +AF_ROSE: AddressFamily +AF_ROUTE: AddressFamily +AF_SECURITY: AddressFamily +AF_SNA: AddressFamily +AF_SYSTEM: AddressFamily +AF_UNSPEC: AddressFamily +AF_WANPIPE: AddressFamily +AF_X25: AddressFamily +if sys.platform == "linux": + AF_CAN: AddressFamily + AF_PACKET: AddressFamily + AF_RDS: AddressFamily + AF_TIPC: AddressFamily + AF_ALG: AddressFamily + AF_NETLINK: AddressFamily + if sys.version_info >= (3, 7): + AF_VSOCK: AddressFamily + if sys.version_info >= (3, 8): + AF_QIPCRTR: AddressFamily +AF_LINK: AddressFamily # availability: BSD, macOS +if sys.platform != "win32" and sys.platform != "darwin": + AF_BLUETOOTH: AddressFamily + class SocketKind(IntEnum): SOCK_STREAM: int SOCK_DGRAM: int @@ -552,14 +474,14 @@ class SocketKind(IntEnum): SOCK_CLOEXEC: int SOCK_NONBLOCK: int -class AddressInfo(IntFlag): - AI_ADDRCONFIG: int - AI_ALL: int - AI_CANONNAME: int - AI_NUMERICHOST: int - AI_NUMERICSERV: int - AI_PASSIVE: int - AI_V4MAPPED: int +SOCK_STREAM: SocketKind +SOCK_DGRAM: SocketKind +SOCK_RAW: SocketKind +SOCK_RDM: SocketKind +SOCK_SEQPACKET: SocketKind +if sys.platform == "linux": + SOCK_CLOEXEC: SocketKind + SOCK_NONBLOCK: SocketKind class MsgFlag(IntFlag): MSG_CTRUNC: int @@ -571,61 +493,62 @@ class MsgFlag(IntFlag): MSG_TRUNC: int MSG_WAITALL: int -# ----- Exceptions ----- - -error = OSError - -class herror(error): - def __init__(self, herror: int = ..., string: str = ...) -> None: ... - -class gaierror(error): - def __init__(self, error: int = ..., string: str = ...) -> None: ... - -class timeout(error): - def __init__(self, error: int = ..., string: str = ...) -> None: ... - -# ----- Classes ----- +MSG_BCAST: MsgFlag +MSG_BTAG: MsgFlag +MSG_CMSG_CLOEXEC: MsgFlag +MSG_CONFIRM: MsgFlag +MSG_CTRUNC: MsgFlag +MSG_DONTROUTE: MsgFlag +MSG_DONTWAIT: MsgFlag +MSG_EOF: MsgFlag +MSG_EOR: MsgFlag +MSG_ERRQUEUE: MsgFlag +MSG_ETAG: MsgFlag +MSG_FASTOPEN: MsgFlag +MSG_MCAST: MsgFlag +MSG_MORE: MsgFlag +MSG_NOSIGNAL: MsgFlag +MSG_NOTIFICATION: MsgFlag +MSG_OOB: MsgFlag +MSG_PEEK: MsgFlag +MSG_TRUNC: MsgFlag +MSG_WAITALL: MsgFlag -# Addresses can be either tuples of varying lengths (AF_INET, AF_INET6, -# AF_NETLINK, AF_TIPC) or strings (AF_UNIX). -_Address = Union[Tuple[Any, ...], str] -_RetAddress = Any -# TODO Most methods allow bytes as address objects +class AddressInfo(IntFlag): + AI_ADDRCONFIG: int + AI_ALL: int + AI_CANONNAME: int + AI_NUMERICHOST: int + AI_NUMERICSERV: int + AI_PASSIVE: int + AI_V4MAPPED: int -_WriteBuffer = Union[bytearray, memoryview] +AI_ADDRCONFIG: AddressInfo +AI_ALL: AddressInfo +AI_CANONNAME: AddressInfo +AI_DEFAULT: AddressInfo +AI_MASK: AddressInfo +AI_NUMERICHOST: AddressInfo +AI_NUMERICSERV: AddressInfo +AI_PASSIVE: AddressInfo +AI_V4MAPPED: AddressInfo +AI_V4MAPPED_CFG: AddressInfo -_CMSG = Tuple[int, int, bytes] -_SelfT = TypeVar("_SelfT", bound=socket) +if sys.platform == "win32": + errorTab: dict[int, str] # undocumented -class socket: - family: int - type: int - proto: int - def __init__(self, family: int = ..., type: int = ..., proto: int = ..., fileno: Optional[int] = ...) -> None: ... - def __enter__(self: _SelfT) -> _SelfT: ... - def __exit__(self, *args: Any) -> None: ... - # --- methods --- - def accept(self) -> Tuple[socket, _RetAddress]: ... - def bind(self, address: Union[_Address, bytes]) -> None: ... - def close(self) -> None: ... - def connect(self, address: Union[_Address, bytes]) -> None: ... - def connect_ex(self, address: Union[_Address, bytes]) -> int: ... - def detach(self) -> int: ... - def dup(self) -> socket: ... - def fileno(self) -> int: ... - def get_inheritable(self) -> bool: ... - def getpeername(self) -> _RetAddress: ... - def getsockname(self) -> _RetAddress: ... - @overload - def getsockopt(self, level: int, optname: int) -> int: ... - @overload - def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ... - if sys.version_info >= (3, 7): - def getblocking(self) -> bool: ... - def gettimeout(self) -> Optional[float]: ... - if sys.platform == "win32": - def ioctl(self, control: int, option: Union[int, Tuple[int, int, int], bool]) -> None: ... - def listen(self, __backlog: int = ...) -> None: ... +class socket(_socket.socket): + def __init__( + self, + family: Union[AddressFamily, int] = ..., + type: Union[SocketKind, int] = ..., + proto: int = ..., + fileno: Optional[int] = ..., + ) -> None: ... + def __enter__(self: Self) -> Self: ... + def __exit__(self, *args: object) -> None: ... + def dup(self: _T) -> _T: ... # noqa: F811 + def accept(self) -> tuple[socket, _RetAddress]: ... # Note that the makefile's documented windows-specific behavior is not represented # mode strings with duplicates are intentionally excluded @overload @@ -648,62 +571,56 @@ class socket: errors: Optional[str] = ..., newline: Optional[str] = ..., ) -> BinaryIO: ... - def recv(self, bufsize: int, flags: int = ...) -> bytes: ... - def recvfrom(self, bufsize: int, flags: int = ...) -> Tuple[bytes, _RetAddress]: ... - if sys.platform != "win32": - def recvmsg(self, __bufsize: int, __ancbufsize: int = ..., __flags: int = ...) -> Tuple[bytes, List[_CMSG], int, Any]: ... - def recvmsg_into( - self, __buffers: Iterable[_WriteBuffer], __ancbufsize: int = ..., __flags: int = ... - ) -> Tuple[int, List[_CMSG], int, Any]: ... - def recvfrom_into(self, buffer: _WriteBuffer, nbytes: int = ..., flags: int = ...) -> Tuple[int, _RetAddress]: ... - def recv_into(self, buffer: _WriteBuffer, nbytes: int = ..., flags: int = ...) -> int: ... - def send(self, data: bytes, flags: int = ...) -> int: ... - def sendall(self, data: bytes, flags: int = ...) -> None: ... # return type: None on success - @overload - def sendto(self, data: bytes, address: _Address) -> int: ... - @overload - def sendto(self, data: bytes, flags: int, address: _Address) -> int: ... - if sys.platform != "win32": - def sendmsg( - self, __buffers: Iterable[bytes], __ancdata: Iterable[_CMSG] = ..., __flags: int = ..., __address: _Address = ... - ) -> int: ... - if sys.platform == "linux": - def sendmsg_afalg( - self, msg: Iterable[bytes] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = ... - ) -> int: ... def sendfile(self, file: BinaryIO, offset: int = ..., count: Optional[int] = ...) -> int: ... + @property + def family(self) -> AddressFamily: ... # type: ignore + @property + def type(self) -> SocketKind: ... # type: ignore + def get_inheritable(self) -> bool: ... def set_inheritable(self, inheritable: bool) -> None: ... - def setblocking(self, flag: bool) -> None: ... - def settimeout(self, value: Optional[float]) -> None: ... - @overload - def setsockopt(self, level: int, optname: int, value: Union[int, bytes]) -> None: ... - @overload - def setsockopt(self, level: int, optname: int, value: None, optlen: int) -> None: ... - if sys.platform == "win32": - def share(self, process_id: int) -> bytes: ... - def shutdown(self, how: int) -> None: ... -# ----- Functions ----- +def fromfd(fd: _FD, family: AddressFamily | int, type: SocketKind | int, proto: int = ...) -> socket: ... -if sys.version_info >= (3, 7): - def close(fd: int) -> None: ... +if sys.platform != "win32": + if sys.version_info >= (3, 9): + # flags and address appear to be unused in send_fds and recv_fds + def send_fds( + sock: socket, buffers: Iterable[bytes], fds: Union[bytes, Iterable[int]], flags: int = ..., address: None = ... + ) -> int: ... + def recv_fds(sock: socket, bufsize: int, maxfds: int, flags: int = ...) -> tuple[bytes, list[int], int, Any]: ... + +if sys.platform == "win32": + def fromshare(info: bytes) -> socket: ... + +if sys.platform == "win32": + def socketpair(family: int = ..., type: int = ..., proto: int = ...) -> tuple[socket, socket]: ... +else: + def socketpair( # type: ignore + family: Union[int, AddressFamily, None] = ..., type: Union[SocketType, int] = ..., proto: int = ... + ) -> tuple[socket, socket]: ... + +class SocketIO(RawIOBase): + def __init__(self, sock: socket, mode: Literal["r", "w", "rw", "rb", "wb", "rwb"]) -> None: ... + def readinto(self, b: WriteableBuffer) -> Optional[int]: ... + def write(self, b: ReadableBuffer) -> Optional[int]: ... + @property + def name(self) -> int: ... # return value is really "int" + @property + def mode(self) -> Literal["rb", "wb", "rwb"]: ... + +def getfqdn(name: str = ...) -> str: ... def create_connection( - address: Tuple[Optional[str], int], - timeout: Optional[float] = ..., - source_address: Optional[Tuple[Union[bytearray, bytes, str], int]] = ..., + address: tuple[Optional[str], int], + timeout: Optional[float] = ..., # noqa: F811 + source_address: Optional[tuple[Union[bytearray, bytes, str], int]] = ..., ) -> socket: ... if sys.version_info >= (3, 8): + def has_dualstack_ipv6() -> bool: ... def create_server( address: _Address, *, family: int = ..., backlog: Optional[int] = ..., reuse_port: bool = ..., dualstack_ipv6: bool = ... ) -> socket: ... - def has_dualstack_ipv6() -> bool: ... - -def fromfd(fd: int, family: int, type: int, proto: int = ...) -> socket: ... - -if sys.platform == "win32": - def fromshare(info: bytes) -> socket: ... # the 5th tuple item is an address def getaddrinfo( @@ -713,50 +630,4 @@ def getaddrinfo( type: int = ..., proto: int = ..., flags: int = ..., -) -> List[Tuple[AddressFamily, SocketKind, int, str, Union[Tuple[str, int], Tuple[str, int, int, int]]]]: ... -def getfqdn(name: str = ...) -> str: ... -def gethostbyname(hostname: str) -> str: ... -def gethostbyname_ex(hostname: str) -> Tuple[str, List[str], List[str]]: ... -def gethostname() -> str: ... -def gethostbyaddr(ip_address: str) -> Tuple[str, List[str], List[str]]: ... -def getnameinfo(sockaddr: Union[Tuple[str, int], Tuple[str, int, int, int]], flags: int) -> Tuple[str, str]: ... -def getprotobyname(protocolname: str) -> int: ... -def getservbyname(servicename: str, protocolname: str = ...) -> int: ... -def getservbyport(port: int, protocolname: str = ...) -> str: ... - -if sys.platform == "win32": - def socketpair(family: int = ..., type: int = ..., proto: int = ...) -> Tuple[socket, socket]: ... - -else: - def socketpair(family: Optional[int] = ..., type: int = ..., proto: int = ...) -> Tuple[socket, socket]: ... - -def ntohl(x: int) -> int: ... # param & ret val are 32-bit ints -def ntohs(x: int) -> int: ... # param & ret val are 16-bit ints -def htonl(x: int) -> int: ... # param & ret val are 32-bit ints -def htons(x: int) -> int: ... # param & ret val are 16-bit ints -def inet_aton(ip_string: str) -> bytes: ... # ret val 4 bytes in length -def inet_ntoa(packed_ip: bytes) -> str: ... -def inet_pton(address_family: int, ip_string: str) -> bytes: ... -def inet_ntop(address_family: int, packed_ip: bytes) -> str: ... - -if sys.version_info >= (3, 9): - if sys.platform != "win32": - # flags and address appear to be unused in send_fds and recv_fds - def send_fds( - sock: socket, buffers: Iterable[bytes], fds: Union[bytes, Iterable[int]], flags: int = ..., address: None = ... - ) -> int: ... - def recv_fds(sock: socket, bufsize: int, maxfds: int, flags: int = ...) -> Tuple[bytes, List[int], int, Any]: ... - -def CMSG_LEN(length: int) -> int: ... -def CMSG_SPACE(length: int) -> int: ... -def getdefaulttimeout() -> Optional[float]: ... -def setdefaulttimeout(timeout: Optional[float]) -> None: ... - -if sys.platform != "win32": - def sethostname(name: str) -> None: ... - -# 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: ... +) -> list[tuple[AddressFamily, SocketKind, int, str, Union[tuple[str, int], tuple[str, int, int, int]]]]: ... diff --git a/mypy/typeshed/stdlib/socketserver.pyi b/mypy/typeshed/stdlib/socketserver.pyi index f0617e393b7e..1403d9cee0ed 100644 --- a/mypy/typeshed/stdlib/socketserver.pyi +++ b/mypy/typeshed/stdlib/socketserver.pyi @@ -1,15 +1,18 @@ import sys import types -from socket import SocketType -from typing import Any, BinaryIO, Callable, ClassVar, List, Optional, Tuple, Type, TypeVar, Union +from _typeshed import Self +from socket import socket as _socket +from typing import Any, BinaryIO, Callable, ClassVar, Optional, Set, Tuple, Type, TypeVar, Union _T = TypeVar("_T") +_RequestType = Union[_socket, Tuple[bytes, _socket]] +_AddressType = Union[Tuple[str, int], str] class BaseServer: address_family: int RequestHandlerClass: Callable[..., BaseRequestHandler] - server_address: Tuple[str, int] - socket: SocketType + server_address: tuple[str, int] + socket: _socket allow_reuse_address: bool request_queue_size: int socket_type: int @@ -20,35 +23,51 @@ class BaseServer: def serve_forever(self, poll_interval: float = ...) -> None: ... def shutdown(self) -> None: ... def server_close(self) -> None: ... - def finish_request(self, request: bytes, client_address: Tuple[str, int]) -> None: ... - def get_request(self) -> Tuple[SocketType, Tuple[str, int]]: ... - def handle_error(self, request: bytes, client_address: Tuple[str, int]) -> None: ... + def finish_request(self, request: _RequestType, client_address: _AddressType) -> None: ... + def get_request(self) -> tuple[Any, Any]: ... + def handle_error(self, request: _RequestType, client_address: _AddressType) -> None: ... def handle_timeout(self) -> None: ... - def process_request(self, request: bytes, client_address: Tuple[str, int]) -> None: ... + def process_request(self, request: _RequestType, client_address: _AddressType) -> None: ... def server_activate(self) -> None: ... def server_bind(self) -> None: ... - def verify_request(self, request: bytes, client_address: Tuple[str, int]) -> bool: ... - def __enter__(self: _T) -> _T: ... + def verify_request(self, request: _RequestType, client_address: _AddressType) -> bool: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[types.TracebackType] ) -> None: ... def service_actions(self) -> None: ... + def shutdown_request(self, request: _RequestType) -> None: ... # undocumented + def close_request(self, request: _RequestType) -> None: ... # undocumented class TCPServer(BaseServer): def __init__( self, - server_address: Tuple[str, int], + server_address: tuple[str, int], RequestHandlerClass: Callable[..., BaseRequestHandler], bind_and_activate: bool = ..., ) -> None: ... + def get_request(self) -> tuple[_socket, Any]: ... + def finish_request(self, request: _RequestType, client_address: _AddressType) -> None: ... + def handle_error(self, request: _RequestType, client_address: _AddressType) -> None: ... + def process_request(self, request: _RequestType, client_address: _AddressType) -> None: ... + def verify_request(self, request: _RequestType, client_address: _AddressType) -> bool: ... + def shutdown_request(self, request: _RequestType) -> None: ... # undocumented + def close_request(self, request: _RequestType) -> None: ... # undocumented class UDPServer(BaseServer): def __init__( self, - server_address: Tuple[str, int], + server_address: tuple[str, int], RequestHandlerClass: Callable[..., BaseRequestHandler], bind_and_activate: bool = ..., ) -> None: ... + def get_request(self) -> tuple[tuple[bytes, _socket], Any]: ... + def finish_request(self, request: _RequestType, client_address: _AddressType) -> None: ... + def handle_error(self, request: _RequestType, client_address: _AddressType) -> None: ... + def process_request(self, request: _RequestType, client_address: _AddressType) -> None: ... + def verify_request(self, request: _RequestType, client_address: _AddressType) -> bool: ... + def shutdown_request(self, request: _RequestType) -> None: ... # undocumented + def close_request(self, request: _RequestType) -> None: ... # undocumented if sys.platform != "win32": class UnixStreamServer(BaseServer): @@ -69,22 +88,22 @@ if sys.platform != "win32": if sys.platform != "win32": class ForkingMixIn: timeout: Optional[float] # undocumented - active_children: Optional[List[int]] # undocumented + active_children: Optional[Set[int]] # undocumented max_children: int # undocumented if sys.version_info >= (3, 7): block_on_close: bool def collect_children(self, *, blocking: bool = ...) -> None: ... # undocumented def handle_timeout(self) -> None: ... # undocumented def service_actions(self) -> None: ... # undocumented - def process_request(self, request: bytes, client_address: Tuple[str, int]) -> None: ... + def process_request(self, request: _RequestType, client_address: _AddressType) -> None: ... def server_close(self) -> None: ... class ThreadingMixIn: daemon_threads: bool if sys.version_info >= (3, 7): block_on_close: bool - def process_request_thread(self, request: bytes, client_address: Tuple[str, int]) -> None: ... # undocumented - def process_request(self, request: bytes, client_address: Tuple[str, int]) -> None: ... + def process_request_thread(self, request: _RequestType, client_address: _AddressType) -> None: ... # undocumented + def process_request(self, request: _RequestType, client_address: _AddressType) -> None: ... def server_close(self) -> None: ... if sys.platform != "win32": @@ -100,15 +119,15 @@ if sys.platform != "win32": class BaseRequestHandler: # Those are technically of types, respectively: - # * Union[SocketType, Tuple[bytes, SocketType]] - # * Union[Tuple[str, int], str] + # * _RequestType + # * _AddressType # But there are some concerns that having unions here would cause # too much inconvenience to people using it (see # https://github.com/python/typeshed/pull/384#issuecomment-234649696) request: Any client_address: Any server: BaseServer - def __init__(self, request: Any, client_address: Any, server: BaseServer) -> None: ... + def __init__(self, request: _RequestType, client_address: _AddressType, server: BaseServer) -> None: ... def setup(self) -> None: ... def handle(self) -> None: ... def finish(self) -> None: ... @@ -118,12 +137,12 @@ class StreamRequestHandler(BaseRequestHandler): wbufsize: ClassVar[int] # Undocumented timeout: ClassVar[Optional[float]] # Undocumented disable_nagle_algorithm: ClassVar[bool] # Undocumented - connection: SocketType # Undocumented + connection: _socket # Undocumented rfile: BinaryIO wfile: BinaryIO class DatagramRequestHandler(BaseRequestHandler): - packet: SocketType # Undocumented - socket: SocketType # Undocumented + packet: _socket # Undocumented + socket: _socket # Undocumented rfile: BinaryIO wfile: BinaryIO diff --git a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi index c53141856ca8..3fb72de659d2 100644 --- a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi +++ b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi @@ -1,5 +1,5 @@ import sys -from _typeshed import StrOrBytesPath +from _typeshed import Self, StrOrBytesPath from datetime import date, datetime, time from typing import Any, Callable, Generator, Iterable, Iterator, List, Optional, Protocol, Tuple, Type, TypeVar, Union @@ -158,7 +158,7 @@ class Connection(object): sleep: float = ..., ) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - def __enter__(self) -> Connection: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, t: Optional[type], exc: Optional[BaseException], tb: Optional[Any]) -> None: ... class Cursor(Iterator[Any]): diff --git a/mypy/typeshed/stdlib/ssl.pyi b/mypy/typeshed/stdlib/ssl.pyi index ccae3e3b3c11..02dd1d3fac6e 100644 --- a/mypy/typeshed/stdlib/ssl.pyi +++ b/mypy/typeshed/stdlib/ssl.pyi @@ -1,7 +1,7 @@ import enum import socket import sys -from _typeshed import StrPath +from _typeshed import ReadableBuffer, StrPath, WriteableBuffer from typing import Any, Callable, Dict, Iterable, List, NamedTuple, Optional, Set, Tuple, Type, Union, overload from typing_extensions import Literal @@ -247,15 +247,20 @@ class SSLSocket(socket.socket): def connect(self, addr: Union[socket._Address, bytes]) -> None: ... def connect_ex(self, addr: Union[socket._Address, bytes]) -> int: ... def recv(self, buflen: int = ..., flags: int = ...) -> bytes: ... - def recv_into(self, buffer: socket._WriteBuffer, nbytes: Optional[int] = ..., flags: int = ...) -> int: ... + def recv_into(self, buffer: WriteableBuffer, nbytes: Optional[int] = ..., flags: int = ...) -> int: ... def recvfrom(self, buflen: int = ..., flags: int = ...) -> tuple[bytes, socket._RetAddress]: ... def recvfrom_into( - self, buffer: socket._WriteBuffer, nbytes: Optional[int] = ..., flags: int = ... + self, buffer: WriteableBuffer, nbytes: Optional[int] = ..., flags: int = ... ) -> tuple[int, socket._RetAddress]: ... + def send(self, data: ReadableBuffer, flags: int = ...) -> int: ... + def sendall(self, data: ReadableBuffer, flags: int = ...) -> None: ... @overload - def sendto(self, data: bytes, flags_or_addr: socket._Address) -> int: ... + def sendto(self, data: ReadableBuffer, flags_or_addr: socket._Address) -> int: ... @overload - def sendto(self, data: bytes, flags_or_addr: Union[int, socket._Address], addr: Optional[socket._Address] = ...) -> int: ... + def sendto( + self, data: ReadableBuffer, flags_or_addr: Union[int, socket._Address], addr: Optional[socket._Address] = ... + ) -> int: ... + def shutdown(self, how: int) -> None: ... def read(self, len: int = ..., buffer: Optional[bytearray] = ...) -> bytes: ... def write(self, data: bytes) -> int: ... def do_handshake(self, block: bool = ...) -> None: ... # block is undocumented diff --git a/mypy/typeshed/stdlib/subprocess.pyi b/mypy/typeshed/stdlib/subprocess.pyi index 9a431f082c37..df63c5a0a709 100644 --- a/mypy/typeshed/stdlib/subprocess.pyi +++ b/mypy/typeshed/stdlib/subprocess.pyi @@ -1,5 +1,5 @@ import sys -from _typeshed import StrOrBytesPath +from _typeshed import Self, StrOrBytesPath from types import TracebackType from typing import IO, Any, AnyStr, Callable, Generic, Mapping, Optional, Sequence, Tuple, Type, TypeVar, Union, overload from typing_extensions import Literal @@ -34,7 +34,6 @@ if sys.platform == "win32": else: _ENV = Union[Mapping[bytes, StrOrBytesPath], Mapping[str, StrOrBytesPath]] -_S = TypeVar("_S") _T = TypeVar("_T") class CompletedProcess(Generic[_T]): @@ -1007,7 +1006,7 @@ class Popen(Generic[AnyStr]): def send_signal(self, sig: int) -> None: ... def terminate(self) -> None: ... def kill(self) -> None: ... - def __enter__(self: _S) -> _S: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, type: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[TracebackType] ) -> None: ... diff --git a/mypy/typeshed/stdlib/sunau.pyi b/mypy/typeshed/stdlib/sunau.pyi index 79d0881c96c2..04a6832d8b44 100644 --- a/mypy/typeshed/stdlib/sunau.pyi +++ b/mypy/typeshed/stdlib/sunau.pyi @@ -1,4 +1,5 @@ import sys +from _typeshed import Self from typing import IO, Any, NamedTuple, NoReturn, Optional, Union _File = Union[str, IO[bytes]] @@ -30,7 +31,7 @@ class _sunau_params(NamedTuple): class Au_read: def __init__(self, f: _File) -> None: ... - def __enter__(self) -> Au_read: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, *args: Any) -> None: ... def getfp(self) -> Optional[IO[bytes]]: ... def rewind(self) -> None: ... @@ -50,7 +51,7 @@ class Au_read: class Au_write: def __init__(self, f: _File) -> None: ... - def __enter__(self) -> Au_write: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, *args: Any) -> None: ... def setnchannels(self, nchannels: int) -> None: ... def getnchannels(self) -> int: ... diff --git a/mypy/typeshed/stdlib/sys.pyi b/mypy/typeshed/stdlib/sys.pyi index 8370f0b29477..5f0f4ab99534 100644 --- a/mypy/typeshed/stdlib/sys.pyi +++ b/mypy/typeshed/stdlib/sys.pyi @@ -2,6 +2,7 @@ import sys from builtins import object as _object from importlib.abc import Loader, PathEntryFinder from importlib.machinery import ModuleSpec +from io import TextIOWrapper from types import FrameType, ModuleType, TracebackType from typing import ( Any, @@ -21,6 +22,7 @@ from typing import ( Union, overload, ) +from typing_extensions import Literal _T = TypeVar("_T") @@ -42,7 +44,7 @@ if sys.platform != "win32": argv: List[str] base_exec_prefix: str base_prefix: str -byteorder: str +byteorder: Literal["little", "big"] builtin_module_names: Sequence[str] # actually a tuple of strings copyright: str if sys.platform == "win32": @@ -79,9 +81,9 @@ stdout: TextIO stderr: TextIO if sys.version_info >= (3, 10): stdlib_module_names: FrozenSet[str] -__stdin__: TextIO -__stdout__: TextIO -__stderr__: TextIO +__stdin__: TextIOWrapper +__stdout__: TextIOWrapper +__stderr__: TextIOWrapper tracebacklimit: int version: str api_version: int diff --git a/mypy/typeshed/stdlib/sysconfig.pyi b/mypy/typeshed/stdlib/sysconfig.pyi index b8044bcaa615..c5f00ee9ea08 100644 --- a/mypy/typeshed/stdlib/sysconfig.pyi +++ b/mypy/typeshed/stdlib/sysconfig.pyi @@ -7,7 +7,7 @@ def get_config_vars() -> Dict[str, Any]: ... def get_config_vars(arg: str, *args: str) -> List[Any]: ... def get_scheme_names() -> Tuple[str, ...]: ... def get_path_names() -> Tuple[str, ...]: ... -def get_path(name: str, scheme: str = ..., vars: Optional[Dict[str, Any]] = ..., expand: bool = ...) -> Optional[str]: ... +def get_path(name: str, scheme: str = ..., vars: Optional[Dict[str, Any]] = ..., expand: bool = ...) -> str: ... def get_paths(scheme: str = ..., vars: Optional[Dict[str, Any]] = ..., expand: bool = ...) -> Dict[str, str]: ... def get_python_version() -> str: ... def get_platform() -> str: ... diff --git a/mypy/typeshed/stdlib/tarfile.pyi b/mypy/typeshed/stdlib/tarfile.pyi index 16f759e986e6..7258ced824b5 100644 --- a/mypy/typeshed/stdlib/tarfile.pyi +++ b/mypy/typeshed/stdlib/tarfile.pyi @@ -1,12 +1,15 @@ +import bz2 import io import sys -from _typeshed import StrOrBytesPath, StrPath +from _typeshed import Self, StrOrBytesPath, StrPath 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, Dict, List, Optional, Protocol, Set, Tuple, Type, Union, overload +from typing import IO, Dict, List, Optional, Protocol, Set, Tuple, Type, TypeVar, Union, overload from typing_extensions import Literal +_TF = TypeVar("_TF", bound=TarFile) + class _Fileobj(Protocol): def read(self, __size: int) -> bytes: ... def write(self, __b: bytes) -> object: ... @@ -17,6 +20,12 @@ class _Fileobj(Protocol): # name: str | bytes # mode: Literal["rb", "r+b", "wb", "xb"] +class _Bz2ReadableFileobj(bz2._ReadableFileobj): + def close(self) -> object: ... + +class _Bz2WritableFileobj(bz2._WritableFileobj): + def close(self) -> object: ... + # tar constants NUL: bytes BLOCKSIZE: int @@ -115,14 +124,14 @@ class TarFile: errorlevel: Optional[int] = ..., copybufsize: Optional[int] = ..., # undocumented ) -> None: ... - def __enter__(self) -> TarFile: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> None: ... def __iter__(self) -> Iterator[TarInfo]: ... @classmethod def open( - cls, + cls: Type[_TF], name: Optional[StrOrBytesPath] = ..., mode: str = ..., fileobj: Optional[IO[bytes]] = ..., # depends on mode @@ -137,10 +146,10 @@ class TarFile: pax_headers: Optional[Mapping[str, str]] = ..., debug: Optional[int] = ..., errorlevel: Optional[int] = ..., - ) -> TarFile: ... + ) -> _TF: ... @classmethod def taropen( - cls, + cls: Type[_TF], name: Optional[StrOrBytesPath], mode: Literal["r", "a", "w", "x"] = ..., fileobj: Optional[_Fileobj] = ..., @@ -154,11 +163,11 @@ class TarFile: pax_headers: Optional[Mapping[str, str]] = ..., debug: Optional[int] = ..., errorlevel: Optional[int] = ..., - ) -> TarFile: ... + ) -> _TF: ... @overload @classmethod def gzopen( - cls, + cls: Type[_TF], name: Optional[StrOrBytesPath], mode: Literal["r"] = ..., fileobj: Optional[_GzipReadableFileobj] = ..., @@ -172,11 +181,11 @@ class TarFile: pax_headers: Optional[Mapping[str, str]] = ..., debug: Optional[int] = ..., errorlevel: Optional[int] = ..., - ) -> TarFile: ... + ) -> _TF: ... @overload @classmethod def gzopen( - cls, + cls: Type[_TF], name: Optional[StrOrBytesPath], mode: Literal["w", "x"], fileobj: Optional[_GzipWritableFileobj] = ..., @@ -190,13 +199,32 @@ class TarFile: pax_headers: Optional[Mapping[str, str]] = ..., debug: Optional[int] = ..., errorlevel: Optional[int] = ..., - ) -> TarFile: ... + ) -> _TF: ... + @overload @classmethod def bz2open( - cls, + cls: Type[_TF], name: Optional[StrOrBytesPath], - mode: Literal["r", "w", "x"] = ..., - fileobj: Optional[IO[bytes]] = ..., + mode: Literal["w", "x"], + fileobj: Optional[_Bz2WritableFileobj] = ..., + compresslevel: int = ..., + *, + format: Optional[int] = ..., + tarinfo: Optional[Type[TarInfo]] = ..., + dereference: Optional[bool] = ..., + ignore_zeros: Optional[bool] = ..., + encoding: Optional[str] = ..., + pax_headers: Optional[Mapping[str, str]] = ..., + debug: Optional[int] = ..., + errorlevel: Optional[int] = ..., + ) -> _TF: ... + @overload + @classmethod + def bz2open( + cls: Type[_TF], + name: Optional[StrOrBytesPath], + mode: Literal["r"] = ..., + fileobj: Optional[_Bz2ReadableFileobj] = ..., compresslevel: int = ..., *, format: Optional[int] = ..., @@ -207,10 +235,10 @@ class TarFile: pax_headers: Optional[Mapping[str, str]] = ..., debug: Optional[int] = ..., errorlevel: Optional[int] = ..., - ) -> TarFile: ... + ) -> _TF: ... @classmethod def xzopen( - cls, + cls: Type[_TF], name: Optional[StrOrBytesPath], mode: Literal["r", "w", "x"] = ..., fileobj: Optional[IO[bytes]] = ..., @@ -224,7 +252,7 @@ class TarFile: pax_headers: Optional[Mapping[str, str]] = ..., debug: Optional[int] = ..., errorlevel: Optional[int] = ..., - ) -> TarFile: ... + ) -> _TF: ... def getmember(self, name: str) -> TarInfo: ... def getmembers(self) -> List[TarInfo]: ... def getnames(self) -> List[str]: ... diff --git a/mypy/typeshed/stdlib/telnetlib.pyi b/mypy/typeshed/stdlib/telnetlib.pyi index 0ee5b760b184..9910e7cd195a 100644 --- a/mypy/typeshed/stdlib/telnetlib.pyi +++ b/mypy/typeshed/stdlib/telnetlib.pyi @@ -1,4 +1,5 @@ import socket +from _typeshed import Self from typing import Any, Callable, Match, Optional, Pattern, Sequence, Tuple, Union DEBUGLEVEL: int @@ -109,5 +110,5 @@ class Telnet: def expect( self, list: Sequence[Union[Pattern[bytes], bytes]], timeout: Optional[float] = ... ) -> Tuple[int, Optional[Match[bytes]], bytes]: ... - def __enter__(self) -> Telnet: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, type: Any, value: Any, traceback: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/tempfile.pyi b/mypy/typeshed/stdlib/tempfile.pyi index f618ce1751d2..9d2fb7a5a7c5 100644 --- a/mypy/typeshed/stdlib/tempfile.pyi +++ b/mypy/typeshed/stdlib/tempfile.pyi @@ -1,7 +1,8 @@ import os import sys +from _typeshed import Self from types import TracebackType -from typing import IO, Any, AnyStr, Generic, Iterable, Iterator, List, Optional, Tuple, Type, TypeVar, Union, overload +from typing import IO, Any, AnyStr, Generic, Iterable, Iterator, List, Optional, Tuple, Type, Union, overload from typing_extensions import Literal if sys.version_info >= (3, 9): @@ -12,7 +13,6 @@ TMP_MAX: int tempdir: Optional[str] template: str -_S = TypeVar("_S") _DirT = Union[AnyStr, os.PathLike[AnyStr]] if sys.version_info >= (3, 8): @@ -168,7 +168,7 @@ class _TemporaryFileWrapper(Generic[AnyStr], IO[AnyStr]): name: str delete: bool def __init__(self, file: IO[AnyStr], name: str, delete: bool = ...) -> None: ... - def __enter__(self) -> _TemporaryFileWrapper[AnyStr]: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, exc: Optional[Type[BaseException]], value: Optional[BaseException], tb: Optional[TracebackType] ) -> Optional[bool]: ... @@ -289,7 +289,7 @@ class SpooledTemporaryFile(IO[AnyStr]): dir: Optional[str] = ..., ) -> None: ... def rollover(self) -> None: ... - def __enter__(self: _S) -> _S: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> Optional[bool]: ... diff --git a/mypy/typeshed/stdlib/tkinter/__init__.pyi b/mypy/typeshed/stdlib/tkinter/__init__.pyi index 8d328abae4d5..e4265c2a81fa 100644 --- a/mypy/typeshed/stdlib/tkinter/__init__.pyi +++ b/mypy/typeshed/stdlib/tkinter/__init__.pyi @@ -164,10 +164,11 @@ class EventType(str, Enum): VirtualEvent: str = ... Visibility: str = ... +_W = TypeVar("_W", bound="Misc") # Events considered covariant because you should never assign to event.widget. -_W = TypeVar("_W", covariant=True, bound="Misc") +_W_co = TypeVar("_W_co", covariant=True, bound="Misc") -class Event(Generic[_W]): +class Event(Generic[_W_co]): serial: int num: int focus: bool @@ -185,7 +186,7 @@ class Event(Generic[_W]): keysym: str keysym_num: int type: EventType - widget: _W + widget: _W_co delta: int def NoDefaultRoot(): ... @@ -995,7 +996,7 @@ class Button(Widget): def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... config = configure def flash(self): ... - def invoke(self): ... + def invoke(self) -> Any: ... class Canvas(Widget, XView, YView): def __init__( @@ -1417,10 +1418,12 @@ class Checkbutton(Widget): config = configure def deselect(self): ... def flash(self): ... - def invoke(self): ... + def invoke(self) -> Any: ... def select(self): ... def toggle(self): ... +_EntryIndex = Union[str, int] # "INDICES" in manual page + class Entry(Widget, XView): def __init__( self, @@ -1512,25 +1515,25 @@ class Entry(Widget, XView): @overload def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... config = configure - def delete(self, first, last: Optional[Any] = ...): ... - def get(self): ... - def icursor(self, index): ... - def index(self, index): ... - def insert(self, index, string): ... + def delete(self, first: _EntryIndex, last: _EntryIndex | None = ...) -> None: ... + def get(self) -> str: ... + def icursor(self, index: _EntryIndex) -> None: ... + def index(self, index: _EntryIndex) -> int: ... + def insert(self, index: _EntryIndex, string: str) -> None: ... def scan_mark(self, x): ... def scan_dragto(self, x): ... - def selection_adjust(self, index): ... - select_adjust: Any - def selection_clear(self): ... - select_clear: Any - def selection_from(self, index): ... - select_from: Any - def selection_present(self): ... - select_present: Any - def selection_range(self, start, end): ... - select_range: Any - def selection_to(self, index): ... - select_to: Any + def selection_adjust(self, index: _EntryIndex) -> None: ... + def selection_clear(self) -> None: ... # type: ignore + def selection_from(self, index: _EntryIndex) -> None: ... + def selection_present(self) -> bool: ... + def selection_range(self, start: _EntryIndex, end: _EntryIndex) -> None: ... + def selection_to(self, index: _EntryIndex) -> None: ... + select_adjust = selection_adjust + select_clear = selection_clear + select_from = selection_from + select_present = selection_present + select_range = selection_range + select_to = selection_to class Frame(Widget): def __init__( @@ -1841,10 +1844,10 @@ class Menu(Widget): @overload def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... config = configure - def tk_popup(self, x: int, y: int, entry: _MenuIndex = ...): ... - def activate(self, index): ... - def add(self, itemType, cnf=..., **kw): ... - def insert(self, index, itemType, cnf=..., **kw): ... + def tk_popup(self, x: int, y: int, entry: _MenuIndex = ...) -> None: ... + def activate(self, index: _MenuIndex) -> None: ... + def add(self, itemType, cnf=..., **kw): ... # docstring says "Internal function." + def insert(self, index, itemType, cnf=..., **kw): ... # docstring says "Internal function." def add_cascade( self, cnf: Optional[Dict[str, Any]] = ..., @@ -2035,17 +2038,19 @@ class Menu(Widget): variable: Variable = ..., ) -> None: ... def insert_separator(self, index: _MenuIndex, cnf: Optional[Dict[str, Any]] = ..., *, background: _Color = ...) -> None: ... - def delete(self, index1, index2: Optional[Any] = ...): ... - def entrycget(self, index, option): ... - def entryconfigure(self, index, cnf: Optional[Any] = ..., **kw): ... - entryconfig: Any - def index(self, index): ... - def invoke(self, index): ... - def post(self, x, y): ... - def type(self, index): ... - def unpost(self): ... - def xposition(self, index): ... - def yposition(self, index): ... + def delete(self, index1: _MenuIndex, index2: _MenuIndex | None = ...) -> None: ... + def entrycget(self, index: _MenuIndex, option: str) -> Any: ... + def entryconfigure( + self, index: _MenuIndex, cnf: dict[str, Any] | None = ..., **kw: Any + ) -> dict[str, Tuple[str, str, str, Any, Any]] | None: ... + entryconfig = entryconfigure + def index(self, index: _MenuIndex) -> int | None: ... + def invoke(self, index: _MenuIndex) -> Any: ... + def post(self, x: int, y: int) -> None: ... + def type(self, index: _MenuIndex) -> Literal["cascade", "checkbutton", "command", "radiobutton", "separator"]: ... + def unpost(self) -> None: ... + def xposition(self, index: _MenuIndex) -> int: ... + def yposition(self, index: _MenuIndex) -> int: ... class Menubutton(Widget): def __init__( @@ -2297,7 +2302,7 @@ class Radiobutton(Widget): config = configure def deselect(self): ... def flash(self): ... - def invoke(self): ... + def invoke(self) -> Any: ... def select(self): ... class Scale(Widget): @@ -2969,7 +2974,8 @@ class Spinbox(Widget, XView): def identify(self, x, y): ... def index(self, index): ... def insert(self, index, s): ... - def invoke(self, element): ... + # spinbox.invoke("asdf") gives error mentioning .invoke("none"), but it's not documented + def invoke(self, element: Literal["none", "buttonup", "buttondown"]) -> Literal[""]: ... def scan(self, *args): ... def scan_mark(self, x): ... def scan_dragto(self, x): ... diff --git a/mypy/typeshed/stdlib/tkinter/dnd.pyi b/mypy/typeshed/stdlib/tkinter/dnd.pyi index 7371f91b524e..71d8d3e5c4f4 100644 --- a/mypy/typeshed/stdlib/tkinter/dnd.pyi +++ b/mypy/typeshed/stdlib/tkinter/dnd.pyi @@ -1,10 +1,12 @@ -from _typeshed.tkinter import DndSource -from tkinter import Event, Misc, Tk -from typing import ClassVar, Optional +from tkinter import Event, Misc, Tk, Widget +from typing import ClassVar, Optional, Protocol + +class _DndSource(Protocol): + def dnd_end(self, target: Optional[Widget], event: Optional[Event[Misc]]) -> None: ... class DndHandler: root: ClassVar[Optional[Tk]] - def __init__(self, source: DndSource, event: Event[Misc]) -> None: ... + def __init__(self, source: _DndSource, event: Event[Misc]) -> None: ... def cancel(self, event: Optional[Event[Misc]] = ...) -> None: ... def finish(self, event: Optional[Event[Misc]], commit: int = ...) -> None: ... def on_motion(self, event: Event[Misc]) -> None: ... diff --git a/mypy/typeshed/stdlib/tkinter/filedialog.pyi b/mypy/typeshed/stdlib/tkinter/filedialog.pyi index 86238f0be798..885a1373ea93 100644 --- a/mypy/typeshed/stdlib/tkinter/filedialog.pyi +++ b/mypy/typeshed/stdlib/tkinter/filedialog.pyi @@ -1,5 +1,7 @@ -from tkinter import Button, Entry, Frame, Listbox, Scrollbar, Toplevel, commondialog -from typing import Any, ClassVar, Dict, Optional, Tuple +from _typeshed import StrOrBytesPath +from tkinter import Button, Entry, Frame, Listbox, Misc, Scrollbar, StringVar, Toplevel, _TkinterSequence, commondialog +from typing import IO, Any, ClassVar, Dict, Iterable, Optional, Tuple +from typing_extensions import Literal dialogstates: Dict[Any, Tuple[Any, Any]] @@ -57,11 +59,75 @@ class SaveAs(_Dialog): class Directory(commondialog.Dialog): command: ClassVar[str] = ... -def askopenfilename(**options): ... -def asksaveasfilename(**options): ... -def askopenfilenames(**options): ... -def askopenfile(mode: str = ..., **options): ... -def askopenfiles(mode: str = ..., **options): ... -def asksaveasfile(mode: str = ..., **options): ... -def askdirectory(**options): ... +# TODO: command kwarg available on macos +def asksaveasfilename( + *, + confirmoverwrite: bool | None = ..., + defaultextension: str | None = ..., + filetypes: Iterable[Tuple[str, str] | Tuple[str, _TkinterSequence[str]]] | None = ..., + initialdir: StrOrBytesPath | None = ..., + initialfile: StrOrBytesPath | None = ..., + parent: Misc | None = ..., + title: str | None = ..., + typevariable: StringVar | str | None = ..., +) -> str: ... # can be empty string +def askopenfilename( + *, + defaultextension: str | None = ..., + filetypes: Iterable[Tuple[str, str] | Tuple[str, _TkinterSequence[str]]] | None = ..., + initialdir: StrOrBytesPath | None = ..., + initialfile: StrOrBytesPath | None = ..., + parent: Misc | None = ..., + title: str | None = ..., + typevariable: StringVar | str | None = ..., +) -> str: ... # can be empty string +def askopenfilenames( + *, + defaultextension: str | None = ..., + filetypes: Iterable[Tuple[str, str] | Tuple[str, _TkinterSequence[str]]] | None = ..., + initialdir: StrOrBytesPath | None = ..., + initialfile: StrOrBytesPath | None = ..., + parent: Misc | None = ..., + title: str | None = ..., + typevariable: StringVar | str | None = ..., +) -> Literal[""] | Tuple[str, ...]: ... +def askdirectory( + *, initialdir: StrOrBytesPath | None = ..., mustexist: bool | None = ..., parent: Misc | None = ..., title: str | None = ... +) -> str: ... # can be empty string + +# TODO: If someone actually uses these, overload to have the actual return type of open(..., mode) +def asksaveasfile( + mode: str = ..., + *, + confirmoverwrite: bool | None = ..., + defaultextension: str | None = ..., + filetypes: Iterable[Tuple[str, str] | Tuple[str, _TkinterSequence[str]]] | None = ..., + initialdir: StrOrBytesPath | None = ..., + initialfile: StrOrBytesPath | None = ..., + parent: Misc | None = ..., + title: str | None = ..., + typevariable: StringVar | str | None = ..., +) -> IO[Any] | None: ... +def askopenfile( + mode: str = ..., + *, + defaultextension: str | None = ..., + filetypes: Iterable[Tuple[str, str] | Tuple[str, _TkinterSequence[str]]] | None = ..., + initialdir: StrOrBytesPath | None = ..., + initialfile: StrOrBytesPath | None = ..., + parent: Misc | None = ..., + title: str | None = ..., + typevariable: StringVar | str | None = ..., +) -> IO[Any] | None: ... +def askopenfiles( + mode: str = ..., + *, + defaultextension: str | None = ..., + filetypes: Iterable[Tuple[str, str] | Tuple[str, _TkinterSequence[str]]] | None = ..., + initialdir: StrOrBytesPath | None = ..., + initialfile: StrOrBytesPath | None = ..., + parent: Misc | None = ..., + title: str | None = ..., + typevariable: StringVar | str | None = ..., +) -> Tuple[IO[Any], ...]: ... # can be empty tuple def test() -> None: ... diff --git a/mypy/typeshed/stdlib/tkinter/font.pyi b/mypy/typeshed/stdlib/tkinter/font.pyi index a19c2dd6dc67..e1733d5c2a88 100644 --- a/mypy/typeshed/stdlib/tkinter/font.pyi +++ b/mypy/typeshed/stdlib/tkinter/font.pyi @@ -1,6 +1,6 @@ import sys import tkinter -from typing import Any, List, Optional, Tuple, TypeVar, Union, overload +from typing import Any, Optional, Tuple, Union, overload from typing_extensions import Literal, TypedDict NORMAL: Literal["normal"] diff --git a/mypy/typeshed/stdlib/tkinter/scrolledtext.pyi b/mypy/typeshed/stdlib/tkinter/scrolledtext.pyi index 12c614072ba2..b82863d88947 100644 --- a/mypy/typeshed/stdlib/tkinter/scrolledtext.pyi +++ b/mypy/typeshed/stdlib/tkinter/scrolledtext.pyi @@ -1,4 +1,4 @@ -from tkinter import Frame, Grid, Misc, Pack, Place, Scrollbar, Text +from tkinter import Frame, Misc, Scrollbar, Text from typing import Any, Optional # The methods from Pack, Place, and Grid are dynamically added over the parent's impls diff --git a/mypy/typeshed/stdlib/tkinter/ttk.pyi b/mypy/typeshed/stdlib/tkinter/ttk.pyi index af3c75142598..755b2f96ff7d 100644 --- a/mypy/typeshed/stdlib/tkinter/ttk.pyi +++ b/mypy/typeshed/stdlib/tkinter/ttk.pyi @@ -2,8 +2,8 @@ import _tkinter import sys import tkinter from tkinter.font import _FontDescription -from typing import Any, Callable, Dict, List, Optional, Tuple, Union, overload -from typing_extensions import Literal +from typing import Any, Callable, Dict, Optional, Tuple, Union, overload +from typing_extensions import Literal, TypedDict def tclobjs_to_py(adict): ... def setup_master(master: Optional[Any] = ...): ... @@ -76,7 +76,7 @@ class Button(Widget): @overload def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... config = configure - def invoke(self): ... + def invoke(self) -> Any: ... class Checkbutton(Widget): def __init__( @@ -128,7 +128,7 @@ class Checkbutton(Widget): @overload def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... config = configure - def invoke(self): ... + def invoke(self) -> Any: ... class Entry(Widget, tkinter.Entry): def __init__( @@ -652,7 +652,7 @@ class Radiobutton(Widget): @overload def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... config = configure - def invoke(self): ... + def invoke(self) -> Any: ... class Scale(Widget, tkinter.Scale): def __init__( @@ -871,6 +871,36 @@ if sys.version_info >= (3, 7): config = configure # type: ignore def set(self, value: Any) -> None: ... +class _TreeviewItemDict(TypedDict): + text: str + image: Literal[""] | list[str] # no idea why it's wrapped in list + values: list[Any] + open: bool # actually 0 or 1 + tags: list[str] + +class _TreeviewTagDict(TypedDict): + text: str + image: Literal[""] | str # not wrapped in list :D + anchor: tkinter._Anchor + background: tkinter._Color + foreground: tkinter._Color + +class _TreeviewHeaderDict(TypedDict): + text: str + image: list[str] + anchor: tkinter._Anchor + command: str + state: str # Doesn't seem to appear anywhere else than in these dicts + +class _TreeviewColumnDict(TypedDict): + width: int + minwidth: int + stretch: bool # actually 0 or 1 + anchor: tkinter._Anchor + id: str + +_TreeviewColumnId = Union[int, str] # manual page: "COLUMN IDENTIFIERS" + class Treeview(Widget, tkinter.XView, tkinter.YView): def __init__( self, @@ -914,38 +944,122 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): @overload def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... config = configure - def bbox(self, item, column: Optional[Any] = ...): ... # type: ignore - def get_children(self, item: Optional[Any] = ...): ... - def set_children(self, item, *newchildren): ... - def column(self, column, option: Optional[Any] = ..., **kw): ... - def delete(self, *items): ... - def detach(self, *items): ... - def exists(self, item): ... - def focus(self, item: Optional[Any] = ...): ... - def heading(self, column, option: Optional[Any] = ..., **kw): ... + def bbox(self, item, column: _TreeviewColumnId | None = ...) -> Tuple[int, int, int, int] | Literal[""]: ... # type: ignore + def get_children(self, item: str | None = ...) -> Tuple[str, ...]: ... + def set_children(self, item: str, *newchildren: str) -> None: ... + @overload + def column(self, column: _TreeviewColumnId, option: Literal["width", "minwidth"]) -> int: ... + @overload + def column(self, column: _TreeviewColumnId, option: Literal["stretch"]) -> bool: ... # actually 0 or 1 + @overload + def column(self, column: _TreeviewColumnId, option: Literal["anchor"]) -> _tkinter.Tcl_Obj: ... + @overload + def column(self, column: _TreeviewColumnId, option: Literal["id"]) -> str: ... + @overload + def column(self, column: _TreeviewColumnId, option: str) -> Any: ... + @overload + def column( + self, + column: _TreeviewColumnId, + option: None = ..., + *, + width: int = ..., + minwidth: int = ..., + stretch: bool = ..., + anchor: tkinter._Anchor = ..., + # id is read-only + ) -> _TreeviewColumnDict | None: ... + def delete(self, *items: str) -> None: ... + def detach(self, *items: str) -> None: ... + def exists(self, item: str) -> bool: ... + @overload # type: ignore + def focus(self, item: None = ...) -> str: ... # can return empty string + @overload + def focus(self, item: str) -> Literal[""]: ... + @overload + def heading(self, column: _TreeviewColumnId, option: Literal["text"]) -> str: ... + @overload + def heading(self, column: _TreeviewColumnId, option: Literal["image"]) -> Tuple[str]: ... + @overload + def heading(self, column: _TreeviewColumnId, option: Literal["anchor"]) -> _tkinter.Tcl_Obj: ... + @overload + def heading(self, column: _TreeviewColumnId, option: Literal["command"]) -> str: ... + @overload + def heading(self, column: _TreeviewColumnId, option: str) -> Any: ... + @overload + def heading( + self, + column: _TreeviewColumnId, + option: None = ..., + *, + text: str = ..., + image: tkinter._ImageSpec = ..., + anochor: tkinter._Anchor = ..., + command: str | Callable[[], Any] = ..., + ) -> _TreeviewHeaderDict | None: ... def identify(self, component, x, y): ... - def identify_row(self, y): ... - def identify_column(self, x): ... - def identify_region(self, x, y): ... - def identify_element(self, x, y): ... - def index(self, item): ... - def insert(self, parent, index, iid: Optional[Any] = ..., **kw): ... - def item(self, item, option: Optional[Any] = ..., **kw): ... - def move(self, item, parent, index): ... - reattach: Any - def next(self, item): ... - def parent(self, item): ... - def prev(self, item): ... - def see(self, item): ... + def identify_row(self, y: int) -> str: ... + def identify_column(self, x: int) -> str: ... + def identify_region(self, x: int, y: int) -> Literal["heading", "separator", "tree", "cell", "nothing"]: ... + def identify_element(self, x: int, y: int) -> str: ... # don't know what possible return values are + def index(self, item: str) -> int: ... + def insert( + self, + parent: str, + index: int | Literal["end"], + iid: str | None = ..., + *, + id: str = ..., # same as iid + text: str = ..., + image: tkinter._ImageSpec = ..., + values: tkinter._TkinterSequence[Any] = ..., + open: bool = ..., + tags: str | tkinter._TkinterSequence[str] = ..., + ) -> str: ... + @overload + def item(self, item: str, option: Literal["text"]) -> str: ... + @overload + def item(self, item: str, option: Literal["image"]) -> Literal[""] | Tuple[str]: ... + @overload + def item(self, item: str, option: Literal["values"]) -> Literal[""] | Tuple[Any, ...]: ... + @overload + def item(self, item: str, option: Literal["open"]) -> bool: ... # actually 0 or 1 + @overload + def item(self, item: str, option: Literal["tags"]) -> Literal[""] | Tuple[str, ...]: ... + @overload + def item(self, item: str, option: str) -> Any: ... + @overload + def item( + self, + item: str, + option: None = ..., + *, + text: str = ..., + image: tkinter._ImageSpec = ..., + values: tkinter._TkinterSequence[Any] = ..., + open: bool = ..., + tags: str | tkinter._TkinterSequence[str] = ..., + ) -> _TreeviewItemDict | None: ... + def move(self, item: str, parent: str, index: int) -> None: ... + reattach = move + def next(self, item: str) -> str: ... # returning empty string means last item + def parent(self, item: str) -> str: ... + def prev(self, item: str) -> str: ... # returning empty string means first item + def see(self, item: str) -> None: ... if sys.version_info >= (3, 8): def selection(self) -> Tuple[str, ...]: ... else: def selection(self, selop: Optional[Any] = ..., items: Optional[Any] = ...) -> Tuple[str, ...]: ... - def selection_set(self, items): ... - def selection_add(self, items): ... - def selection_remove(self, items): ... - def selection_toggle(self, items): ... - def set(self, item, column: Optional[Any] = ..., value: Optional[Any] = ...): ... + def selection_set(self, items: str | tkinter._TkinterSequence[str]) -> None: ... + def selection_add(self, items: str | tkinter._TkinterSequence[str]) -> None: ... + def selection_remove(self, items: str | tkinter._TkinterSequence[str]) -> None: ... + def selection_toggle(self, items: str | tkinter._TkinterSequence[str]) -> None: ... + @overload + def set(self, item: str, column: None = ..., value: None = ...) -> dict[str, Any]: ... + @overload + def set(self, item: str, column: _TreeviewColumnId, value: None = ...) -> Any: ... + @overload + def set(self, item: str, column: _TreeviewColumnId, value: Any) -> Literal[""]: ... # There's no tag_unbind() or 'add' argument for whatever reason. # Also, it's 'callback' instead of 'func' here. @overload @@ -956,8 +1070,32 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): def tag_bind(self, tagname: str, sequence: Optional[str], callback: str) -> None: ... @overload def tag_bind(self, tagname: str, *, callback: str) -> None: ... - def tag_configure(self, tagname, option: Optional[Any] = ..., **kw): ... - def tag_has(self, tagname, item: Optional[Any] = ...): ... + @overload + def tag_configure(self, tagname: str, option: Literal["text"]) -> str: ... + @overload + def tag_configure(self, tagname: str, option: Literal["image"]) -> str: ... + @overload + def tag_configure(self, tagname: str, option: Literal["anchor"]) -> tkinter._Anchor | Literal[""]: ... + @overload + def tag_configure(self, tagname: str, option: Literal["foreground", "background"]) -> tkinter._Color: ... + @overload + def tag_configure(self, tagname: str, option: str) -> Any: ... + @overload + def tag_configure( + self, + tagname: str, + option: None = ..., + *, + text: str = ..., + image: tkinter._ImageSpec = ..., + anchor: tkinter._Anchor = ..., + background: tkinter._Color = ..., + foreground: tkinter._Color = ..., + ) -> _TreeviewTagDict | None: ... + @overload + def tag_has(self, tagname: str, item: None = ...) -> Tuple[str, ...]: ... + @overload + def tag_has(self, tagname: str, item: str) -> bool: ... class LabeledScale(Frame): label: Any diff --git a/mypy/typeshed/stdlib/types.pyi b/mypy/typeshed/stdlib/types.pyi index e280150e3406..fbd9e0645816 100644 --- a/mypy/typeshed/stdlib/types.pyi +++ b/mypy/typeshed/stdlib/types.pyi @@ -34,9 +34,9 @@ class _Cell: cell_contents: Any class FunctionType: - __closure__: Optional[Tuple[_Cell, ...]] + __closure__: Tuple[_Cell, ...] | None __code__: CodeType - __defaults__: Optional[Tuple[Any, ...]] + __defaults__: Tuple[Any, ...] | None __dict__: Dict[str, Any] __globals__: Dict[str, Any] __name__: str @@ -47,12 +47,12 @@ class FunctionType: self, code: CodeType, globals: Dict[str, Any], - name: Optional[str] = ..., - argdefs: Optional[Tuple[object, ...]] = ..., - closure: Optional[Tuple[_Cell, ...]] = ..., + name: str | None = ..., + argdefs: Tuple[object, ...] | None = ..., + closure: Tuple[_Cell, ...] | None = ..., ) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - def __get__(self, obj: Optional[object], type: Optional[type]) -> MethodType: ... + def __get__(self, obj: object | None, type: type | None) -> MethodType: ... LambdaType = FunctionType @@ -222,10 +222,12 @@ class _StaticFunctionType: def __get__(self, obj: Optional[object], type: Optional[type]) -> FunctionType: ... class MethodType: + __closure__: Optional[Tuple[_Cell, ...]] # inherited from the added function + __defaults__: Optional[Tuple[Any, ...]] # inherited from the added function __func__: _StaticFunctionType __self__: object - __name__: str - __qualname__: str + __name__: str # inherited from the added function + __qualname__: str # inherited from the added function def __init__(self, func: Callable[..., Any], obj: object) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... diff --git a/mypy/typeshed/stdlib/typing.pyi b/mypy/typeshed/stdlib/typing.pyi index 0995c9412726..359a7d4f9e92 100644 --- a/mypy/typeshed/stdlib/typing.pyi +++ b/mypy/typeshed/stdlib/typing.pyi @@ -603,7 +603,6 @@ class Pattern(Generic[AnyStr]): pattern: AnyStr def search(self, string: AnyStr, pos: int = ..., endpos: int = ...) -> Optional[Match[AnyStr]]: ... def match(self, string: AnyStr, pos: int = ..., endpos: int = ...) -> Optional[Match[AnyStr]]: ... - # New in Python 3.4 def fullmatch(self, string: AnyStr, pos: int = ..., endpos: int = ...) -> Optional[Match[AnyStr]]: ... def split(self, string: AnyStr, maxsplit: int = ...) -> list[AnyStr]: ... def findall(self, string: AnyStr, pos: int = ..., endpos: int = ...) -> list[Any]: ... diff --git a/mypy/typeshed/stdlib/unittest/case.pyi b/mypy/typeshed/stdlib/unittest/case.pyi index 16036264af11..79a7e79069af 100644 --- a/mypy/typeshed/stdlib/unittest/case.pyi +++ b/mypy/typeshed/stdlib/unittest/case.pyi @@ -2,6 +2,7 @@ import datetime import logging import sys import unittest.result +from _typeshed import Self from collections.abc import Set from types import TracebackType from typing import ( @@ -14,6 +15,7 @@ from typing import ( Iterable, List, Mapping, + NamedTuple, NoReturn, Optional, Pattern, @@ -251,9 +253,13 @@ class FunctionTestCase(TestCase): ) -> None: ... def runTest(self) -> None: ... +class _LoggingWatcher(NamedTuple): + records: List[logging.LogRecord] + output: List[str] + class _AssertRaisesContext(Generic[_E]): exception: _E - def __enter__(self) -> _AssertRaisesContext[_E]: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> bool: ... @@ -265,7 +271,7 @@ class _AssertWarnsContext: filename: str lineno: int warnings: List[WarningMessage] - def __enter__(self) -> _AssertWarnsContext: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> None: ... @@ -275,7 +281,10 @@ class _AssertLogsContext: records: List[logging.LogRecord] output: List[str] def __init__(self, test_case: TestCase, logger_name: str, level: int) -> None: ... - def __enter__(self) -> _AssertLogsContext: ... + if sys.version_info >= (3, 10): + def __enter__(self) -> _LoggingWatcher | None: ... + else: + def __enter__(self) -> _LoggingWatcher: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> Optional[bool]: ... diff --git a/mypy/typeshed/stdlib/urllib/request.pyi b/mypy/typeshed/stdlib/urllib/request.pyi index 60ccdf2dd90c..cbbb48270dea 100644 --- a/mypy/typeshed/stdlib/urllib/request.pyi +++ b/mypy/typeshed/stdlib/urllib/request.pyi @@ -119,19 +119,19 @@ class HTTPRedirectHandler(BaseHandler): max_repeats: ClassVar[int] # undocumented inf_msg: ClassVar[str] # undocumented def redirect_request( - self, req: Request, fp: IO[str], code: int, msg: str, headers: Mapping[str, str], newurl: str + self, req: Request, fp: IO[bytes], code: int, msg: str, headers: Mapping[str, str], newurl: str ) -> Optional[Request]: ... def http_error_301( - self, req: Request, fp: IO[str], code: int, msg: int, headers: Mapping[str, str] + self, req: Request, fp: IO[bytes], code: int, msg: str, headers: Mapping[str, str] ) -> Optional[_UrlopenRet]: ... def http_error_302( - self, req: Request, fp: IO[str], code: int, msg: int, headers: Mapping[str, str] + self, req: Request, fp: IO[bytes], code: int, msg: str, headers: Mapping[str, str] ) -> Optional[_UrlopenRet]: ... def http_error_303( - self, req: Request, fp: IO[str], code: int, msg: int, headers: Mapping[str, str] + self, req: Request, fp: IO[bytes], code: int, msg: str, headers: Mapping[str, str] ) -> Optional[_UrlopenRet]: ... def http_error_307( - self, req: Request, fp: IO[str], code: int, msg: int, headers: Mapping[str, str] + self, req: Request, fp: IO[bytes], code: int, msg: str, headers: Mapping[str, str] ) -> Optional[_UrlopenRet]: ... class HTTPCookieProcessor(BaseHandler): @@ -179,13 +179,13 @@ class AbstractBasicAuthHandler: class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler): auth_header: ClassVar[str] # undocumented def http_error_401( - self, req: Request, fp: IO[str], code: int, msg: int, headers: Mapping[str, str] + self, req: Request, fp: IO[bytes], code: int, msg: str, headers: Mapping[str, str] ) -> Optional[_UrlopenRet]: ... class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler): auth_header: ClassVar[str] def http_error_407( - self, req: Request, fp: IO[str], code: int, msg: int, headers: Mapping[str, str] + self, req: Request, fp: IO[bytes], code: int, msg: str, headers: Mapping[str, str] ) -> Optional[_UrlopenRet]: ... class AbstractDigestAuthHandler: @@ -201,13 +201,13 @@ class AbstractDigestAuthHandler: class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): auth_header: ClassVar[str] # undocumented def http_error_401( - self, req: Request, fp: IO[str], code: int, msg: int, headers: Mapping[str, str] + self, req: Request, fp: IO[bytes], code: int, msg: str, headers: Mapping[str, str] ) -> Optional[_UrlopenRet]: ... class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): auth_header: ClassVar[str] # undocumented def http_error_407( - self, req: Request, fp: IO[str], code: int, msg: int, headers: Mapping[str, str] + self, req: Request, fp: IO[bytes], code: int, msg: str, headers: Mapping[str, str] ) -> Optional[_UrlopenRet]: ... class AbstractHTTPHandler(BaseHandler): # undocumented @@ -310,21 +310,21 @@ class FancyURLopener(URLopener): def prompt_user_passwd(self, host: str, realm: str) -> Tuple[str, str]: ... def get_user_passwd(self, host: str, realm: str, clear_cache: int = ...) -> Tuple[str, str]: ... # undocumented def http_error_301( - self, url: str, fp: IO[str], errcode: int, errmsg: str, headers: Mapping[str, str], data: Optional[bytes] = ... + self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: Mapping[str, str], data: Optional[bytes] = ... ) -> Optional[Union[_UrlopenRet, addinfourl]]: ... # undocumented def http_error_302( - self, url: str, fp: IO[str], errcode: int, errmsg: str, headers: Mapping[str, str], data: Optional[bytes] = ... + self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: Mapping[str, str], data: Optional[bytes] = ... ) -> Optional[Union[_UrlopenRet, addinfourl]]: ... # undocumented def http_error_303( - self, url: str, fp: IO[str], errcode: int, errmsg: str, headers: Mapping[str, str], data: Optional[bytes] = ... + self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: Mapping[str, str], data: Optional[bytes] = ... ) -> Optional[Union[_UrlopenRet, addinfourl]]: ... # undocumented def http_error_307( - self, url: str, fp: IO[str], errcode: int, errmsg: str, headers: Mapping[str, str], data: Optional[bytes] = ... + self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: Mapping[str, str], data: Optional[bytes] = ... ) -> Optional[Union[_UrlopenRet, addinfourl]]: ... # undocumented def http_error_401( self, url: str, - fp: IO[str], + fp: IO[bytes], errcode: int, errmsg: str, headers: Mapping[str, str], @@ -334,7 +334,7 @@ class FancyURLopener(URLopener): def http_error_407( self, url: str, - fp: IO[str], + fp: IO[bytes], errcode: int, errmsg: str, headers: Mapping[str, str], @@ -345,7 +345,7 @@ class FancyURLopener(URLopener): self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: Mapping[str, str] ) -> addinfourl: ... # undocumented def redirect_internal( - self, url: str, fp: IO[str], errcode: int, errmsg: str, headers: Mapping[str, str], data: Optional[bytes] + self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: Mapping[str, str], data: Optional[bytes] ) -> Optional[_UrlopenRet]: ... # undocumented def retry_http_basic_auth( self, url: str, realm: str, data: Optional[bytes] = ... diff --git a/mypy/typeshed/stdlib/urllib/response.pyi b/mypy/typeshed/stdlib/urllib/response.pyi index c8f9d75d2f14..300105076048 100644 --- a/mypy/typeshed/stdlib/urllib/response.pyi +++ b/mypy/typeshed/stdlib/urllib/response.pyi @@ -1,3 +1,4 @@ +from _typeshed import Self from email.message import Message from types import TracebackType from typing import IO, Any, BinaryIO, Callable, Iterable, List, Optional, Tuple, Type, TypeVar @@ -7,7 +8,7 @@ _AIUT = TypeVar("_AIUT", bound=addbase) class addbase(BinaryIO): fp: IO[bytes] def __init__(self, fp: IO[bytes]) -> None: ... - def __enter__(self: _AIUT) -> _AIUT: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, type: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[TracebackType] ) -> None: ... diff --git a/mypy/typeshed/stdlib/wave.pyi b/mypy/typeshed/stdlib/wave.pyi index 61f9136ea334..cafdcd408398 100644 --- a/mypy/typeshed/stdlib/wave.pyi +++ b/mypy/typeshed/stdlib/wave.pyi @@ -1,4 +1,5 @@ import sys +from _typeshed import Self from typing import IO, Any, BinaryIO, NamedTuple, NoReturn, Optional, Union _File = Union[str, IO[bytes]] @@ -17,7 +18,7 @@ class _wave_params(NamedTuple): class Wave_read: def __init__(self, f: _File) -> None: ... - def __enter__(self) -> Wave_read: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, *args: Any) -> None: ... def getfp(self) -> Optional[BinaryIO]: ... def rewind(self) -> None: ... @@ -37,7 +38,7 @@ class Wave_read: class Wave_write: def __init__(self, f: _File) -> None: ... - def __enter__(self) -> Wave_write: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, *args: Any) -> None: ... def setnchannels(self, nchannels: int) -> None: ... def getnchannels(self) -> int: ... diff --git a/mypy/typeshed/stdlib/winreg.pyi b/mypy/typeshed/stdlib/winreg.pyi index 8f25dd61a092..ac9fcb24934b 100644 --- a/mypy/typeshed/stdlib/winreg.pyi +++ b/mypy/typeshed/stdlib/winreg.pyi @@ -1,3 +1,4 @@ +from _typeshed import Self from types import TracebackType from typing import Any, Optional, Tuple, Type, Union @@ -90,7 +91,7 @@ error = OSError class HKEYType: def __bool__(self) -> bool: ... def __int__(self) -> int: ... - def __enter__(self) -> HKEYType: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> Optional[bool]: ... diff --git a/mypy/typeshed/stdlib/xml/dom/minidom.pyi b/mypy/typeshed/stdlib/xml/dom/minidom.pyi index 90396299effc..a9ae79c01902 100644 --- a/mypy/typeshed/stdlib/xml/dom/minidom.pyi +++ b/mypy/typeshed/stdlib/xml/dom/minidom.pyi @@ -1,11 +1,10 @@ import sys import xml.dom -from typing import IO, Any, Optional, TypeVar, Union +from _typeshed import Self +from typing import IO, Any, Optional, Union from xml.dom.xmlbuilder import DocumentLS, DOMImplementationLS from xml.sax.xmlreader import XMLReader -_T = TypeVar("_T") - def parse(file: Union[str, IO[Any]], parser: Optional[XMLReader] = ..., bufsize: Optional[int] = ...): ... def parseString(string: Union[str, bytes], parser: Optional[XMLReader] = ...): ... def getDOMImplementation(features=...): ... @@ -39,7 +38,7 @@ class Node(xml.dom.Node): def setUserData(self, key, data, handler): ... childNodes: Any def unlink(self) -> None: ... - def __enter__(self: _T) -> _T: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, et, ev, tb) -> None: ... class DocumentFragment(Node): diff --git a/mypy/typeshed/stdlib/xmlrpc/client.pyi b/mypy/typeshed/stdlib/xmlrpc/client.pyi index b0c615063729..8844b875950e 100644 --- a/mypy/typeshed/stdlib/xmlrpc/client.pyi +++ b/mypy/typeshed/stdlib/xmlrpc/client.pyi @@ -2,7 +2,7 @@ import gzip import http.client import sys import time -from _typeshed import SupportsRead, SupportsWrite +from _typeshed import Self, SupportsRead, SupportsWrite from datetime import datetime from io import BytesIO from types import TracebackType @@ -301,7 +301,7 @@ class ServerProxy: def __call__(self, attr: Literal["transport"]) -> Transport: ... @overload def __call__(self, attr: str) -> Union[Callable[[], None], Transport]: ... - def __enter__(self) -> ServerProxy: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> None: ... diff --git a/mypy/typeshed/stdlib/zipfile.pyi b/mypy/typeshed/stdlib/zipfile.pyi index b43ff218c062..3a1f7a125f16 100644 --- a/mypy/typeshed/stdlib/zipfile.pyi +++ b/mypy/typeshed/stdlib/zipfile.pyi @@ -1,11 +1,12 @@ import io import sys -from _typeshed import StrPath +from _typeshed import Self, StrPath from types import TracebackType from typing import IO, Callable, Dict, Iterable, Iterator, List, Optional, Protocol, Sequence, Tuple, Type, Union, overload from typing_extensions import Literal _DateTuple = Tuple[int, int, int, int, int, int] +_ZipFileMode = Literal["r", "w", "x", "a"] class BadZipFile(Exception): ... @@ -104,11 +105,15 @@ class ZipFile: fp: Optional[IO[bytes]] NameToInfo: Dict[str, ZipInfo] start_dir: int # undocumented + compression: int # undocumented + compresslevel: int | None # undocumented + mode: _ZipFileMode # undocumented + pwd: str | None # undocumented if sys.version_info >= (3, 8): def __init__( self, file: Union[StrPath, IO[bytes]], - mode: str = ..., + mode: _ZipFileMode = ..., compression: int = ..., allowZip64: bool = ..., compresslevel: Optional[int] = ..., @@ -119,7 +124,7 @@ class ZipFile: def __init__( self, file: Union[StrPath, IO[bytes]], - mode: str = ..., + mode: _ZipFileMode = ..., compression: int = ..., allowZip64: bool = ..., compresslevel: Optional[int] = ..., @@ -128,7 +133,7 @@ class ZipFile: def __init__( self, file: Union[StrPath, IO[bytes]], mode: str = ..., compression: int = ..., allowZip64: bool = ... ) -> None: ... - def __enter__(self) -> ZipFile: ... + def __enter__(self: Self) -> Self: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> None: ... @@ -137,7 +142,7 @@ class ZipFile: def infolist(self) -> List[ZipInfo]: ... def namelist(self) -> List[str]: ... def open( - self, name: Union[str, ZipInfo], mode: str = ..., pwd: Optional[bytes] = ..., *, force_zip64: bool = ... + self, name: Union[str, ZipInfo], mode: Literal["r", "w"] = ..., pwd: Optional[bytes] = ..., *, force_zip64: bool = ... ) -> IO[bytes]: ... def extract(self, member: Union[str, ZipInfo], path: Optional[StrPath] = ..., pwd: Optional[bytes] = ...) -> str: ... def extractall( @@ -194,7 +199,8 @@ class ZipInfo: CRC: int compress_size: int file_size: int - def __init__(self, filename: Optional[str] = ..., date_time: Optional[_DateTuple] = ...) -> None: ... + orig_filename: str # undocumented + def __init__(self, filename: str = ..., date_time: _DateTuple = ...) -> None: ... if sys.version_info >= (3, 8): @classmethod def from_file(cls, filename: StrPath, arcname: Optional[StrPath] = ..., *, strict_timestamps: bool = ...) -> ZipInfo: ... diff --git a/mypy/typeshed/stubs/mypy-extensions/@tests/stubtest_allowlist.txt b/mypy/typeshed/stubs/mypy-extensions/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..bffaebc697dc --- /dev/null +++ b/mypy/typeshed/stubs/mypy-extensions/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +mypy_extensions.FlexibleAlias +mypy_extensions.TypedDict diff --git a/test-data/unit/fixtures/bool.pyi b/test-data/unit/fixtures/bool.pyi index cef2e9129fb7..ca2564dabafd 100644 --- a/test-data/unit/fixtures/bool.pyi +++ b/test-data/unit/fixtures/bool.pyi @@ -16,3 +16,4 @@ class float: pass class str: pass class unicode: pass class ellipsis: pass +class list: pass diff --git a/test-data/unit/fixtures/callable.pyi b/test-data/unit/fixtures/callable.pyi index 80fcf6ba10bf..7d4757df4bf5 100644 --- a/test-data/unit/fixtures/callable.pyi +++ b/test-data/unit/fixtures/callable.pyi @@ -25,3 +25,4 @@ class str: def __add__(self, other: 'str') -> 'str': pass def __eq__(self, other: 'str') -> bool: pass class ellipsis: pass +class list: ...