[ty] Sync vendored typeshed stubs (#22321)

Co-authored-by: typeshedbot <>
Co-authored-by: Alex Waygood <alex.waygood@gmail.com>
This commit is contained in:
github-actions[bot]
2026-01-01 01:29:12 +00:00
committed by GitHub
parent 7366a9e951
commit 8e45bac3c1
45 changed files with 524 additions and 246 deletions

View File

@@ -796,13 +796,13 @@ mod tests {
| -------
5 | """some docs"""
|
::: stdlib/types.pyi:950:11
::: stdlib/types.pyi:974:11
|
948 | if sys.version_info >= (3, 10):
949 | @final
950 | class NoneType:
972 | if sys.version_info >= (3, 10):
973 | @final
974 | class NoneType:
| --------
951 | """The type of the None singleton."""
975 | """The type of the None singleton."""
|
"#);
}
@@ -850,13 +850,13 @@ mod tests {
| -------
5 | """some docs"""
|
::: stdlib/types.pyi:950:11
::: stdlib/types.pyi:974:11
|
948 | if sys.version_info >= (3, 10):
949 | @final
950 | class NoneType:
972 | if sys.version_info >= (3, 10):
973 | @final
974 | class NoneType:
| --------
951 | """The type of the None singleton."""
975 | """The type of the None singleton."""
|
"#);
}
@@ -1609,13 +1609,13 @@ def function():
916 | """str(object='') -> str
917 | str(bytes_or_buffer[, encoding[, errors]]) -> str
|
::: stdlib/types.pyi:950:11
::: stdlib/types.pyi:974:11
|
948 | if sys.version_info >= (3, 10):
949 | @final
950 | class NoneType:
972 | if sys.version_info >= (3, 10):
973 | @final
974 | class NoneType:
| --------
951 | """The type of the None singleton."""
975 | """The type of the None singleton."""
|
"#);
}

View File

@@ -2442,13 +2442,13 @@ mod tests {
|
info[inlay-hint-location]: Inlay Hint Target
--> stdlib/types.pyi:950:11
--> stdlib/types.pyi:974:11
|
948 | if sys.version_info >= (3, 10):
949 | @final
950 | class NoneType:
972 | if sys.version_info >= (3, 10):
973 | @final
974 | class NoneType:
| ^^^^^^^^
951 | """The type of the None singleton."""
975 | """The type of the None singleton."""
|
info: Source
--> main2.py:5:20
@@ -5615,13 +5615,13 @@ mod tests {
|
info[inlay-hint-location]: Inlay Hint Target
--> stdlib/types.pyi:950:11
--> stdlib/types.pyi:974:11
|
948 | if sys.version_info >= (3, 10):
949 | @final
950 | class NoneType:
972 | if sys.version_info >= (3, 10):
973 | @final
974 | class NoneType:
| ^^^^^^^^
951 | """The type of the None singleton."""
975 | """The type of the None singleton."""
|
info: Source
--> main2.py:13:37
@@ -6294,12 +6294,12 @@ mod tests {
a[: <module 'foo'>] = foo
---------------------------------------------
info[inlay-hint-location]: Inlay Hint Target
--> stdlib/types.pyi:423:7
--> stdlib/types.pyi:431:7
|
422 | @disjoint_base
423 | class ModuleType:
430 | @disjoint_base
431 | class ModuleType:
| ^^^^^^^^^^
424 | """Create a module object.
432 | """Create a module object.
|
info: Source
--> main2.py:4:6
@@ -6430,13 +6430,13 @@ mod tests {
a[: <wrapper-descriptor '__get__' of 'function' objects>] = FunctionType.__get__
---------------------------------------------
info[inlay-hint-location]: Inlay Hint Target
--> stdlib/types.pyi:670:7
--> stdlib/types.pyi:690:7
|
669 | @final
670 | class WrapperDescriptorType:
689 | @final
690 | class WrapperDescriptorType:
| ^^^^^^^^^^^^^^^^^^^^^
671 | @property
672 | def __name__(self) -> str: ...
691 | @property
692 | def __name__(self) -> str: ...
|
info: Source
--> main2.py:4:6
@@ -6482,13 +6482,13 @@ mod tests {
a[: <method-wrapper '__call__' of function 'f'>] = f.__call__
---------------------------------------------
info[inlay-hint-location]: Inlay Hint Target
--> stdlib/types.pyi:684:7
--> stdlib/types.pyi:704:7
|
683 | @final
684 | class MethodWrapperType:
703 | @final
704 | class MethodWrapperType:
| ^^^^^^^^^^^^^^^^^
685 | @property
686 | def __self__(self) -> object: ...
705 | @property
706 | def __self__(self) -> object: ...
|
info: Source
--> main2.py:4:6
@@ -6500,13 +6500,13 @@ mod tests {
|
info[inlay-hint-location]: Inlay Hint Target
--> stdlib/types.pyi:134:9
--> stdlib/types.pyi:139:9
|
132 | ) -> Self: ...
133 |
134 | def __call__(self, *args: Any, **kwargs: Any) -> Any:
137 | ) -> Self: ...
138 |
139 | def __call__(self, *args: Any, **kwargs: Any) -> Any:
| ^^^^^^^^
135 | """Call self as a function."""
140 | """Call self as a function."""
|
info: Source
--> main2.py:4:22

View File

@@ -91,14 +91,14 @@ error[missing-argument]: No argument provided for required parameter `arg` of bo
7 | from typing_extensions import deprecated
|
info: Parameter declared here
--> stdlib/typing_extensions.pyi:1341:28
--> stdlib/typing_extensions.pyi:1301:28
|
1339 | stacklevel: int
1340 | def __init__(self, message: LiteralString, /, *, category: type[Warning] | None = ..., stacklevel: int = 1) -> None: ...
1341 | def __call__(self, arg: _T, /) -> _T: ...
1299 | stacklevel: int
1300 | def __init__(self, message: LiteralString, /, *, category: type[Warning] | None = ..., stacklevel: int = 1) -> None: ...
1301 | def __call__(self, arg: _T, /) -> _T: ...
| ^^^^^^^
1342 |
1343 | @final
1302 |
1303 | @final
|
info: rule `missing-argument` is enabled by default

View File

@@ -1 +1 @@
3714af2b840f476bd992f3cad8dd4886edda7712
91756673d95f0bd5ba51f6ec2bcb2cbb8e798c27

View File

@@ -127,6 +127,8 @@ class _SimpleCData(_CData, Generic[_T], metaclass=_PyCSimpleType):
"""XXX to be provided"""
value: _T
"""current value"""
# The TypeVar can be unsolved here,
# but we can't use overloads without creating many, many mypy false-positive errors
def __init__(self, value: _T = ...) -> None: ... # pyright: ignore[reportInvalidTypeVarUse]
@@ -157,6 +159,8 @@ class _Pointer(_PointerLike, _CData, Generic[_CT], metaclass=_PyCPointerType):
_type_: type[_CT]
contents: _CT
"""the object this pointer points to (read-write)"""
@overload
def __init__(self) -> None: ...
@overload
@@ -228,8 +232,14 @@ class CFuncPtr(_PointerLike, _CData, metaclass=_PyCFuncPtrType):
"""Function Pointer"""
restype: type[_CDataType] | Callable[[int], Any] | None
"""specify the result type"""
argtypes: Sequence[type[_CDataType]]
"""specify the argument types"""
errcheck: _ECT
"""a function to check for errors"""
# Abstract attribute that must be defined on subclasses
_flags_: ClassVar[int]
@overload
@@ -258,15 +268,35 @@ if sys.version_info >= (3, 14):
"""Structure/Union member"""
offset: int
"""offset in bytes of this field (same as byte_offset)"""
size: int
"""size in bytes of this field. For bitfields, this is a legacy packed value; use byte_size instead"""
name: str
"""name of this field"""
type: builtins.type[_CT]
"""type of this field"""
byte_offset: int
"""offset in bytes of this field. For bitfields: excludes bit_offset."""
byte_size: int
"""size of this field in bytes"""
is_bitfield: bool
"""true if this is a bitfield"""
bit_offset: int
"""additional offset in bits (relative to byte_offset); zero for non-bitfields"""
bit_size: int
"""size of this field in bits"""
is_anonymous: bool
"""true if this field is anonymous"""
@overload
def __get__(self, instance: None, owner: builtins.type[Any] | None = None, /) -> Self:
"""Return an attribute of instance, which is of type owner."""

View File

@@ -870,6 +870,8 @@ class error(Exception): ...
@final
class window: # undocumented
encoding: str
"""the typecode character used to create the array"""
@overload
def addch(self, ch: _ChType, attr: int = ...) -> None:
"""addch([y, x,] ch, [attr=_curses.A_NORMAL])

View File

@@ -442,6 +442,8 @@ class FileIO(RawIOBase, _RawIOBase, BinaryIO): # type: ignore[misc] # incompat
"""
mode: str
"""String giving the file mode"""
# The type of "name" equals the argument passed in to the constructor,
# but that can make FileIO incompatible with other I/O types that assume
# "name" is a str. In the future, making FileIO generic might help.
@@ -629,8 +631,25 @@ class _TextIOBase(_IOBase):
"""
encoding: str
"""Encoding of the text stream.
Subclasses should override.
"""
errors: str | None
"""The error setting of the decoder or encoder.
Subclasses should override.
"""
newlines: str | tuple[str, ...] | None
"""Line endings translated so far.
Only line endings translated during reading are considered.
Subclasses should override.
"""
def __iter__(self) -> Iterator[str]: # type: ignore[override]
"""Implement iter(self)."""

View File

@@ -60,11 +60,21 @@ class make_scanner:
"""JSON scanner object"""
object_hook: Any
"""object_hook"""
object_pairs_hook: Any
parse_int: Any
"""parse_int"""
parse_constant: Any
"""parse_constant"""
parse_float: Any
"""parse_float"""
strict: bool
"""strict"""
# TODO: 'context' needs the attrs above (ducktype), but not __call__.
def __new__(cls, context: make_scanner) -> Self: ...
def __call__(self, string: str, index: int) -> tuple[Any, int]:

View File

@@ -68,18 +68,38 @@ class profiler_entry(structseq[Any], tuple[CodeType | str, int, int, float, floa
if sys.version_info >= (3, 10):
__match_args__: Final = ("code", "callcount", "reccallcount", "totaltime", "inlinetime", "calls")
code: CodeType | str
"""code object or built-in function name"""
callcount: int
"""how many times this was called"""
reccallcount: int
"""how many times called recursively"""
totaltime: float
"""total time in this entry"""
inlinetime: float
"""inline time in this entry (not in subcalls)"""
calls: list[profiler_subentry]
"""details of the calls"""
@final
class profiler_subentry(structseq[Any], tuple[CodeType | str, int, int, float, float]):
if sys.version_info >= (3, 10):
__match_args__: Final = ("code", "callcount", "reccallcount", "totaltime", "inlinetime")
code: CodeType | str
"""called code object or built-in function name"""
callcount: int
"""how many times this is called"""
reccallcount: int
"""how many times this is called recursively"""
totaltime: float
"""total time spent in this call"""
inlinetime: float
"""inline time (not in further subcalls)"""

View File

@@ -14,6 +14,8 @@ class _MultibyteCodec:
@disjoint_base
class MultibyteIncrementalDecoder:
errors: str
"""how to treat errors"""
def __init__(self, errors: str = "strict") -> None: ...
def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...
def getstate(self) -> tuple[bytes, int]: ...
@@ -23,6 +25,8 @@ class MultibyteIncrementalDecoder:
@disjoint_base
class MultibyteIncrementalEncoder:
errors: str
"""how to treat errors"""
def __init__(self, errors: str = "strict") -> None: ...
def encode(self, input: str, final: bool = False) -> bytes: ...
def getstate(self) -> int: ...
@@ -32,6 +36,8 @@ class MultibyteIncrementalEncoder:
@disjoint_base
class MultibyteStreamReader:
errors: str
"""how to treat errors"""
stream: _ReadableStream
def __init__(self, stream: _ReadableStream, errors: str = "strict") -> None: ...
def read(self, sizeobj: int | None = None, /) -> str: ...
@@ -42,6 +48,8 @@ class MultibyteStreamReader:
@disjoint_base
class MultibyteStreamWriter:
errors: str
"""how to treat errors"""
stream: _WritableStream
def __init__(self, stream: _WritableStream, errors: str = "strict") -> None: ...
def reset(self) -> None: ...

View File

@@ -124,12 +124,24 @@ class _SSLContext:
maximum_version: int
minimum_version: int
num_tickets: int
"""Control the number of TLSv1.3 session tickets."""
options: int
post_handshake_auth: bool
protocol: int
if sys.version_info >= (3, 10):
security_level: int
"""The current security level."""
sni_callback: Callable[[SSLObject, str, SSLContext], None | int] | None
"""Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
If the argument is None then the callback is disabled. The method is called
with the SSLSocket, the server name as a string, and the SSLContext object.
See RFC 6066 for details of the SNI extension.
"""
verify_flags: int
verify_mode: int
def __new__(cls, protocol: int, /) -> Self: ...
@@ -182,7 +194,11 @@ class _SSLContext:
@final
class MemoryBIO:
eof: bool
"""Whether the memory BIO is at EOF."""
pending: int
"""The number of bytes pending in the memory BIO."""
def __new__(self) -> Self: ...
def read(self, size: int = -1, /) -> bytes:
"""Read up to size bytes from the memory BIO.

View File

@@ -53,6 +53,8 @@ class RLock:
to be available for other threads.
"""
__enter__ = acquire
"""Lock the lock."""
def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None:
"""Release the lock."""
if sys.version_info >= (3, 14):

View File

@@ -337,6 +337,8 @@ if sys.platform == "win32":
"""OVERLAPPED structure wrapper"""
event: int
"""overlapped event handle"""
def GetOverlappedResult(self, wait: bool, /) -> tuple[int, int]: ...
def cancel(self) -> None: ...
def getbuffer(self) -> bytes | None: ...

View File

@@ -1444,6 +1444,8 @@ class Tuple(expr):
elts: list[expr]
ctx: expr_context # Not present in Python < 3.13 if not passed to `__init__`
dims: list[expr]
"""Deprecated. Use elts instead."""
if sys.version_info >= (3, 13):
def __init__(self, elts: list[expr] = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ...
else:

View File

@@ -116,13 +116,17 @@ if sys.platform == "win32":
if sys.version_info >= (3, 14):
class _WindowsSelectorEventLoopPolicy(events._BaseDefaultEventLoopPolicy):
_loop_factory: ClassVar[type[SelectorEventLoop]]
"""Windows version of selector event loop."""
class _WindowsProactorEventLoopPolicy(events._BaseDefaultEventLoopPolicy):
_loop_factory: ClassVar[type[ProactorEventLoop]]
"""Windows version of proactor event loop using IOCP."""
else:
class WindowsSelectorEventLoopPolicy(events.BaseDefaultEventLoopPolicy):
_loop_factory: ClassVar[type[SelectorEventLoop]]
"""Windows version of selector event loop."""
def get_child_watcher(self) -> NoReturn:
"""Get the watcher for child processes."""
@@ -131,6 +135,8 @@ if sys.platform == "win32":
class WindowsProactorEventLoopPolicy(events.BaseDefaultEventLoopPolicy):
_loop_factory: ClassVar[type[ProactorEventLoop]]
"""Windows version of proactor event loop using IOCP."""
def get_child_watcher(self) -> NoReturn:
"""Get the watcher for child processes."""

View File

@@ -4545,7 +4545,11 @@ class BaseException:
args: tuple[Any, ...]
__cause__: BaseException | None
"""exception cause"""
__context__: BaseException | None
"""exception context"""
__suppress_context__: bool
__traceback__: TracebackType | None
def __init__(self, *args: object) -> None: ...
@@ -4574,6 +4578,7 @@ class SystemExit(BaseException):
"""Request to exit from the interpreter."""
code: sys._ExitCode
"""exception code"""
class Exception(BaseException):
"""Common base class for all non-exit exceptions."""
@@ -4583,18 +4588,28 @@ class StopIteration(Exception):
"""Signal the end from iterator.__next__()."""
value: Any
"""generator return value"""
@disjoint_base
class OSError(Exception):
"""Base class for I/O related errors."""
errno: int | None
"""POSIX exception code"""
strerror: str | None
"""exception strerror"""
# filename, filename2 are actually str | bytes | None
filename: Any
"""exception filename"""
filename2: Any
"""second exception filename"""
if sys.platform == "win32":
winerror: int
"""Win32 exception code"""
EnvironmentError = OSError
IOError = OSError
@@ -4614,7 +4629,10 @@ if sys.version_info >= (3, 10):
def __init__(self, *args: object, name: str | None = None, obj: object = None) -> None: ...
name: str | None
"""attribute name"""
obj: object
"""object"""
else:
class AttributeError(Exception):
@@ -4632,10 +4650,17 @@ class ImportError(Exception):
def __init__(self, *args: object, name: str | None = None, path: str | None = None) -> None: ...
name: str | None
"""module name"""
path: str | None
"""module path"""
msg: str # undocumented
"""exception message"""
if sys.version_info >= (3, 12):
name_from: str | None # undocumented
"""name imported from module"""
class LookupError(Exception):
"""Base class for lookup errors."""
@@ -4650,6 +4675,7 @@ if sys.version_info >= (3, 10):
def __init__(self, *args: object, name: str | None = None) -> None: ...
name: str | None
"""name"""
else:
class NameError(Exception):
@@ -4669,16 +4695,31 @@ class SyntaxError(Exception):
"""Invalid syntax."""
msg: str
"""exception msg"""
filename: str | None
"""exception filename"""
lineno: int | None
"""exception lineno"""
offset: int | None
"""exception offset"""
text: str | None
"""exception text"""
# Errors are displayed differently if this attribute exists on the exception.
# The value is always None.
print_file_and_line: None
"""exception print_file_and_line"""
if sys.version_info >= (3, 10):
end_lineno: int | None
"""exception end lineno"""
end_offset: int | None
"""exception end offset"""
@overload
def __init__(self) -> None: ...
@@ -4797,10 +4838,20 @@ class UnicodeDecodeError(UnicodeError):
"""Unicode decoding error."""
encoding: str
"""exception encoding"""
object: bytes
"""exception object"""
start: int
"""exception start"""
end: int
"""exception end"""
reason: str
"""exception reason"""
def __init__(self, encoding: str, object: ReadableBuffer, start: int, end: int, reason: str, /) -> None: ...
@disjoint_base
@@ -4808,10 +4859,20 @@ class UnicodeEncodeError(UnicodeError):
"""Unicode encoding error."""
encoding: str
"""exception encoding"""
object: str
"""exception object"""
start: int
"""exception start"""
end: int
"""exception end"""
reason: str
"""exception reason"""
def __init__(self, encoding: str, object: str, start: int, end: int, reason: str, /) -> None: ...
@disjoint_base
@@ -4819,10 +4880,20 @@ class UnicodeTranslateError(UnicodeError):
"""Unicode translation error."""
encoding: None
"""exception encoding"""
object: str
"""exception object"""
start: int
"""exception start"""
end: int
"""exception end"""
reason: str
"""exception reason"""
def __init__(self, object: str, start: int, end: int, reason: str, /) -> None: ...
class Warning(Exception):

View File

@@ -731,6 +731,8 @@ class defaultdict(dict[_KT, _VT]):
"""
default_factory: Callable[[], _VT] | None
"""Factory for default value called by __missing__()."""
@overload
def __init__(self) -> None: ...
@overload

View File

@@ -46,6 +46,9 @@ if sys.version_info >= (3, 14):
class InterpreterPoolExecutor(ThreadPoolExecutor):
BROKEN: type[BrokenInterpreterPool]
"""
Raised when a worker thread in an InterpreterPoolExecutor failed initializing.
"""
@overload # type: ignore[override]
@classmethod

View File

@@ -96,6 +96,9 @@ class BrokenThreadPool(BrokenExecutor):
class ThreadPoolExecutor(Executor):
if sys.version_info >= (3, 14):
BROKEN: type[BrokenThreadPool]
"""
Raised when a worker thread in a ThreadPoolExecutor failed initializing.
"""
_max_workers: int
_idle_semaphore: Semaphore

View File

@@ -762,6 +762,8 @@ class Context:
def __copy__(self) -> Context: ...
# see https://github.com/python/cpython/issues/94107
__hash__: ClassVar[None] # type: ignore[assignment]
"""Return hash(self)."""
def Etiny(self) -> int:
"""Return a value equal to Emin - prec + 1, which is the minimum exponent value
for subnormal results. When underflow occurs, the exponent is set to Etiny.

View File

@@ -696,6 +696,8 @@ class auto:
def __and__(self, other: int | Self) -> Self: ...
def __xor__(self, other: int | Self) -> Self: ...
__ror__ = __or__
"""Return value|self."""
__rand__ = __and__
__rxor__ = __xor__

View File

@@ -13,6 +13,10 @@ class BaseProcess:
name: str
daemon: bool
"""
Return whether process is a daemon
"""
authkey: bytes
_identity: tuple[int, ...] # undocumented
def __init__(

View File

@@ -103,6 +103,8 @@ class AbstractReducer(metaclass=ABCMeta):
ForkingPickler = _ForkingPickler
register = _register
"""Register a reduce function for a type."""
dump = _dump
send_handle = _send_handle
recv_handle = _recv_handle

View File

@@ -733,6 +733,24 @@ class _Environ(MutableMapping[AnyStr, AnyStr], Generic[AnyStr]):
encodevalue: _EnvironCodeFunc[AnyStr],
decodevalue: _EnvironCodeFunc[AnyStr],
) -> None: ...
@overload
def get(self, key: AnyStr, default: None = None) -> AnyStr | None:
"""D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None."""
@overload
def get(self, key: AnyStr, default: AnyStr) -> AnyStr: ...
@overload
def get(self, key: AnyStr, default: _T) -> AnyStr | _T: ...
@overload
def pop(self, key: AnyStr) -> AnyStr:
"""D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised.
"""
@overload
def pop(self, key: AnyStr, default: AnyStr) -> AnyStr: ...
@overload
def pop(self, key: AnyStr, default: _T) -> AnyStr | _T: ...
def setdefault(self, key: AnyStr, value: AnyStr) -> AnyStr: ...
def copy(self) -> dict[AnyStr, AnyStr]: ...
def __delitem__(self, key: AnyStr) -> None: ...

View File

@@ -476,8 +476,7 @@ The mean (expected value) and variance of the random variable are:
"""
randint = _inst.randint
"""Return random integer in range [a, b], including both end points.
"""
"""Return random integer in range [a, b], including both end points."""
choice = _inst.choice
"""Choose a random element from a non-empty sequence."""
@@ -624,6 +623,7 @@ if sys.version_info >= (3, 12):
Var[X] = n * p * (1 - p)
"""
betavariate = _inst.betavariate
"""Beta distribution.

View File

@@ -132,6 +132,8 @@ if sys.platform != "linux" and sys.platform != "win32":
"""
closed: bool
"""True if the kqueue handler is closed"""
def __init__(self) -> None: ...
def close(self) -> None:
"""Close the kqueue control file descriptor.
@@ -226,6 +228,8 @@ if sys.platform == "linux":
Further operations on the epoll object will raise an exception.
"""
closed: bool
"""True if the epoll handler is closed"""
def fileno(self) -> int:
"""Return the epoll control file descriptor."""

View File

@@ -471,9 +471,13 @@ class SSLSocket(socket.socket):
"""
context: SSLContext
"""The SSLContext that is currently in use."""
server_side: bool
server_hostname: str | None
session: SSLSession | None
"""The SSLSession for client socket."""
@property
def session_reused(self) -> bool | None:
"""Was the client session reused during handshake"""
@@ -632,11 +636,33 @@ class SSLContext(_SSLContext):
# However, the docs explicitly state that it's OK to override these attributes on instances,
# so making these ClassVars wouldn't be appropriate
sslobject_class: type[SSLObject]
"""This class implements an interface on top of a low-level SSL object as
implemented by OpenSSL. This object captures the state of an SSL connection
but does not provide any network IO itself. IO needs to be performed
through separate "BIO" objects which are OpenSSL's IO abstraction layer.
This class does not have a public constructor. Instances are returned by
``SSLContext.wrap_bio``. This class is typically used by framework authors
that want to implement asynchronous IO for SSL through memory buffers.
When compared to ``SSLSocket``, this object lacks the following features:
* Any form of network IO, including methods such as ``recv`` and ``send``.
* The ``do_handshake_on_connect`` and ``suppress_ragged_eofs`` machinery.
"""
sslsocket_class: type[SSLSocket]
"""This class implements a subtype of socket.socket that wraps
the underlying OS socket in an SSL context when necessary, and
provides read and write methods over that channel.
"""
keylog_filename: str
post_handshake_auth: bool
if sys.version_info >= (3, 10):
security_level: int
"""The current security level."""
if sys.version_info >= (3, 10):
@overload
def __new__(cls, protocol: int, *args: Any, **kwargs: Any) -> Self: ...
@@ -774,6 +800,8 @@ class SSLObject:
"""
context: SSLContext
"""The SSLContext that is currently in use."""
@property
def server_side(self) -> bool:
"""Whether this is a server-side socket."""
@@ -784,6 +812,8 @@ class SSLObject:
server hostname is set.
"""
session: SSLSession | None
"""The SSLSession for client socket."""
@property
def session_reused(self) -> bool:
"""Was the client session reused during handshake"""

View File

@@ -11,7 +11,10 @@ class Template: # TODO: consider making `Template` generic on `TypeVarTuple`
"""Template object"""
strings: tuple[str, ...]
"""Strings"""
interpolations: tuple[Interpolation, ...]
"""Interpolations"""
def __new__(cls, *args: str | Interpolation) -> Template: ...
def __iter__(self) -> Iterator[str | Interpolation]:
@@ -32,9 +35,16 @@ class Interpolation:
"""Interpolation object"""
value: Any # TODO: consider making `Interpolation` generic in runtime
"""Value"""
expression: str
"""Expression"""
conversion: Literal["a", "r", "s"] | None
"""Conversion"""
format_spec: str
"""Format specifier"""
__match_args__ = ("value", "expression", "conversion", "format_spec")

View File

@@ -1759,6 +1759,8 @@ class CalledProcessError(SubprocessError):
# morally: str | bytes | None
stdout: Any
"""Alias for output attribute, to match stderr"""
stderr: Any
def __init__(
self, returncode: int, cmd: _CMD, output: str | bytes | None = None, stderr: str | bytes | None = None

View File

@@ -801,13 +801,6 @@ def intern(string: LiteralString, /) -> LiteralString:
def intern(string: str, /) -> str: ... # type: ignore[misc]
__interactivehook__: Callable[[], object]
"""Configure readline completion on interactive prompts.
If the readline module can be imported, the hook will set the Tab key
as completion key and register ~/.python_history as history file.
This can be overridden in the sitecustomize or usercustomize module,
or in a PYTHONSTARTUP file.
"""
if sys.version_info >= (3, 13):
def _is_gil_enabled() -> bool:

View File

@@ -126,6 +126,13 @@ class TarFile:
fileobj: _Fileobj | None
format: _TarFormat | None
tarinfo: type[TarInfo]
"""Informational class which holds the details about an
archive member given by a tar header block.
TarInfo objects are returned by TarFile.getmember(),
TarFile.getmembers() and TarFile.gettarinfo() and are
usually created internally.
"""
dereference: bool | None
ignore_zeros: bool | None
encoding: str | None
@@ -1117,6 +1124,8 @@ class TarInfo:
)
name: str
path: str
"""In pax headers, "name" is called "path"."""
size: int
mtime: int | float
chksum: int

View File

@@ -177,6 +177,13 @@ class Thread:
"""
name: str
"""A string used for identification purposes only.
It has no semantics. Multiple threads may be given the same name. The
initial name is set by the constructor.
"""
@property
def ident(self) -> int | None:
"""Thread identifier of this thread or None if it has not been started.
@@ -187,6 +194,17 @@ class Thread:
"""
daemon: bool
"""A boolean value indicating whether this thread is a daemon thread.
This must be set before start() is called, otherwise RuntimeError is
raised. Its initial value is inherited from the creating thread; the
main thread is not a daemon thread and therefore all threads created in
the main thread default to daemon = False.
The entire Python program exits when only daemon threads are left.
"""
if sys.version_info >= (3, 14):
def __init__(
self,
@@ -652,11 +670,8 @@ class Event:
"""
excepthook: Callable[[_ExceptHookArgs], object]
"""Handle uncaught Thread.run() exception."""
if sys.version_info >= (3, 10):
__excepthook__: Callable[[_ExceptHookArgs], object]
"""Handle uncaught Thread.run() exception."""
ExceptHookArgs = _ExceptHookArgs
class Timer(Thread):

View File

@@ -56,10 +56,6 @@ _Timer: TypeAlias = Callable[[], float]
_Stmt: TypeAlias = str | Callable[[], object]
default_timer: _Timer
"""perf_counter() -> float
Performance counter for benchmarking.
"""
class Timer:
"""Class for timing execution speed of small code snippets.

View File

@@ -2294,6 +2294,12 @@ class Tk(Misc, Wm):
.CLASSNAME.py if such a file exists in the home directory.
"""
report_callback_exception: Callable[[type[BaseException], BaseException, TracebackType | None], object]
"""Report callback exception on sys.stderr.
Applications may want to override this internal function, and
should when sys.stderr is None.
"""
# Tk has __getattr__ so that tk_instance.foo falls back to tk_instance.tk.foo
# Please keep in sync with _tkinter.TkappType.
# Some methods are intentionally missing because they are inherited from Misc instead.
@@ -6172,7 +6178,11 @@ class Image(_Image):
def __setitem__(self, key, value) -> None: ...
def __getitem__(self, key): ...
configure: Incomplete
"""Configure the image."""
config: Incomplete
"""Configure the image."""
def type(self):
"""Return the type of the image, e.g. "photo" or "bitmap"."""

View File

@@ -2447,6 +2447,7 @@ class LabeledScale(Frame):
"""
# destroy is overridden, signature does not change
value: Any
"""Return current scale value."""
class OptionMenu(Menubutton):
"""Themed OptionMenu, based after tkinter's OptionMenu, which allows

View File

@@ -101,14 +101,19 @@ class FunctionType:
__name__: str
__qualname__: str
__annotations__: dict[str, AnnotationForm]
"""Dict of annotations in a function object."""
if sys.version_info >= (3, 14):
__annotate__: AnnotateFunc | None
"""Get the code object for a function."""
__kwdefaults__: dict[str, Any] | None
if sys.version_info >= (3, 10):
@property
def __builtins__(self) -> dict[str, Any]: ...
if sys.version_info >= (3, 12):
__type_params__: tuple[TypeVar | ParamSpec | TypeVarTuple, ...]
"""Get the declared type parameters for a function."""
__module__: str
if sys.version_info >= (3, 13):
@@ -335,12 +340,15 @@ class CodeType:
"""Return a copy of the code object with new values for the specified fields."""
if sys.version_info >= (3, 13):
__replace__ = replace
"""The same as replace()."""
@final
class MappingProxyType(Mapping[_KT_co, _VT_co]): # type: ignore[type-var] # pyright: ignore[reportInvalidTypeArguments]
"""Read-only proxy of a mapping."""
__hash__: ClassVar[None] # type: ignore[assignment]
"""Return hash(self)."""
def __new__(cls, mapping: SupportsKeysAndGetItem[_KT_co, _VT_co]) -> Self: ...
def __getitem__(self, key: _KT_co, /) -> _VT_co: # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues]
"""Return self[key]."""
@@ -485,7 +493,11 @@ class GeneratorType(Generator[_YieldT_co, _SendT_contra, _ReturnT_co]):
@property
def gi_suspended(self) -> bool: ...
__name__: str
"""name of the generator"""
__qualname__: str
"""qualified name of the generator"""
def __iter__(self) -> Self:
"""Implement iter(self)."""
@@ -527,7 +539,11 @@ class AsyncGeneratorType(AsyncGenerator[_YieldT_co, _SendT_contra]):
@property
def ag_running(self) -> bool: ...
__name__: str
"""name of the async generator"""
__qualname__: str
"""qualified name of the async generator"""
if sys.version_info >= (3, 12):
@property
def ag_suspended(self) -> bool: ...
@@ -568,7 +584,11 @@ _ReturnT_nd_co = TypeVar("_ReturnT_nd_co", covariant=True)
@final
class CoroutineType(Coroutine[_YieldT_co, _SendT_nd_contra, _ReturnT_nd_co]):
__name__: str
"""name of the coroutine"""
__qualname__: str
"""qualified name of the coroutine"""
@property
def cr_await(self) -> Any | None:
"""object being awaited on, or None"""
@@ -769,8 +789,12 @@ class FrameType:
def f_locals(self) -> dict[str, Any]:
"""Return the mapping used by the frame to look up local variables."""
f_trace: Callable[[FrameType, str, Any], Any] | None
"""Return the trace function for this frame, or None if no trace function is set."""
f_trace_lines: bool
f_trace_opcodes: bool
"""Return True if opcode tracing is enabled, False otherwise."""
def clear(self) -> None:
"""Clear all references held by the frame."""
if sys.version_info >= (3, 14):

View File

@@ -379,41 +379,41 @@ Protocol classes can be generic, they are defined as::
Callable: _SpecialForm
"""Deprecated alias to collections.abc.Callable.
Callable[[int], str] signifies a function that takes a single
parameter of type int and returns a str.
Callable[[int], str] signifies a function that takes a single
parameter of type int and returns a str.
The subscription syntax must always be used with exactly two
values: the argument list and the return type.
The argument list must be a list of types, a ParamSpec,
Concatenate or ellipsis. The return type must be a single type.
The subscription syntax must always be used with exactly two
values: the argument list and the return type.
The argument list must be a list of types, a ParamSpec,
Concatenate or ellipsis. The return type must be a single type.
There is no syntax to indicate optional or keyword arguments;
such function types are rarely used as callback types.
"""
There is no syntax to indicate optional or keyword arguments;
such function types are rarely used as callback types.
"""
Type: _SpecialForm
"""Deprecated alias to builtins.type.
builtins.type or typing.Type can be used to annotate class objects.
For example, suppose we have the following classes::
builtins.type or typing.Type can be used to annotate class objects.
For example, suppose we have the following classes::
class User: ... # Abstract base for User classes
class BasicUser(User): ...
class ProUser(User): ...
class TeamUser(User): ...
class User: ... # Abstract base for User classes
class BasicUser(User): ...
class ProUser(User): ...
class TeamUser(User): ...
And a function that takes a class argument that's a subclass of
User and returns an instance of the corresponding class::
And a function that takes a class argument that's a subclass of
User and returns an instance of the corresponding class::
def new_user[U](user_class: Type[U]) -> U:
user = user_class()
# (Here we could write the user object to a database)
return user
def new_user[U](user_class: Type[U]) -> U:
user = user_class()
# (Here we could write the user object to a database)
return user
joe = new_user(BasicUser)
joe = new_user(BasicUser)
At this point the type checker knows that joe has type BasicUser.
"""
At this point the type checker knows that joe has type BasicUser.
"""
NoReturn: _SpecialForm
"""Special type indicating functions that never return.
@@ -456,14 +456,14 @@ Optional: _SpecialForm
Tuple: _SpecialForm
"""Deprecated alias to builtins.tuple.
Tuple[X, Y] is the cross-product type of X and Y.
Tuple[X, Y] is the cross-product type of X and Y.
Example: Tuple[T1, T2] is a tuple of two elements corresponding
to type variables T1 and T2. Tuple[int, float, str] is a tuple
of an int, a float and a string.
Example: Tuple[T1, T2] is a tuple of two elements corresponding
to type variables T1 and T2. Tuple[int, float, str] is a tuple
of an int, a float and a string.
To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
"""
To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
"""
Final: _SpecialForm
"""Special typing construct to indicate final names to type checkers.

View File

@@ -551,15 +551,6 @@ underlying type::
"""
_AnnotatedAlias: Any # undocumented
"""Runtime representation of an annotated type.
At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'
with extra metadata. The alias behaves like a normal typing alias.
Instantiating is the same as instantiating the underlying type; binding
it to types is also the same.
The metadata itself is stored in a '__metadata__' attribute as a tuple.
"""
# New and changed things in 3.10
if sys.version_info >= (3, 10):
@@ -609,23 +600,19 @@ else:
def __init__(self, origin: ParamSpec) -> None: ...
Concatenate: _SpecialForm
"""Special form for annotating higher-order functions.
``Concatenate`` can be used in conjunction with ``ParamSpec`` and
``Callable`` to represent a higher-order function which adds, removes or
transforms the parameters of a callable.
"""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
higher order function which adds, removes or transforms parameters of a
callable.
For example::
Callable[Concatenate[int, P], int]
Callable[Concatenate[int, P], int]
See PEP 612 for detailed information.
"""
TypeAlias: _SpecialForm
"""Special form for marking type aliases.
Use TypeAlias to indicate that an assignment should
"""Special marker indicating that an assignment should
be recognized as a proper type alias definition by type
checkers.
@@ -637,52 +624,44 @@ else:
"""
TypeGuard: _SpecialForm
"""Special typing construct for marking user-defined type predicate functions.
``TypeGuard`` can be used to annotate the return type of a user-defined
type predicate function. ``TypeGuard`` only accepts a single type argument.
"""Special typing form used to annotate the return type of a user-defined
type guard function. ``TypeGuard`` only accepts a single type argument.
At runtime, functions marked this way should return a boolean.
``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
type checkers to determine a more precise type of an expression within a
program's code flow. Usually type narrowing is done by analyzing
conditional code flow and applying the narrowing to a block of code. The
conditional expression here is sometimes referred to as a "type predicate".
conditional expression here is sometimes referred to as a "type guard".
Sometimes it would be convenient to use a user-defined boolean function
as a type predicate. Such a function should use ``TypeGuard[...]`` or
``TypeIs[...]`` as its return type to alert static type checkers to
this intention. ``TypeGuard`` should be used over ``TypeIs`` when narrowing
from an incompatible type (e.g., ``list[object]`` to ``list[int]``) or when
the function does not return ``True`` for all instances of the narrowed type.
as a type guard. Such a function should use ``TypeGuard[...]`` as its
return type to alert static type checkers to this intention.
Using ``-> TypeGuard[NarrowedType]`` tells the static type checker that
for a given function:
Using ``-> TypeGuard`` tells the static type checker that for a given
function:
1. The return value is a boolean.
2. If the return value is ``True``, the type of its argument
is ``NarrowedType``.
is the type inside ``TypeGuard``.
For example::
def is_str_list(val: list[object]) -> TypeGuard[list[str]]:
'''Determines whether all objects in the list are strings'''
return all(isinstance(x, str) for x in val)
def func1(val: list[object]):
if is_str_list(val):
# Type of ``val`` is narrowed to ``list[str]``.
print(" ".join(val))
else:
# Type of ``val`` remains as ``list[object]``.
print("Not a list of strings!")
def is_str(val: Union[str, float]):
# "isinstance" type guard
if isinstance(val, str):
# Type of ``val`` is narrowed to ``str``
...
else:
# Else, type of ``val`` is narrowed to ``float``.
...
Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
form of ``TypeA`` (it can even be a wider form) and this may lead to
type-unsafe results. The main reason is to allow for things like
narrowing ``list[object]`` to ``list[str]`` even though the latter is not
a subtype of the former, since ``list`` is invariant. The responsibility of
writing type-safe type predicates is left to the user.
narrowing ``List[object]`` to ``List[str]`` even though the latter is not
a subtype of the former, since ``List`` is invariant. The responsibility of
writing type-safe type guards is left to the user.
``TypeGuard`` also works with type variables. For more information, see
PEP 647 (User-Defined Type Guards).
@@ -724,16 +703,13 @@ else:
Example::
from typing import Self
from typing import Self
class Foo:
def return_self(self) -> Self:
...
return self
class ReturnsSelf:
def parse(self, data: bytes) -> Self:
...
return self
This is especially useful for:
- classmethods that are used as alternative constructors
- annotating an `__enter__` method which returns self
"""
Never: _SpecialForm
@@ -742,7 +718,7 @@ else:
This can be used to define a function that should never be
called, or a function that never returns::
from typing import Never
from typing_extensions import Never
def never_call_me(arg: Never) -> None:
pass
@@ -755,7 +731,8 @@ else:
case str():
print("It's a str")
case _:
never_call_me(arg) # OK, arg is of type Never
never_call_me(arg) # ok, arg is of type Never
"""
def reveal_type(obj: _T, /) -> _T:
@@ -816,11 +793,8 @@ else:
def get_overloads(func: Callable[..., object]) -> Sequence[Callable[..., object]]:
"""Return all defined overloads for *func* as a sequence."""
Required: _SpecialForm
"""Special typing construct to mark a TypedDict key as required.
This is mainly useful for total=False TypedDicts.
For example::
"""A special typing construct to mark a key of a total=False TypedDict
as required. For example:
class Movie(TypedDict, total=False):
title: Required[str]
@@ -836,9 +810,8 @@ else:
"""
NotRequired: _SpecialForm
"""Special typing construct to mark a TypedDict key as potentially missing.
For example::
"""A special typing construct to mark a key of a TypedDict as
potentially missing. For example:
class Movie(TypedDict):
title: str
@@ -855,70 +828,57 @@ else:
Example::
from typing import LiteralString
from typing_extensions import LiteralString
def run_query(sql: LiteralString) -> None:
...
def query(sql: LiteralString) -> ...:
...
def caller(arbitrary_string: str, literal_string: LiteralString) -> None:
run_query("SELECT * FROM students") # OK
run_query(literal_string) # OK
run_query("SELECT * FROM " + literal_string) # OK
run_query(arbitrary_string) # type checker error
run_query( # type checker error
f"SELECT * FROM students WHERE name = {arbitrary_string}"
)
query("SELECT * FROM table") # ok
query(f"SELECT * FROM {input()}") # not ok
See PEP 675 for details.
Only string literals and other LiteralStrings are compatible
with LiteralString. This provides a tool to help prevent
security issues such as SQL injection.
"""
Unpack: _SpecialForm
"""Type unpack operator.
The type unpack operator takes the child types from some container type,
such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'.
such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'. For
example:
For example::
# For some generic class `Foo`:
Foo[Unpack[tuple[int, str]]] # Equivalent to Foo[int, str]
# For some generic class `Foo`:
Foo[Unpack[tuple[int, str]]] # Equivalent to Foo[int, str]
Ts = TypeVarTuple('Ts')
# Specifies that `Bar` is generic in an arbitrary number of types.
# (Think of `Ts` as a tuple of an arbitrary number of individual
# `TypeVar`s, which the `Unpack` is 'pulling out' directly into the
# `Generic[]`.)
class Bar(Generic[Unpack[Ts]]): ...
Bar[int] # Valid
Bar[int, str] # Also valid
Ts = TypeVarTuple('Ts')
# Specifies that `Bar` is generic in an arbitrary number of types.
# (Think of `Ts` as a tuple of an arbitrary number of individual
# `TypeVar`s, which the `Unpack` is 'pulling out' directly into the
# `Generic[]`.)
class Bar(Generic[Unpack[Ts]]): ...
Bar[int] # Valid
Bar[int, str] # Also valid
From Python 3.11, this can also be done using the `*` operator::
From Python 3.11, this can also be done using the `*` operator:
Foo[*tuple[int, str]]
class Bar(Generic[*Ts]): ...
And from Python 3.12, it can be done using built-in syntax for generics::
Foo[*tuple[int, str]]
class Bar[*Ts]: ...
The operator can also be used along with a `TypedDict` to annotate
`**kwargs` in a function signature::
`**kwargs` in a function signature. For instance:
class Movie(TypedDict):
name: str
year: int
class Movie(TypedDict):
name: str
year: int
# This function expects two keyword arguments - *name* of type `str` and
# *year* of type `int`.
def foo(**kwargs: Unpack[Movie]): ...
# This function expects two keyword arguments - *name* of type `str` and
# *year* of type `int`.
def foo(**kwargs: Unpack[Movie]): ...
Note that there is only some runtime checking of this operator. Not
everything the runtime allows may be accepted by static type checkers.
For more information, see PEPs 646 and 692.
For more information, see PEP 646 and PEP 692.
"""
def dataclass_transform(
@@ -1433,7 +1393,7 @@ else:
ReadOnly: _SpecialForm
"""A special typing construct to mark an item of a TypedDict as read-only.
For example::
For example:
class Movie(TypedDict):
title: ReadOnly[str]
@@ -1447,68 +1407,41 @@ else:
"""
TypeIs: _SpecialForm
"""Special typing construct for marking user-defined type predicate functions.
``TypeIs`` can be used to annotate the return type of a user-defined
type predicate function. ``TypeIs`` only accepts a single type argument.
At runtime, functions marked this way should return a boolean and accept
at least one argument.
"""Special typing form used to annotate the return type of a user-defined
type narrower function. ``TypeIs`` only accepts a single type argument.
At runtime, functions marked this way should return a boolean.
``TypeIs`` aims to benefit *type narrowing* -- a technique used by static
type checkers to determine a more precise type of an expression within a
program's code flow. Usually type narrowing is done by analyzing
conditional code flow and applying the narrowing to a block of code. The
conditional expression here is sometimes referred to as a "type predicate".
conditional expression here is sometimes referred to as a "type guard".
Sometimes it would be convenient to use a user-defined boolean function
as a type predicate. Such a function should use ``TypeIs[...]`` or
``TypeGuard[...]`` as its return type to alert static type checkers to
this intention. ``TypeIs`` usually has more intuitive behavior than
``TypeGuard``, but it cannot be used when the input and output types
are incompatible (e.g., ``list[object]`` to ``list[int]``) or when the
function does not return ``True`` for all instances of the narrowed type.
as a type guard. Such a function should use ``TypeIs[...]`` as its
return type to alert static type checkers to this intention.
Using ``-> TypeIs[NarrowedType]`` tells the static type checker that for
a given function:
Using ``-> TypeIs`` tells the static type checker that for a given
function:
1. The return value is a boolean.
2. If the return value is ``True``, the type of its argument
is the intersection of the argument's original type and
``NarrowedType``.
3. If the return value is ``False``, the type of its argument
is narrowed to exclude ``NarrowedType``.
is the intersection of the type inside ``TypeIs`` and the argument's
previously known type.
For example::
from typing import assert_type, final, TypeIs
def is_awaitable(val: object) -> TypeIs[Awaitable[Any]]:
return hasattr(val, '__await__')
class Parent: pass
class Child(Parent): pass
@final
class Unrelated: pass
def is_parent(val: object) -> TypeIs[Parent]:
return isinstance(val, Parent)
def run(arg: Child | Unrelated):
if is_parent(arg):
# Type of ``arg`` is narrowed to the intersection
# of ``Parent`` and ``Child``, which is equivalent to
# ``Child``.
assert_type(arg, Child)
def f(val: Union[int, Awaitable[int]]) -> int:
if is_awaitable(val):
assert_type(val, Awaitable[int])
else:
# Type of ``arg`` is narrowed to exclude ``Parent``,
# so only ``Unrelated`` is left.
assert_type(arg, Unrelated)
The type inside ``TypeIs`` must be consistent with the type of the
function's argument; if it is not, static type checkers will raise
an error. An incorrectly written ``TypeIs`` function can lead to
unsound behavior in the type system; it is the user's responsibility
to write such functions in a type-safe manner.
assert_type(val, int)
``TypeIs`` also works with type variables. For more information, see
PEP 742 (Narrowing types with ``TypeIs``).
PEP 742 (Narrowing types with TypeIs).
"""
# TypeAliasType was added in Python 3.12, but had significant changes in 3.14.

View File

@@ -572,7 +572,10 @@ class _patch_dict:
def __exit__(self, *args: object) -> Any:
"""Unpatch the dict."""
start: Any
"""Activate a patch, returning any created mock."""
stop: Any
"""Stop an active patch."""
# This class does not exist at runtime, it's a hack to add methods to the
# patch() function.

View File

@@ -32,6 +32,8 @@ class _WritelnDecorator:
# These attributes are prevented by __getattr__
stream: Never
__getstate__: Never
"""Helper for pickle."""
# Methods proxied from the wrapped stream object via __getattr__
def flush(self) -> object: ...
def write(self, s: str, /) -> object: ...
@@ -70,6 +72,11 @@ class TextTestRunner:
"""
resultclass: _ResultClassType
"""A test result class that can print formatted text results to a stream.
Used by TextTestRunner.
"""
stream: _WritelnDecorator
descriptions: bool
verbosity: int

View File

@@ -21,6 +21,8 @@ class URLError(OSError):
reason: str | BaseException
# The `filename` attribute only exists if it was provided to `__init__` and wasn't `None`.
filename: str
"""exception filename"""
def __init__(self, reason: str | BaseException, filename: str | None = None) -> None: ...
class HTTPError(URLError, addinfourl):

View File

@@ -51,6 +51,8 @@ class CallableProxyType(Generic[_CallableT]): # "weakcallableproxy"
def __eq__(self, value: object, /) -> bool: ...
def __getattr__(self, attr: str) -> Any: ...
__call__: _CallableT
"""Call self as a function."""
__hash__: ClassVar[None] # type: ignore[assignment]
@final
@@ -58,6 +60,7 @@ class ProxyType(Generic[_T]): # "weakproxy"
def __eq__(self, value: object, /) -> bool: ...
def __getattr__(self, attr: str) -> Any: ...
__hash__: ClassVar[None] # type: ignore[assignment]
"""Return hash(self)."""
@disjoint_base
class ReferenceType(Generic[_T]): # "weakref"
@@ -291,3 +294,4 @@ class finalize(Generic[_P, _T]):
def alive(self) -> bool:
"""Whether finalizer is alive"""
atexit: bool
"""Whether finalizer should be called at exit"""

View File

@@ -743,6 +743,7 @@ class Document(Node, DocumentLS):
documentURI: str | None
doctype: DocumentType | None
documentElement: Element | None
"""Top-level element of this document."""
def __init__(self) -> None: ...
def appendChild(self, node: _DocumentChildrenVar) -> _DocumentChildrenVar: ... # type: ignore[override]

View File

@@ -137,9 +137,17 @@ _OtherTag = TypeVar("_OtherTag", default=str, bound=str | _ElementCallable)
@disjoint_base
class Element(Generic[_Tag]):
tag: _Tag
"""A string identifying what kind of data this element represents"""
attrib: dict[str, str]
"""A dictionary containing the element's attributes"""
text: str | None
"""A string of text directly after the start tag, or None"""
tail: str | None
"""A string of text directly after the end tag, or None"""
def __init__(self, tag: _Tag, attrib: dict[str, str] = {}, **extra: str) -> None: ...
def append(self, subelement: Element[Any], /) -> None: ...
def clear(self) -> None: ...

View File

@@ -175,6 +175,8 @@ class ZipFile:
filename: str | None
debug: int
comment: bytes
"""The comment text associated with the ZIP file."""
filelist: list[ZipInfo]
fp: IO[bytes] | None
NameToInfo: dict[str, ZipInfo]