[ty] Sync vendored typeshed stubs (#20083)

Co-authored-by: typeshedbot <>
Co-authored-by: Alex Waygood <alex.waygood@gmail.com>
This commit is contained in:
github-actions[bot] 2025-08-25 17:01:51 +00:00 committed by GitHub
parent db423ee978
commit ba47010150
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
84 changed files with 1733 additions and 846 deletions

View file

@ -199,14 +199,13 @@ mod tests {
assert_snapshot!(test.goto_type_definition(), @r#" assert_snapshot!(test.goto_type_definition(), @r#"
info[goto-type-definition]: Type definition info[goto-type-definition]: Type definition
--> stdlib/builtins.pyi:901:7 --> stdlib/builtins.pyi:911:7
| |
899 | def __getitem__(self, key: int, /) -> str | int | None: ... 910 | @disjoint_base
900 | 911 | class str(Sequence[str]):
901 | class str(Sequence[str]):
| ^^^ | ^^^
902 | """str(object='') -> str 912 | """str(object='') -> str
903 | str(bytes_or_buffer[, encoding[, errors]]) -> str 913 | str(bytes_or_buffer[, encoding[, errors]]) -> str
| |
info: Source info: Source
--> main.py:4:1 --> main.py:4:1
@ -228,14 +227,13 @@ mod tests {
assert_snapshot!(test.goto_type_definition(), @r#" assert_snapshot!(test.goto_type_definition(), @r#"
info[goto-type-definition]: Type definition info[goto-type-definition]: Type definition
--> stdlib/builtins.pyi:901:7 --> stdlib/builtins.pyi:911:7
| |
899 | def __getitem__(self, key: int, /) -> str | int | None: ... 910 | @disjoint_base
900 | 911 | class str(Sequence[str]):
901 | class str(Sequence[str]):
| ^^^ | ^^^
902 | """str(object='') -> str 912 | """str(object='') -> str
903 | str(bytes_or_buffer[, encoding[, errors]]) -> str 913 | str(bytes_or_buffer[, encoding[, errors]]) -> str
| |
info: Source info: Source
--> main.py:2:10 --> main.py:2:10
@ -344,14 +342,13 @@ mod tests {
assert_snapshot!(test.goto_type_definition(), @r#" assert_snapshot!(test.goto_type_definition(), @r#"
info[goto-type-definition]: Type definition info[goto-type-definition]: Type definition
--> stdlib/builtins.pyi:901:7 --> stdlib/builtins.pyi:911:7
| |
899 | def __getitem__(self, key: int, /) -> str | int | None: ... 910 | @disjoint_base
900 | 911 | class str(Sequence[str]):
901 | class str(Sequence[str]):
| ^^^ | ^^^
902 | """str(object='') -> str 912 | """str(object='') -> str
903 | str(bytes_or_buffer[, encoding[, errors]]) -> str 913 | str(bytes_or_buffer[, encoding[, errors]]) -> str
| |
info: Source info: Source
--> main.py:4:6 --> main.py:4:6
@ -379,14 +376,13 @@ mod tests {
// is an int. Navigating to `str` would match pyright's behavior. // is an int. Navigating to `str` would match pyright's behavior.
assert_snapshot!(test.goto_type_definition(), @r#" assert_snapshot!(test.goto_type_definition(), @r#"
info[goto-type-definition]: Type definition info[goto-type-definition]: Type definition
--> stdlib/builtins.pyi:337:7 --> stdlib/builtins.pyi:344:7
| |
335 | _LiteralInteger = _PositiveInteger | _NegativeInteger | Literal[0] # noqa: Y026 # TODO: Use TypeAlias once mypy bugs are fixed 343 | @disjoint_base
336 | 344 | class int:
337 | class int:
| ^^^ | ^^^
338 | """int([x]) -> integer 345 | """int([x]) -> integer
339 | int(x, base=10) -> integer 346 | int(x, base=10) -> integer
| |
info: Source info: Source
--> main.py:4:6 --> main.py:4:6
@ -411,16 +407,15 @@ f(**kwargs<CURSOR>)
"#, "#,
); );
assert_snapshot!(test.goto_type_definition(), @r###" assert_snapshot!(test.goto_type_definition(), @r#"
info[goto-type-definition]: Type definition info[goto-type-definition]: Type definition
--> stdlib/builtins.pyi:2901:7 --> stdlib/builtins.pyi:2917:7
| |
2899 | """See PEP 585""" 2916 | @disjoint_base
2900 | 2917 | class dict(MutableMapping[_KT, _VT]):
2901 | class dict(MutableMapping[_KT, _VT]):
| ^^^^ | ^^^^
2902 | """dict() -> new empty dictionary 2918 | """dict() -> new empty dictionary
2903 | dict(mapping) -> new dictionary initialized from a mapping object's 2919 | dict(mapping) -> new dictionary initialized from a mapping object's
| |
info: Source info: Source
--> main.py:6:5 --> main.py:6:5
@ -430,7 +425,7 @@ f(**kwargs<CURSOR>)
6 | f(**kwargs) 6 | f(**kwargs)
| ^^^^^^ | ^^^^^^
| |
"###); "#);
} }
#[test] #[test]
@ -444,14 +439,13 @@ f(**kwargs<CURSOR>)
assert_snapshot!(test.goto_type_definition(), @r#" assert_snapshot!(test.goto_type_definition(), @r#"
info[goto-type-definition]: Type definition info[goto-type-definition]: Type definition
--> stdlib/builtins.pyi:901:7 --> stdlib/builtins.pyi:911:7
| |
899 | def __getitem__(self, key: int, /) -> str | int | None: ... 910 | @disjoint_base
900 | 911 | class str(Sequence[str]):
901 | class str(Sequence[str]):
| ^^^ | ^^^
902 | """str(object='') -> str 912 | """str(object='') -> str
903 | str(bytes_or_buffer[, encoding[, errors]]) -> str 913 | str(bytes_or_buffer[, encoding[, errors]]) -> str
| |
info: Source info: Source
--> main.py:3:5 --> main.py:3:5
@ -537,14 +531,13 @@ f(**kwargs<CURSOR>)
assert_snapshot!(test.goto_type_definition(), @r#" assert_snapshot!(test.goto_type_definition(), @r#"
info[goto-type-definition]: Type definition info[goto-type-definition]: Type definition
--> stdlib/builtins.pyi:901:7 --> stdlib/builtins.pyi:911:7
| |
899 | def __getitem__(self, key: int, /) -> str | int | None: ... 910 | @disjoint_base
900 | 911 | class str(Sequence[str]):
901 | class str(Sequence[str]):
| ^^^ | ^^^
902 | """str(object='') -> str 912 | """str(object='') -> str
903 | str(bytes_or_buffer[, encoding[, errors]]) -> str 913 | str(bytes_or_buffer[, encoding[, errors]]) -> str
| |
info: Source info: Source
--> main.py:4:15 --> main.py:4:15
@ -568,13 +561,13 @@ f(**kwargs<CURSOR>)
assert_snapshot!(test.goto_type_definition(), @r#" assert_snapshot!(test.goto_type_definition(), @r#"
info[goto-type-definition]: Type definition info[goto-type-definition]: Type definition
--> stdlib/types.pyi:922:11 --> stdlib/types.pyi:941:11
| |
920 | if sys.version_info >= (3, 10): 939 | if sys.version_info >= (3, 10):
921 | @final 940 | @final
922 | class NoneType: 941 | class NoneType:
| ^^^^^^^^ | ^^^^^^^^
923 | """The type of the None singleton.""" 942 | """The type of the None singleton."""
| |
info: Source info: Source
--> main.py:3:5 --> main.py:3:5
@ -585,14 +578,13 @@ f(**kwargs<CURSOR>)
| |
info[goto-type-definition]: Type definition info[goto-type-definition]: Type definition
--> stdlib/builtins.pyi:901:7 --> stdlib/builtins.pyi:911:7
| |
899 | def __getitem__(self, key: int, /) -> str | int | None: ... 910 | @disjoint_base
900 | 911 | class str(Sequence[str]):
901 | class str(Sequence[str]):
| ^^^ | ^^^
902 | """str(object='') -> str 912 | """str(object='') -> str
903 | str(bytes_or_buffer[, encoding[, errors]]) -> str 913 | str(bytes_or_buffer[, encoding[, errors]]) -> str
| |
info: Source info: Source
--> main.py:3:5 --> main.py:3:5

View file

@ -91,15 +91,15 @@ error[missing-argument]: No argument provided for required parameter `arg` of bo
7 | from typing_extensions import deprecated 7 | from typing_extensions import deprecated
| |
info: Parameter declared here info: Parameter declared here
--> stdlib/typing_extensions.pyi:973:28 --> stdlib/typing_extensions.pyi:1000:28
| |
971 | stacklevel: int 998 | stacklevel: int
972 | def __init__(self, message: LiteralString, /, *, category: type[Warning] | None = ..., stacklevel: int = 1) -> None: ... 999 | def __init__(self, message: LiteralString, /, *, category: type[Warning] | None = ..., stacklevel: int = 1) -> None: ...
973 | def __call__(self, arg: _T, /) -> _T: ... 1000 | def __call__(self, arg: _T, /) -> _T: ...
| ^^^^^^^ | ^^^^^^^
974 | 1001 |
975 | @final 1002 | @final
| |
info: rule `missing-argument` is enabled by default info: rule `missing-argument` is enabled by default
``` ```

View file

@ -26,14 +26,13 @@ error[invalid-await]: `Literal[1]` is not awaitable
2 | await 1 # error: [invalid-await] 2 | await 1 # error: [invalid-await]
| ^ | ^
| |
::: stdlib/builtins.pyi:337:7 ::: stdlib/builtins.pyi:344:7
| |
335 | _LiteralInteger = _PositiveInteger | _NegativeInteger | Literal[0] # noqa: Y026 # TODO: Use TypeAlias once mypy bugs are fixed 343 | @disjoint_base
336 | 344 | class int:
337 | class int:
| --- type defined here | --- type defined here
338 | """int([x]) -> integer 345 | """int([x]) -> integer
339 | int(x, base=10) -> integer 346 | int(x, base=10) -> integer
| |
info: `__await__` is missing info: `__await__` is missing
info: rule `invalid-await` is enabled by default info: rule `invalid-await` is enabled by default

View file

@ -1409,7 +1409,12 @@ mod implicit_globals {
/// Conceptually this function could be a `Set` rather than a list, /// Conceptually this function could be a `Set` rather than a list,
/// but the number of symbols declared in this scope is likely to be very small, /// but the number of symbols declared in this scope is likely to be very small,
/// so the cost of hashing the names is likely to be more expensive than it's worth. /// so the cost of hashing the names is likely to be more expensive than it's worth.
#[salsa::tracked(returns(deref), heap_size=ruff_memory_usage::heap_size)] #[salsa::tracked(
returns(deref),
cycle_initial=module_type_symbols_initial,
cycle_fn=module_type_symbols_cycle_recover,
heap_size=ruff_memory_usage::heap_size
)]
fn module_type_symbols<'db>(db: &'db dyn Db) -> smallvec::SmallVec<[ast::name::Name; 8]> { fn module_type_symbols<'db>(db: &'db dyn Db) -> smallvec::SmallVec<[ast::name::Name; 8]> {
let Some(module_type) = KnownClass::ModuleType let Some(module_type) = KnownClass::ModuleType
.to_class_literal(db) .to_class_literal(db)
@ -1437,6 +1442,18 @@ mod implicit_globals {
.collect() .collect()
} }
fn module_type_symbols_initial(_db: &dyn Db) -> smallvec::SmallVec<[ast::name::Name; 8]> {
smallvec::SmallVec::default()
}
fn module_type_symbols_cycle_recover(
_db: &dyn Db,
_value: &smallvec::SmallVec<[ast::name::Name; 8]>,
_count: u32,
) -> salsa::CycleRecoveryAction<smallvec::SmallVec<[ast::name::Name; 8]>> {
salsa::CycleRecoveryAction::Iterate
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;

View file

@ -11726,6 +11726,14 @@ mod tests {
fn unbound_symbol_no_reachability_constraint_check() { fn unbound_symbol_no_reachability_constraint_check() {
let mut db = setup_db(); let mut db = setup_db();
// First, type-check a random other file so that we cache a result for the `module_type_symbols`
// query (which often encounters cycles due to `types.pyi` importing `typing_extensions` and
// `typing_extensions.pyi` importing `types`). Clear the events afterwards so that unrelated
// cycles from that query don't interfere with our test.
db.write_dedented("src/wherever.py", "print(x)").unwrap();
assert_file_diagnostics(&db, "src/wherever.py", &["Name `x` used when not defined"]);
db.clear_salsa_events();
// If the bug we are testing for is not fixed, what happens is that when inferring the // If the bug we are testing for is not fixed, what happens is that when inferring the
// `flag: bool = True` definitions, we look up `bool` as a deferred name (thus from end of // `flag: bool = True` definitions, we look up `bool` as a deferred name (thus from end of
// scope), and because of the early return its "unbound" binding has a reachability // scope), and because of the early return its "unbound" binding has a reachability

View file

@ -1 +1 @@
f32d9f08bde8e42a3a35c050839d0275979eb3af 91e2ed0953592795fd8c29e3005a1315bf652ffc

View file

@ -6,12 +6,13 @@ from collections.abc import Awaitable, Callable, Coroutine, Generator
from contextvars import Context from contextvars import Context
from types import FrameType, GenericAlias from types import FrameType, GenericAlias
from typing import Any, Literal, TextIO, TypeVar from typing import Any, Literal, TextIO, TypeVar
from typing_extensions import Self, TypeAlias from typing_extensions import Self, TypeAlias, disjoint_base
_T = TypeVar("_T") _T = TypeVar("_T")
_T_co = TypeVar("_T_co", covariant=True) _T_co = TypeVar("_T_co", covariant=True)
_TaskYieldType: TypeAlias = Future[object] | None _TaskYieldType: TypeAlias = Future[object] | None
@disjoint_base
class Future(Awaitable[_T]): class Future(Awaitable[_T]):
"""This class is *almost* compatible with concurrent.futures.Future. """This class is *almost* compatible with concurrent.futures.Future.
@ -36,7 +37,7 @@ class Future(Awaitable[_T]):
@_log_traceback.setter @_log_traceback.setter
def _log_traceback(self, val: Literal[False]) -> None: ... def _log_traceback(self, val: Literal[False]) -> None: ...
_asyncio_future_blocking: bool # is a part of duck-typing contract for `Future` _asyncio_future_blocking: bool # is a part of duck-typing contract for `Future`
def __init__(self, *, loop: AbstractEventLoop | None = ...) -> None: ... def __init__(self, *, loop: AbstractEventLoop | None = None) -> None: ...
def __del__(self) -> None: def __del__(self) -> None:
"""Called when the instance is about to be destroyed.""" """Called when the instance is about to be destroyed."""
@ -128,6 +129,7 @@ else:
# While this is true in general, here it's sort-of okay to have a covariant subclass, # While this is true in general, here it's sort-of okay to have a covariant subclass,
# since the only reason why `asyncio.Future` is invariant is the `set_result()` method, # since the only reason why `asyncio.Future` is invariant is the `set_result()` method,
# and `asyncio.Task.set_result()` always raises. # and `asyncio.Task.set_result()` always raises.
@disjoint_base
class Task(Future[_T_co]): # type: ignore[type-var] # pyright: ignore[reportInvalidTypeArguments] class Task(Future[_T_co]): # type: ignore[type-var] # pyright: ignore[reportInvalidTypeArguments]
"""A coroutine wrapped in a Future.""" """A coroutine wrapped in a Future."""
@ -137,7 +139,7 @@ class Task(Future[_T_co]): # type: ignore[type-var] # pyright: ignore[reportIn
coro: _TaskCompatibleCoro[_T_co], coro: _TaskCompatibleCoro[_T_co],
*, *,
loop: AbstractEventLoop | None = None, loop: AbstractEventLoop | None = None,
name: str | None = ..., name: str | None = None,
context: Context | None = None, context: Context | None = None,
eager_start: bool = False, eager_start: bool = False,
) -> None: ... ) -> None: ...
@ -147,12 +149,12 @@ class Task(Future[_T_co]): # type: ignore[type-var] # pyright: ignore[reportIn
coro: _TaskCompatibleCoro[_T_co], coro: _TaskCompatibleCoro[_T_co],
*, *,
loop: AbstractEventLoop | None = None, loop: AbstractEventLoop | None = None,
name: str | None = ..., name: str | None = None,
context: Context | None = None, context: Context | None = None,
) -> None: ... ) -> None: ...
else: else:
def __init__( def __init__(
self, coro: _TaskCompatibleCoro[_T_co], *, loop: AbstractEventLoop | None = None, name: str | None = ... self, coro: _TaskCompatibleCoro[_T_co], *, loop: AbstractEventLoop | None = None, name: str | None = None
) -> None: ... ) -> None: ...
if sys.version_info >= (3, 12): if sys.version_info >= (3, 12):

View file

@ -1,5 +1,6 @@
"""_blake2b provides BLAKE2b for hashlib""" """_blake2b provides BLAKE2b for hashlib"""
import sys
from _typeshed import ReadableBuffer from _typeshed import ReadableBuffer
from typing import ClassVar, Final, final from typing import ClassVar, Final, final
from typing_extensions import Self from typing_extensions import Self
@ -24,24 +25,45 @@ class blake2b:
block_size: int block_size: int
digest_size: int digest_size: int
name: str name: str
def __new__( if sys.version_info >= (3, 13):
cls, def __new__(
data: ReadableBuffer = b"", cls,
/, data: ReadableBuffer = b"",
*, *,
digest_size: int = 64, digest_size: int = 64,
key: ReadableBuffer = b"", key: ReadableBuffer = b"",
salt: ReadableBuffer = b"", salt: ReadableBuffer = b"",
person: ReadableBuffer = b"", person: ReadableBuffer = b"",
fanout: int = 1, fanout: int = 1,
depth: int = 1, depth: int = 1,
leaf_size: int = 0, leaf_size: int = 0,
node_offset: int = 0, node_offset: int = 0,
node_depth: int = 0, node_depth: int = 0,
inner_size: int = 0, inner_size: int = 0,
last_node: bool = False, last_node: bool = False,
usedforsecurity: bool = True, usedforsecurity: bool = True,
) -> Self: ... string: ReadableBuffer | None = None,
) -> Self: ...
else:
def __new__(
cls,
data: ReadableBuffer = b"",
/,
*,
digest_size: int = 64,
key: ReadableBuffer = b"",
salt: ReadableBuffer = b"",
person: ReadableBuffer = b"",
fanout: int = 1,
depth: int = 1,
leaf_size: int = 0,
node_offset: int = 0,
node_depth: int = 0,
inner_size: int = 0,
last_node: bool = False,
usedforsecurity: bool = True,
) -> Self: ...
def copy(self) -> Self: def copy(self) -> Self:
"""Return a copy of the hash object.""" """Return a copy of the hash object."""
@ -65,24 +87,45 @@ class blake2s:
block_size: int block_size: int
digest_size: int digest_size: int
name: str name: str
def __new__( if sys.version_info >= (3, 13):
cls, def __new__(
data: ReadableBuffer = b"", cls,
/, data: ReadableBuffer = b"",
*, *,
digest_size: int = 32, digest_size: int = 32,
key: ReadableBuffer = b"", key: ReadableBuffer = b"",
salt: ReadableBuffer = b"", salt: ReadableBuffer = b"",
person: ReadableBuffer = b"", person: ReadableBuffer = b"",
fanout: int = 1, fanout: int = 1,
depth: int = 1, depth: int = 1,
leaf_size: int = 0, leaf_size: int = 0,
node_offset: int = 0, node_offset: int = 0,
node_depth: int = 0, node_depth: int = 0,
inner_size: int = 0, inner_size: int = 0,
last_node: bool = False, last_node: bool = False,
usedforsecurity: bool = True, usedforsecurity: bool = True,
) -> Self: ... string: ReadableBuffer | None = None,
) -> Self: ...
else:
def __new__(
cls,
data: ReadableBuffer = b"",
/,
*,
digest_size: int = 32,
key: ReadableBuffer = b"",
salt: ReadableBuffer = b"",
person: ReadableBuffer = b"",
fanout: int = 1,
depth: int = 1,
leaf_size: int = 0,
node_offset: int = 0,
node_depth: int = 0,
inner_size: int = 0,
last_node: bool = False,
usedforsecurity: bool = True,
) -> Self: ...
def copy(self) -> Self: def copy(self) -> Self:
"""Return a copy of the hash object.""" """Return a copy of the hash object."""

View file

@ -5,7 +5,7 @@ import sys
from _typeshed import SupportsWrite from _typeshed import SupportsWrite
from collections.abc import Iterable from collections.abc import Iterable
from typing import Any, Final, Literal, type_check_only from typing import Any, Final, Literal, type_check_only
from typing_extensions import Self, TypeAlias from typing_extensions import Self, TypeAlias, disjoint_base
__version__: Final[str] __version__: Final[str]
@ -26,6 +26,7 @@ class Error(Exception): ...
_DialectLike: TypeAlias = str | Dialect | csv.Dialect | type[Dialect | csv.Dialect] _DialectLike: TypeAlias = str | Dialect | csv.Dialect | type[Dialect | csv.Dialect]
@disjoint_base
class Dialect: class Dialect:
"""CSV dialect """CSV dialect
@ -42,7 +43,7 @@ class Dialect:
strict: bool strict: bool
def __new__( def __new__(
cls, cls,
dialect: _DialectLike | None = ..., dialect: _DialectLike | None = None,
delimiter: str = ",", delimiter: str = ",",
doublequote: bool = True, doublequote: bool = True,
escapechar: str | None = None, escapechar: str | None = None,
@ -55,6 +56,7 @@ class Dialect:
if sys.version_info >= (3, 10): if sys.version_info >= (3, 10):
# This class calls itself _csv.reader. # This class calls itself _csv.reader.
@disjoint_base
class Reader: class Reader:
"""CSV reader """CSV reader
@ -72,6 +74,7 @@ if sys.version_info >= (3, 10):
"""Implement next(self).""" """Implement next(self)."""
# This class calls itself _csv.writer. # This class calls itself _csv.writer.
@disjoint_base
class Writer: class Writer:
"""CSV writer """CSV writer

View file

@ -573,7 +573,7 @@ def newpad(nlines: int, ncols: int, /) -> window:
Width. Width.
""" """
def newwin(nlines: int, ncols: int, begin_y: int = ..., begin_x: int = ..., /) -> window: def newwin(nlines: int, ncols: int, begin_y: int = 0, begin_x: int = 0, /) -> window:
"""newwin(nlines, ncols, [begin_y=0, begin_x=0]) """newwin(nlines, ncols, [begin_y=0, begin_x=0])
Return a new window. Return a new window.
@ -1016,7 +1016,7 @@ class window: # undocumented
""" """
@overload @overload
def box(self, vertch: _ChType = ..., horch: _ChType = ...) -> None: ... def box(self, vertch: _ChType = 0, horch: _ChType = 0) -> None: ...
@overload @overload
def chgat(self, attr: int) -> None: def chgat(self, attr: int) -> None:
"""chgat([y, x,] [n=-1,] attr) """chgat([y, x,] [n=-1,] attr)
@ -1289,7 +1289,7 @@ class window: # undocumented
@overload @overload
def insstr(self, y: int, x: int, str: str, attr: int = ...) -> None: ... def insstr(self, y: int, x: int, str: str, attr: int = ...) -> None: ...
@overload @overload
def instr(self, n: int = ...) -> bytes: def instr(self, n: int = 2047) -> bytes:
"""instr([y, x,] n=2047) """instr([y, x,] n=2047)
Return a string of characters, extracted from the window. Return a string of characters, extracted from the window.
@ -1307,7 +1307,7 @@ class window: # undocumented
""" """
@overload @overload
def instr(self, y: int, x: int, n: int = ...) -> bytes: ... def instr(self, y: int, x: int, n: int = 2047) -> bytes: ...
def is_linetouched(self, line: int, /) -> bool: def is_linetouched(self, line: int, /) -> bool:
"""Return True if the specified line was modified, otherwise return False. """Return True if the specified line was modified, otherwise return False.
@ -1415,7 +1415,7 @@ class window: # undocumented
@overload @overload
def refresh(self, pminrow: int, pmincol: int, sminrow: int, smincol: int, smaxrow: int, smaxcol: int) -> None: ... def refresh(self, pminrow: int, pmincol: int, sminrow: int, smincol: int, smaxrow: int, smaxcol: int) -> None: ...
def resize(self, nlines: int, ncols: int) -> None: ... def resize(self, nlines: int, ncols: int) -> None: ...
def scroll(self, lines: int = ...) -> None: def scroll(self, lines: int = 1) -> None:
"""scroll([lines=1]) """scroll([lines=1])
Scroll the screen or scrolling region. Scroll the screen or scrolling region.
@ -1483,7 +1483,7 @@ class window: # undocumented
def syncok(self, flag: bool) -> None: ... def syncok(self, flag: bool) -> None: ...
def syncup(self) -> None: ... def syncup(self) -> None: ...
def timeout(self, delay: int) -> None: ... def timeout(self, delay: int) -> None: ...
def touchline(self, start: int, count: int, changed: bool = ...) -> None: def touchline(self, start: int, count: int, changed: bool = True) -> None:
"""touchline(start, count, [changed=True]) """touchline(start, count, [changed=True])
Pretend count lines have been changed, starting with line start. Pretend count lines have been changed, starting with line start.

View file

@ -33,7 +33,7 @@ if sys.platform != "win32":
@overload @overload
def get(self, k: _KeyType, default: _T, /) -> bytes | _T: ... def get(self, k: _KeyType, default: _T, /) -> bytes | _T: ...
def keys(self) -> list[bytes]: ... def keys(self) -> list[bytes]: ...
def setdefault(self, k: _KeyType, default: _ValueType = ..., /) -> bytes: ... def setdefault(self, k: _KeyType, default: _ValueType = b"", /) -> bytes: ...
# This isn't true, but the class can't be instantiated. See #13024 # This isn't true, but the class can't be instantiated. See #13024
__new__: None # type: ignore[assignment] __new__: None # type: ignore[assignment]
__init__: None # type: ignore[assignment] __init__: None # type: ignore[assignment]

View file

@ -56,14 +56,14 @@ if sys.version_info >= (3, 11):
def localcontext( def localcontext(
ctx: Context | None = None, ctx: Context | None = None,
*, *,
prec: int | None = ..., prec: int | None = None,
rounding: str | None = ..., rounding: str | None = None,
Emin: int | None = ..., Emin: int | None = None,
Emax: int | None = ..., Emax: int | None = None,
capitals: int | None = ..., capitals: int | None = None,
clamp: int | None = ..., clamp: int | None = None,
traps: dict[_TrapType, bool] | None = ..., traps: dict[_TrapType, bool] | None = None,
flags: dict[_TrapType, bool] | None = ..., flags: dict[_TrapType, bool] | None = None,
) -> _ContextManager: ) -> _ContextManager:
"""Return a context manager that will set the default context to a copy of ctx """Return a context manager that will set the default context to a copy of ctx
on entry to the with-statement and restore the previous default context when on entry to the with-statement and restore the previous default context when

View file

@ -5,7 +5,7 @@ from _typeshed import ReadableBuffer
from collections.abc import Callable from collections.abc import Callable
from types import ModuleType from types import ModuleType
from typing import AnyStr, Protocol, final, overload, type_check_only from typing import AnyStr, Protocol, final, overload, type_check_only
from typing_extensions import Self, TypeAlias from typing_extensions import Self, TypeAlias, disjoint_base
_DigestMod: TypeAlias = str | Callable[[], _HashObject] | ModuleType | None _DigestMod: TypeAlias = str | Callable[[], _HashObject] | ModuleType | None
@ -24,6 +24,7 @@ class _HashObject(Protocol):
def hexdigest(self) -> str: ... def hexdigest(self) -> str: ...
def update(self, obj: ReadableBuffer, /) -> None: ... def update(self, obj: ReadableBuffer, /) -> None: ...
@disjoint_base
class HASH: class HASH:
"""A hash is an object used to calculate a checksum of a string of information. """A hash is an object used to calculate a checksum of a string of information.

View file

@ -5,7 +5,7 @@ The 'interpreters' module provides a more convenient interface.
import types import types
from collections.abc import Callable from collections.abc import Callable
from typing import Any, Final, Literal, SupportsIndex, TypeVar, overload from typing import Any, Final, Literal, SupportsIndex, TypeVar, overload
from typing_extensions import TypeAlias from typing_extensions import TypeAlias, disjoint_base
_R = TypeVar("_R") _R = TypeVar("_R")
@ -20,6 +20,7 @@ class InterpreterNotFoundError(InterpreterError):
class NotShareableError(ValueError): ... class NotShareableError(ValueError): ...
@disjoint_base
class CrossInterpreterBufferView: class CrossInterpreterBufferView:
def __buffer__(self, flags: int, /) -> memoryview: def __buffer__(self, flags: int, /) -> memoryview:
"""Return a buffer object that exposes the underlying memory of the object.""" """Return a buffer object that exposes the underlying memory of the object."""

View file

@ -41,11 +41,14 @@ from io import BufferedIOBase, RawIOBase, TextIOBase, UnsupportedOperation as Un
from os import _Opener from os import _Opener
from types import TracebackType from types import TracebackType
from typing import IO, Any, BinaryIO, Final, Generic, Literal, Protocol, TextIO, TypeVar, overload, type_check_only from typing import IO, Any, BinaryIO, Final, Generic, Literal, Protocol, TextIO, TypeVar, overload, type_check_only
from typing_extensions import Self from typing_extensions import Self, disjoint_base
_T = TypeVar("_T") _T = TypeVar("_T")
DEFAULT_BUFFER_SIZE: Final = 8192 if sys.version_info >= (3, 14):
DEFAULT_BUFFER_SIZE: Final = 131072
else:
DEFAULT_BUFFER_SIZE: Final = 8192
open = builtins.open open = builtins.open
@ -58,150 +61,296 @@ def open_code(path: str) -> IO[bytes]:
BlockingIOError = builtins.BlockingIOError BlockingIOError = builtins.BlockingIOError
class _IOBase: if sys.version_info >= (3, 12):
"""The abstract base class for all I/O classes. @disjoint_base
class _IOBase:
"""The abstract base class for all I/O classes.
This class provides dummy implementations for many methods that This class provides dummy implementations for many methods that
derived classes can override selectively; the default implementations derived classes can override selectively; the default implementations
represent a file that cannot be read, written or seeked. represent a file that cannot be read, written or seeked.
Even though IOBase does not declare read, readinto, or write because Even though IOBase does not declare read, readinto, or write because
their signatures will vary, implementations and clients should their signatures will vary, implementations and clients should
consider those methods part of the interface. Also, implementations consider those methods part of the interface. Also, implementations
may raise UnsupportedOperation when operations they do not support are may raise UnsupportedOperation when operations they do not support are
called. called.
The basic type used for binary data read from or written to a file is The basic type used for binary data read from or written to a file is
bytes. Other bytes-like objects are accepted as method arguments too. bytes. Other bytes-like objects are accepted as method arguments too.
In some cases (such as readinto), a writable object is required. Text In some cases (such as readinto), a writable object is required. Text
I/O classes work with str data. I/O classes work with str data.
Note that calling any method (except additional calls to close(), Note that calling any method (except additional calls to close(),
which are ignored) on a closed stream should raise a ValueError. which are ignored) on a closed stream should raise a ValueError.
IOBase (and its subclasses) support the iterator protocol, meaning IOBase (and its subclasses) support the iterator protocol, meaning
that an IOBase object can be iterated over yielding the lines in a that an IOBase object can be iterated over yielding the lines in a
stream. stream.
IOBase also supports the :keyword:`with` statement. In this example, IOBase also supports the :keyword:`with` statement. In this example,
fp is closed after the suite of the with statement is complete: fp is closed after the suite of the with statement is complete:
with open('spam.txt', 'r') as fp: with open('spam.txt', 'r') as fp:
fp.write('Spam and eggs!') fp.write('Spam and eggs!')
"""
def __iter__(self) -> Iterator[bytes]:
"""Implement iter(self)."""
def __next__(self) -> bytes:
"""Implement next(self)."""
def __enter__(self) -> Self: ...
def __exit__(
self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None
) -> None: ...
def close(self) -> None:
"""Flush and close the IO object.
This method has no effect if the file is already closed.
""" """
def fileno(self) -> int: def __iter__(self) -> Iterator[bytes]:
"""Return underlying file descriptor if one exists. """Implement iter(self)."""
Raise OSError if the IO object does not use a file descriptor. def __next__(self) -> bytes:
"""Implement next(self)."""
def __enter__(self) -> Self: ...
def __exit__(
self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None
) -> None: ...
def close(self) -> None:
"""Flush and close the IO object.
This method has no effect if the file is already closed.
"""
def fileno(self) -> int:
"""Return underlying file descriptor if one exists.
Raise OSError if the IO object does not use a file descriptor.
"""
def flush(self) -> None:
"""Flush write buffers, if applicable.
This is not implemented for read-only and non-blocking streams.
"""
def isatty(self) -> bool:
"""Return whether this is an 'interactive' stream.
Return False if it can't be determined.
"""
def readable(self) -> bool:
"""Return whether object was opened for reading.
If False, read() will raise OSError.
"""
read: Callable[..., Any]
def readlines(self, hint: int = -1, /) -> list[bytes]:
"""Return a list of lines from the stream.
hint can be specified to control the number of lines read: no more
lines will be read if the total size (in bytes/characters) of all
lines so far exceeds hint.
"""
def seek(self, offset: int, whence: int = 0, /) -> int:
"""Change the stream position to the given byte offset.
offset
The stream position, relative to 'whence'.
whence
The relative position to seek from.
The offset is interpreted relative to the position indicated by whence.
Values for whence are:
* os.SEEK_SET or 0 -- start of stream (the default); offset should be zero or positive
* os.SEEK_CUR or 1 -- current stream position; offset may be negative
* os.SEEK_END or 2 -- end of stream; offset is usually negative
Return the new absolute position.
"""
def seekable(self) -> bool:
"""Return whether object supports random access.
If False, seek(), tell() and truncate() will raise OSError.
This method may need to do a test seek().
"""
def tell(self) -> int:
"""Return current stream position."""
def truncate(self, size: int | None = None, /) -> int:
"""Truncate file to size bytes.
File pointer is left unchanged. Size defaults to the current IO position
as reported by tell(). Return the new size.
"""
def writable(self) -> bool:
"""Return whether object was opened for writing.
If False, write() will raise OSError.
"""
write: Callable[..., Any]
def writelines(self, lines: Iterable[ReadableBuffer], /) -> None:
"""Write a list of lines to stream.
Line separators are not added, so it is usual for each of the
lines provided to have a line separator at the end.
"""
def readline(self, size: int | None = -1, /) -> bytes:
"""Read and return a line from the stream.
If size is specified, at most size bytes will be read.
The line terminator is always b'\\n' for binary files; for text
files, the newlines argument to open can be used to select the line
terminator(s) recognized.
"""
def __del__(self) -> None:
"""Called when the instance is about to be destroyed."""
@property
def closed(self) -> bool: ...
def _checkClosed(self) -> None: ... # undocumented
else:
class _IOBase:
"""The abstract base class for all I/O classes.
This class provides dummy implementations for many methods that
derived classes can override selectively; the default implementations
represent a file that cannot be read, written or seeked.
Even though IOBase does not declare read, readinto, or write because
their signatures will vary, implementations and clients should
consider those methods part of the interface. Also, implementations
may raise UnsupportedOperation when operations they do not support are
called.
The basic type used for binary data read from or written to a file is
bytes. Other bytes-like objects are accepted as method arguments too.
In some cases (such as readinto), a writable object is required. Text
I/O classes work with str data.
Note that calling any method (except additional calls to close(),
which are ignored) on a closed stream should raise a ValueError.
IOBase (and its subclasses) support the iterator protocol, meaning
that an IOBase object can be iterated over yielding the lines in a
stream.
IOBase also supports the :keyword:`with` statement. In this example,
fp is closed after the suite of the with statement is complete:
with open('spam.txt', 'r') as fp:
fp.write('Spam and eggs!')
""" """
def flush(self) -> None: def __iter__(self) -> Iterator[bytes]:
"""Flush write buffers, if applicable. """Implement iter(self)."""
This is not implemented for read-only and non-blocking streams. def __next__(self) -> bytes:
""" """Implement next(self)."""
def isatty(self) -> bool: def __enter__(self) -> Self: ...
"""Return whether this is an 'interactive' stream. def __exit__(
self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None
) -> None: ...
def close(self) -> None:
"""Flush and close the IO object.
Return False if it can't be determined. This method has no effect if the file is already closed.
""" """
def readable(self) -> bool: def fileno(self) -> int:
"""Return whether object was opened for reading. """Returns underlying file descriptor if one exists.
If False, read() will raise OSError. OSError is raised if the IO object does not use a file descriptor.
""" """
read: Callable[..., Any]
def readlines(self, hint: int = -1, /) -> list[bytes]:
"""Return a list of lines from the stream.
hint can be specified to control the number of lines read: no more def flush(self) -> None:
lines will be read if the total size (in bytes/characters) of all """Flush write buffers, if applicable.
lines so far exceeds hint.
"""
def seek(self, offset: int, whence: int = 0, /) -> int: This is not implemented for read-only and non-blocking streams.
"""Change the stream position to the given byte offset. """
offset def isatty(self) -> bool:
The stream position, relative to 'whence'. """Return whether this is an 'interactive' stream.
whence
The relative position to seek from.
The offset is interpreted relative to the position indicated by whence. Return False if it can't be determined.
Values for whence are: """
* os.SEEK_SET or 0 -- start of stream (the default); offset should be zero or positive def readable(self) -> bool:
* os.SEEK_CUR or 1 -- current stream position; offset may be negative """Return whether object was opened for reading.
* os.SEEK_END or 2 -- end of stream; offset is usually negative
Return the new absolute position. If False, read() will raise OSError.
""" """
read: Callable[..., Any]
def readlines(self, hint: int = -1, /) -> list[bytes]:
"""Return a list of lines from the stream.
def seekable(self) -> bool: hint can be specified to control the number of lines read: no more
"""Return whether object supports random access. lines will be read if the total size (in bytes/characters) of all
lines so far exceeds hint.
"""
If False, seek(), tell() and truncate() will raise OSError. def seek(self, offset: int, whence: int = 0, /) -> int:
This method may need to do a test seek(). """Change the stream position to the given byte offset.
"""
def tell(self) -> int: offset
"""Return current stream position.""" The stream position, relative to 'whence'.
whence
The relative position to seek from.
def truncate(self, size: int | None = None, /) -> int: The offset is interpreted relative to the position indicated by whence.
"""Truncate file to size bytes. Values for whence are:
File pointer is left unchanged. Size defaults to the current IO position * os.SEEK_SET or 0 -- start of stream (the default); offset should be zero or positive
as reported by tell(). Return the new size. * os.SEEK_CUR or 1 -- current stream position; offset may be negative
""" * os.SEEK_END or 2 -- end of stream; offset is usually negative
def writable(self) -> bool: Return the new absolute position.
"""Return whether object was opened for writing. """
If False, write() will raise OSError. def seekable(self) -> bool:
""" """Return whether object supports random access.
write: Callable[..., Any]
def writelines(self, lines: Iterable[ReadableBuffer], /) -> None:
"""Write a list of lines to stream.
Line separators are not added, so it is usual for each of the If False, seek(), tell() and truncate() will raise OSError.
lines provided to have a line separator at the end. This method may need to do a test seek().
""" """
def readline(self, size: int | None = -1, /) -> bytes: def tell(self) -> int:
"""Read and return a line from the stream. """Return current stream position."""
If size is specified, at most size bytes will be read. def truncate(self, size: int | None = None, /) -> int:
"""Truncate file to size bytes.
The line terminator is always b'\\n' for binary files; for text File pointer is left unchanged. Size defaults to the current IO
files, the newlines argument to open can be used to select the line position as reported by tell(). Returns the new size.
terminator(s) recognized. """
"""
def __del__(self) -> None: def writable(self) -> bool:
"""Called when the instance is about to be destroyed.""" """Return whether object was opened for writing.
@property If False, write() will raise OSError.
def closed(self) -> bool: ... """
def _checkClosed(self) -> None: ... # undocumented write: Callable[..., Any]
def writelines(self, lines: Iterable[ReadableBuffer], /) -> None:
"""Write a list of lines to stream.
Line separators are not added, so it is usual for each of the
lines provided to have a line separator at the end.
"""
def readline(self, size: int | None = -1, /) -> bytes:
"""Read and return a line from the stream.
If size is specified, at most size bytes will be read.
The line terminator is always b'\\n' for binary files; for text
files, the newlines argument to open can be used to select the line
terminator(s) recognized.
"""
def __del__(self) -> None: ...
@property
def closed(self) -> bool: ...
def _checkClosed(self) -> None: ... # undocumented
class _RawIOBase(_IOBase): class _RawIOBase(_IOBase):
"""Base class for raw binary I/O.""" """Base class for raw binary I/O."""
@ -275,6 +424,7 @@ class _BufferedIOBase(_IOBase):
A short result does not imply that EOF is imminent. A short result does not imply that EOF is imminent.
""" """
@disjoint_base
class FileIO(RawIOBase, _RawIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of writelines in the base classes class FileIO(RawIOBase, _RawIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of writelines in the base classes
"""Open a file. """Open a file.
@ -328,6 +478,7 @@ class FileIO(RawIOBase, _RawIOBase, BinaryIO): # type: ignore[misc] # incompat
bytes object at EOF. bytes object at EOF.
""" """
@disjoint_base
class BytesIO(BufferedIOBase, _BufferedIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of methods in the base classes class BytesIO(BufferedIOBase, _BufferedIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of methods in the base classes
"""Buffered I/O implementation using an in-memory bytes buffer.""" """Buffered I/O implementation using an in-memory bytes buffer."""
@ -395,15 +546,21 @@ class _BufferedReaderStream(Protocol):
_BufferedReaderStreamT = TypeVar("_BufferedReaderStreamT", bound=_BufferedReaderStream, default=_BufferedReaderStream) _BufferedReaderStreamT = TypeVar("_BufferedReaderStreamT", bound=_BufferedReaderStream, default=_BufferedReaderStream)
@disjoint_base
class BufferedReader(BufferedIOBase, _BufferedIOBase, BinaryIO, Generic[_BufferedReaderStreamT]): # type: ignore[misc] # incompatible definitions of methods in the base classes class BufferedReader(BufferedIOBase, _BufferedIOBase, BinaryIO, Generic[_BufferedReaderStreamT]): # type: ignore[misc] # incompatible definitions of methods in the base classes
"""Create a new buffered reader using the given readable raw IO object.""" """Create a new buffered reader using the given readable raw IO object."""
raw: _BufferedReaderStreamT raw: _BufferedReaderStreamT
def __init__(self, raw: _BufferedReaderStreamT, buffer_size: int = 8192) -> None: ... if sys.version_info >= (3, 14):
def __init__(self, raw: _BufferedReaderStreamT, buffer_size: int = 131072) -> None: ...
else:
def __init__(self, raw: _BufferedReaderStreamT, buffer_size: int = 8192) -> None: ...
def peek(self, size: int = 0, /) -> bytes: ... def peek(self, size: int = 0, /) -> bytes: ...
def seek(self, target: int, whence: int = 0, /) -> int: ... def seek(self, target: int, whence: int = 0, /) -> int: ...
def truncate(self, pos: int | None = None, /) -> int: ... def truncate(self, pos: int | None = None, /) -> int: ...
@disjoint_base
class BufferedWriter(BufferedIOBase, _BufferedIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of writelines in the base classes class BufferedWriter(BufferedIOBase, _BufferedIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of writelines in the base classes
"""A buffer for a writeable sequential RawIO object. """A buffer for a writeable sequential RawIO object.
@ -413,11 +570,16 @@ class BufferedWriter(BufferedIOBase, _BufferedIOBase, BinaryIO): # type: ignore
""" """
raw: RawIOBase raw: RawIOBase
def __init__(self, raw: RawIOBase, buffer_size: int = 8192) -> None: ... if sys.version_info >= (3, 14):
def __init__(self, raw: RawIOBase, buffer_size: int = 131072) -> None: ...
else:
def __init__(self, raw: RawIOBase, buffer_size: int = 8192) -> None: ...
def write(self, buffer: ReadableBuffer, /) -> int: ... def write(self, buffer: ReadableBuffer, /) -> int: ...
def seek(self, target: int, whence: int = 0, /) -> int: ... def seek(self, target: int, whence: int = 0, /) -> int: ...
def truncate(self, pos: int | None = None, /) -> int: ... def truncate(self, pos: int | None = None, /) -> int: ...
@disjoint_base
class BufferedRandom(BufferedIOBase, _BufferedIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of methods in the base classes class BufferedRandom(BufferedIOBase, _BufferedIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of methods in the base classes
"""A buffered interface to random access streams. """A buffered interface to random access streams.
@ -429,11 +591,16 @@ class BufferedRandom(BufferedIOBase, _BufferedIOBase, BinaryIO): # type: ignore
mode: str mode: str
name: Any name: Any
raw: RawIOBase raw: RawIOBase
def __init__(self, raw: RawIOBase, buffer_size: int = 8192) -> None: ... if sys.version_info >= (3, 14):
def __init__(self, raw: RawIOBase, buffer_size: int = 131072) -> None: ...
else:
def __init__(self, raw: RawIOBase, buffer_size: int = 8192) -> None: ...
def seek(self, target: int, whence: int = 0, /) -> int: ... # stubtest needs this def seek(self, target: int, whence: int = 0, /) -> int: ... # stubtest needs this
def peek(self, size: int = 0, /) -> bytes: ... def peek(self, size: int = 0, /) -> bytes: ...
def truncate(self, pos: int | None = None, /) -> int: ... def truncate(self, pos: int | None = None, /) -> int: ...
@disjoint_base
class BufferedRWPair(BufferedIOBase, _BufferedIOBase, Generic[_BufferedReaderStreamT]): class BufferedRWPair(BufferedIOBase, _BufferedIOBase, Generic[_BufferedReaderStreamT]):
"""A buffered reader and writer object together. """A buffered reader and writer object together.
@ -446,7 +613,11 @@ class BufferedRWPair(BufferedIOBase, _BufferedIOBase, Generic[_BufferedReaderStr
DEFAULT_BUFFER_SIZE. DEFAULT_BUFFER_SIZE.
""" """
def __init__(self, reader: _BufferedReaderStreamT, writer: RawIOBase, buffer_size: int = 8192, /) -> None: ... if sys.version_info >= (3, 14):
def __init__(self, reader: _BufferedReaderStreamT, writer: RawIOBase, buffer_size: int = 131072, /) -> None: ...
else:
def __init__(self, reader: _BufferedReaderStreamT, writer: RawIOBase, buffer_size: int = 8192, /) -> None: ...
def peek(self, size: int = 0, /) -> bytes: ... def peek(self, size: int = 0, /) -> bytes: ...
class _TextIOBase(_IOBase): class _TextIOBase(_IOBase):
@ -533,6 +704,7 @@ class _WrappedBuffer(Protocol):
_BufferT_co = TypeVar("_BufferT_co", bound=_WrappedBuffer, default=_WrappedBuffer, covariant=True) _BufferT_co = TypeVar("_BufferT_co", bound=_WrappedBuffer, default=_WrappedBuffer, covariant=True)
@disjoint_base
class TextIOWrapper(TextIOBase, _TextIOBase, TextIO, Generic[_BufferT_co]): # type: ignore[misc] # incompatible definitions of write in the base classes class TextIOWrapper(TextIOBase, _TextIOBase, TextIO, Generic[_BufferT_co]): # type: ignore[misc] # incompatible definitions of write in the base classes
"""Character and line based layer over a BufferedIOBase object, buffer. """Character and line based layer over a BufferedIOBase object, buffer.
@ -622,6 +794,7 @@ class TextIOWrapper(TextIOBase, _TextIOBase, TextIO, Generic[_BufferT_co]): # t
def truncate(self, pos: int | None = None, /) -> int: ... def truncate(self, pos: int | None = None, /) -> int: ...
@disjoint_base
class StringIO(TextIOBase, _TextIOBase, TextIO): # type: ignore[misc] # incompatible definitions of write in the base classes class StringIO(TextIOBase, _TextIOBase, TextIO): # type: ignore[misc] # incompatible definitions of write in the base classes
"""Text I/O implementation using an in-memory buffer. """Text I/O implementation using an in-memory buffer.
@ -657,6 +830,7 @@ class StringIO(TextIOBase, _TextIOBase, TextIO): # type: ignore[misc] # incomp
Returns the new absolute position. Returns the new absolute position.
""" """
@disjoint_base
class IncrementalNewlineDecoder: class IncrementalNewlineDecoder:
"""Codec used when reading a file in universal newlines mode. """Codec used when reading a file in universal newlines mode.

View file

@ -5,7 +5,9 @@ from _typeshed import structseq
from collections.abc import Callable from collections.abc import Callable
from types import CodeType from types import CodeType
from typing import Any, Final, final from typing import Any, Final, final
from typing_extensions import disjoint_base
@disjoint_base
class Profiler: class Profiler:
"""Build a profiler object using the specified timer function. """Build a profiler object using the specified timer function.

View file

@ -58,9 +58,9 @@ class LZMADecompressor:
""" """
if sys.version_info >= (3, 12): if sys.version_info >= (3, 12):
def __new__(cls, format: int | None = ..., memlimit: int | None = ..., filters: _FilterChain | None = ...) -> Self: ... def __new__(cls, format: int = 0, memlimit: int | None = None, filters: _FilterChain | None = None) -> Self: ...
else: else:
def __init__(self, format: int | None = ..., memlimit: int | None = ..., filters: _FilterChain | None = ...) -> None: ... def __init__(self, format: int = 0, memlimit: int | None = None, filters: _FilterChain | None = None) -> None: ...
def decompress(self, data: ReadableBuffer, max_length: int = -1) -> bytes: def decompress(self, data: ReadableBuffer, max_length: int = -1) -> bytes:
"""Decompress *data*, returning uncompressed data as bytes. """Decompress *data*, returning uncompressed data as bytes.
@ -127,11 +127,11 @@ class LZMACompressor:
if sys.version_info >= (3, 12): if sys.version_info >= (3, 12):
def __new__( def __new__(
cls, format: int | None = ..., check: int = ..., preset: int | None = ..., filters: _FilterChain | None = ... cls, format: int = 1, check: int = -1, preset: int | None = None, filters: _FilterChain | None = None
) -> Self: ... ) -> Self: ...
else: else:
def __init__( def __init__(
self, format: int | None = ..., check: int = ..., preset: int | None = ..., filters: _FilterChain | None = ... self, format: int = 1, check: int = -1, preset: int | None = None, filters: _FilterChain | None = None
) -> None: ... ) -> None: ...
def compress(self, data: ReadableBuffer, /) -> bytes: def compress(self, data: ReadableBuffer, /) -> bytes:

View file

@ -2,6 +2,7 @@ from _typeshed import ReadableBuffer
from codecs import _ReadableStream, _WritableStream from codecs import _ReadableStream, _WritableStream
from collections.abc import Iterable from collections.abc import Iterable
from typing import final, type_check_only from typing import final, type_check_only
from typing_extensions import disjoint_base
# This class is not exposed. It calls itself _multibytecodec.MultibyteCodec. # This class is not exposed. It calls itself _multibytecodec.MultibyteCodec.
@final @final
@ -10,6 +11,7 @@ class _MultibyteCodec:
def decode(self, input: ReadableBuffer, errors: str | None = None) -> str: ... def decode(self, input: ReadableBuffer, errors: str | None = None) -> str: ...
def encode(self, input: str, errors: str | None = None) -> bytes: ... def encode(self, input: str, errors: str | None = None) -> bytes: ...
@disjoint_base
class MultibyteIncrementalDecoder: class MultibyteIncrementalDecoder:
errors: str errors: str
def __init__(self, errors: str = "strict") -> None: ... def __init__(self, errors: str = "strict") -> None: ...
@ -18,6 +20,7 @@ class MultibyteIncrementalDecoder:
def reset(self) -> None: ... def reset(self) -> None: ...
def setstate(self, state: tuple[bytes, int], /) -> None: ... def setstate(self, state: tuple[bytes, int], /) -> None: ...
@disjoint_base
class MultibyteIncrementalEncoder: class MultibyteIncrementalEncoder:
errors: str errors: str
def __init__(self, errors: str = "strict") -> None: ... def __init__(self, errors: str = "strict") -> None: ...
@ -26,6 +29,7 @@ class MultibyteIncrementalEncoder:
def reset(self) -> None: ... def reset(self) -> None: ...
def setstate(self, state: int, /) -> None: ... def setstate(self, state: int, /) -> None: ...
@disjoint_base
class MultibyteStreamReader: class MultibyteStreamReader:
errors: str errors: str
stream: _ReadableStream stream: _ReadableStream
@ -35,6 +39,7 @@ class MultibyteStreamReader:
def readlines(self, sizehintobj: int | None = None, /) -> list[str]: ... def readlines(self, sizehintobj: int | None = None, /) -> list[str]: ...
def reset(self) -> None: ... def reset(self) -> None: ...
@disjoint_base
class MultibyteStreamWriter: class MultibyteStreamWriter:
errors: str errors: str
stream: _WritableStream stream: _WritableStream

View file

@ -4,7 +4,7 @@ from _typeshed import ReadableBuffer, SupportsWrite
from collections.abc import Callable, Iterable, Iterator, Mapping from collections.abc import Callable, Iterable, Iterator, Mapping
from pickle import PickleBuffer as PickleBuffer from pickle import PickleBuffer as PickleBuffer
from typing import Any, Protocol, type_check_only from typing import Any, Protocol, type_check_only
from typing_extensions import TypeAlias from typing_extensions import TypeAlias, disjoint_base
@type_check_only @type_check_only
class _ReadableFileobj(Protocol): class _ReadableFileobj(Protocol):
@ -145,6 +145,7 @@ class PicklerMemoProxy:
def clear(self, /) -> None: ... def clear(self, /) -> None: ...
def copy(self, /) -> dict[int, tuple[int, Any]]: ... def copy(self, /) -> dict[int, tuple[int, Any]]: ...
@disjoint_base
class Pickler: class Pickler:
"""This takes a binary file for writing a pickle data stream. """This takes a binary file for writing a pickle data stream.
@ -212,6 +213,7 @@ class UnpicklerMemoProxy:
def clear(self, /) -> None: ... def clear(self, /) -> None: ...
def copy(self, /) -> dict[int, tuple[int, Any]]: ... def copy(self, /) -> dict[int, tuple[int, Any]]: ...
@disjoint_base
class Unpickler: class Unpickler:
"""This takes a binary file for reading a pickle data stream. """This takes a binary file for reading a pickle data stream.

View file

@ -4,12 +4,14 @@ This module is an implementation detail, please do not use it directly.
from types import GenericAlias from types import GenericAlias
from typing import Any, Generic, TypeVar from typing import Any, Generic, TypeVar
from typing_extensions import disjoint_base
_T = TypeVar("_T") _T = TypeVar("_T")
class Empty(Exception): class Empty(Exception):
"""Exception raised by Queue.get(block=0)/get_nowait().""" """Exception raised by Queue.get(block=0)/get_nowait()."""
@disjoint_base
class SimpleQueue(Generic[_T]): class SimpleQueue(Generic[_T]):
"""Simple, unbounded, reentrant FIFO queue.""" """Simple, unbounded, reentrant FIFO queue."""

View file

@ -1,14 +1,20 @@
"""Module implements the Mersenne Twister random number generator.""" """Module implements the Mersenne Twister random number generator."""
from typing_extensions import TypeAlias import sys
from typing_extensions import Self, TypeAlias, disjoint_base
# Actually Tuple[(int,) * 625] # Actually Tuple[(int,) * 625]
_State: TypeAlias = tuple[int, ...] _State: TypeAlias = tuple[int, ...]
@disjoint_base
class Random: class Random:
"""Random() -> create a random number generator with its own internal state.""" """Random() -> create a random number generator with its own internal state."""
def __init__(self, seed: object = ...) -> None: ... if sys.version_info >= (3, 10):
def __init__(self, seed: object = ..., /) -> None: ...
else:
def __new__(self, seed: object = ..., /) -> Self: ...
def seed(self, n: object = None, /) -> None: def seed(self, n: object = None, /) -> None:
"""seed([n]) -> None. """seed([n]) -> None.

View file

@ -8,7 +8,7 @@ from _typeshed import ReadableBuffer, WriteableBuffer
from collections.abc import Iterable from collections.abc import Iterable
from socket import error as error, gaierror as gaierror, herror as herror, timeout as timeout from socket import error as error, gaierror as gaierror, herror as herror, timeout as timeout
from typing import Any, Final, SupportsIndex, overload from typing import Any, Final, SupportsIndex, overload
from typing_extensions import CapsuleType, TypeAlias from typing_extensions import CapsuleType, TypeAlias, disjoint_base
_CMSG: TypeAlias = tuple[int, int, bytes] _CMSG: TypeAlias = tuple[int, int, bytes]
_CMSGArg: TypeAlias = tuple[int, int, ReadableBuffer] _CMSGArg: TypeAlias = tuple[int, int, ReadableBuffer]
@ -736,6 +736,7 @@ if sys.platform != "win32" and sys.platform != "darwin":
# ===== Classes ===== # ===== Classes =====
@disjoint_base
class socket: class socket:
"""socket(family=AF_INET, type=SOCK_STREAM, proto=0) -> socket object """socket(family=AF_INET, type=SOCK_STREAM, proto=0) -> socket object
socket(family=-1, type=-1, proto=-1, fileno=None) -> socket object socket(family=-1, type=-1, proto=-1, fileno=None) -> socket object

View file

@ -17,7 +17,7 @@ from ssl import (
SSLZeroReturnError as SSLZeroReturnError, SSLZeroReturnError as SSLZeroReturnError,
) )
from typing import Any, ClassVar, Final, Literal, TypedDict, final, overload, type_check_only from typing import Any, ClassVar, Final, Literal, TypedDict, final, overload, type_check_only
from typing_extensions import NotRequired, Self, TypeAlias, deprecated from typing_extensions import NotRequired, Self, TypeAlias, deprecated, disjoint_base
_PasswordType: TypeAlias = Callable[[], str | bytes | bytearray] | str | bytes | bytearray _PasswordType: TypeAlias = Callable[[], str | bytes | bytearray] | str | bytes | bytearray
_PCTRTT: TypeAlias = tuple[tuple[str, str], ...] _PCTRTT: TypeAlias = tuple[tuple[str, str], ...]
@ -117,6 +117,7 @@ def txt2obj(txt: str, name: bool = False) -> tuple[int, str, str, str]:
def nid2obj(nid: int, /) -> tuple[int, str, str, str]: def nid2obj(nid: int, /) -> tuple[int, str, str, str]:
"""Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.""" """Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID."""
@disjoint_base
class _SSLContext: class _SSLContext:
check_hostname: bool check_hostname: bool
keylog_filename: str | None keylog_filename: str | None

View file

@ -31,6 +31,7 @@ The variable struct.error is an exception raised on errors.
from _typeshed import ReadableBuffer, WriteableBuffer from _typeshed import ReadableBuffer, WriteableBuffer
from collections.abc import Iterator from collections.abc import Iterator
from typing import Any from typing import Any
from typing_extensions import disjoint_base
def pack(fmt: str | bytes, /, *v: Any) -> bytes: def pack(fmt: str | bytes, /, *v: Any) -> bytes:
"""pack(format, v1, v2, ...) -> bytes """pack(format, v1, v2, ...) -> bytes
@ -76,6 +77,7 @@ def iter_unpack(format: str | bytes, buffer: ReadableBuffer, /) -> Iterator[tupl
def calcsize(format: str | bytes, /) -> int: def calcsize(format: str | bytes, /) -> int:
"""Return size in bytes of the struct described by the format string.""" """Return size in bytes of the struct described by the format string."""
@disjoint_base
class Struct: class Struct:
"""Struct(fmt) --> compiled struct object""" """Struct(fmt) --> compiled struct object"""

View file

@ -9,7 +9,7 @@ from collections.abc import Callable
from threading import Thread from threading import Thread
from types import TracebackType from types import TracebackType
from typing import Any, Final, NoReturn, final, overload from typing import Any, Final, NoReturn, final, overload
from typing_extensions import TypeVarTuple, Unpack from typing_extensions import TypeVarTuple, Unpack, disjoint_base
_Ts = TypeVarTuple("_Ts") _Ts = TypeVarTuple("_Ts")
@ -361,6 +361,7 @@ if sys.version_info >= (3, 14):
def set_name(name: str) -> None: def set_name(name: str) -> None:
"""Set the name of the current thread.""" """Set the name of the current thread."""
@disjoint_base
class _local: class _local:
"""Thread-local data""" """Thread-local data"""

View file

@ -54,7 +54,8 @@ Unused: TypeAlias = object # stable
# Marker for return types that include None, but where forcing the user to # Marker for return types that include None, but where forcing the user to
# check for None can be detrimental. Sometimes called "the Any trick". See # check for None can be detrimental. Sometimes called "the Any trick". See
# CONTRIBUTING.md for more information. # https://typing.python.org/en/latest/guides/writing_stubs.html#the-any-trick
# for more information.
MaybeNone: TypeAlias = Any # stable MaybeNone: TypeAlias = Any # stable
# Used to mark arguments that default to a sentinel value. This prevents # Used to mark arguments that default to a sentinel value. This prevents

View file

@ -60,9 +60,9 @@ def warn_explicit(
filename: str, filename: str,
lineno: int, lineno: int,
module: str | None = ..., module: str | None = ...,
registry: dict[str | tuple[str, type[Warning], int], int] | None = ..., registry: dict[str | tuple[str, type[Warning], int], int] | None = None,
module_globals: dict[str, Any] | None = ..., module_globals: dict[str, Any] | None = None,
source: Any | None = ..., source: Any | None = None,
) -> None: ) -> None:
"""Issue a warning, or maybe ignore it or raise an exception.""" """Issue a warning, or maybe ignore it or raise an exception."""
@ -72,8 +72,8 @@ def warn_explicit(
category: Any, category: Any,
filename: str, filename: str,
lineno: int, lineno: int,
module: str | None = ..., module: str | None = None,
registry: dict[str | tuple[str, type[Warning], int], int] | None = ..., registry: dict[str | tuple[str, type[Warning], int], int] | None = None,
module_globals: dict[str, Any] | None = ..., module_globals: dict[str, Any] | None = None,
source: Any | None = ..., source: Any | None = None,
) -> None: ... ) -> None: ...

View file

@ -60,9 +60,9 @@ class ZstdCompressor:
CONTINUE: Final = 0 CONTINUE: Final = 0
FLUSH_BLOCK: Final = 1 FLUSH_BLOCK: Final = 1
FLUSH_FRAME: Final = 2 FLUSH_FRAME: Final = 2
def __init__( def __new__(
self, level: int | None = None, options: Mapping[int, int] | None = None, zstd_dict: ZstdDict | None = None cls, level: int | None = None, options: Mapping[int, int] | None = None, zstd_dict: ZstdDict | None = None
) -> None: ... ) -> Self: ...
def compress( def compress(
self, /, data: ReadableBuffer, mode: _ZstdCompressorContinue | _ZstdCompressorFlushBlock | _ZstdCompressorFlushFrame = 0 self, /, data: ReadableBuffer, mode: _ZstdCompressorContinue | _ZstdCompressorFlushBlock | _ZstdCompressorFlushFrame = 0
) -> bytes: ) -> bytes:
@ -126,7 +126,7 @@ class ZstdDecompressor:
function instead. function instead.
""" """
def __init__(self, zstd_dict: ZstdDict | None = None, options: Mapping[int, int] | None = None) -> None: ... def __new__(cls, zstd_dict: ZstdDict | None = None, options: Mapping[int, int] | None = None) -> Self: ...
def decompress(self, /, data: ReadableBuffer, max_length: int = -1) -> bytes: def decompress(self, /, data: ReadableBuffer, max_length: int = -1) -> bytes:
"""Decompress *data*, returning uncompressed bytes if possible, or b'' otherwise. """Decompress *data*, returning uncompressed bytes if possible, or b'' otherwise.
@ -188,7 +188,7 @@ class ZstdDict:
by multiple ZstdCompressor or ZstdDecompressor objects. by multiple ZstdCompressor or ZstdDecompressor objects.
""" """
def __init__(self, dict_content: bytes, /, *, is_raw: bool = False) -> None: ... def __new__(cls, dict_content: bytes, /, *, is_raw: bool = False) -> Self: ...
def __len__(self, /) -> int: def __len__(self, /) -> int:
"""Return len(self).""" """Return len(self)."""

View file

@ -42,6 +42,20 @@ if sys.version_info >= (3, 14):
""" """
__slots__ = (
"__forward_is_argument__",
"__forward_is_class__",
"__forward_module__",
"__weakref__",
"__arg__",
"__globals__",
"__extra_names__",
"__code__",
"__ast_node__",
"__cell__",
"__owner__",
"__stringifier_dict__",
)
__forward_is_argument__: bool __forward_is_argument__: bool
__forward_is_class__: bool __forward_is_class__: bool
__forward_module__: str | None __forward_module__: str | None

View file

@ -260,7 +260,7 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer):
exit_on_error: bool = True, exit_on_error: bool = True,
*, *,
suggest_on_error: bool = False, suggest_on_error: bool = False,
color: bool = False, color: bool = True,
) -> None: ... ) -> None: ...
else: else:
def __init__( def __init__(

View file

@ -9,7 +9,7 @@ from _typeshed import ReadableBuffer, SupportsRead, SupportsWrite
from collections.abc import Iterable, MutableSequence from collections.abc import Iterable, MutableSequence
from types import GenericAlias from types import GenericAlias
from typing import Any, ClassVar, Literal, SupportsIndex, TypeVar, overload from typing import Any, ClassVar, Literal, SupportsIndex, TypeVar, overload
from typing_extensions import Self, TypeAlias, deprecated from typing_extensions import Self, TypeAlias, deprecated, disjoint_base
_IntTypeCode: TypeAlias = Literal["b", "B", "h", "H", "i", "I", "l", "L", "q", "Q"] _IntTypeCode: TypeAlias = Literal["b", "B", "h", "H", "i", "I", "l", "L", "q", "Q"]
_FloatTypeCode: TypeAlias = Literal["f", "d"] _FloatTypeCode: TypeAlias = Literal["f", "d"]
@ -23,6 +23,7 @@ _T = TypeVar("_T", int, float, str)
typecodes: str typecodes: str
@disjoint_base
class array(MutableSequence[_T]): class array(MutableSequence[_T]):
"""array(typecode [, initializer]) -> array """array(typecode [, initializer]) -> array

View file

@ -34,7 +34,7 @@ from _ast import (
from _typeshed import ReadableBuffer, Unused from _typeshed import ReadableBuffer, Unused
from collections.abc import Iterable, Iterator, Sequence from collections.abc import Iterable, Iterator, Sequence
from typing import Any, ClassVar, Generic, Literal, TypedDict, TypeVar as _TypeVar, overload, type_check_only from typing import Any, ClassVar, Generic, Literal, TypedDict, TypeVar as _TypeVar, overload, type_check_only
from typing_extensions import Self, Unpack, deprecated from typing_extensions import Self, Unpack, deprecated, disjoint_base
if sys.version_info >= (3, 13): if sys.version_info >= (3, 13):
from _ast import PyCF_OPTIMIZED_AST as PyCF_OPTIMIZED_AST from _ast import PyCF_OPTIMIZED_AST as PyCF_OPTIMIZED_AST
@ -53,17 +53,25 @@ class _Attributes(TypedDict, Generic[_EndPositionT], total=False):
# The various AST classes are implemented in C, and imported from _ast at runtime, # The various AST classes are implemented in C, and imported from _ast at runtime,
# but they consider themselves to live in the ast module, # but they consider themselves to live in the ast module,
# so we'll define the stubs in this file. # so we'll define the stubs in this file.
class AST: if sys.version_info >= (3, 12):
if sys.version_info >= (3, 10): @disjoint_base
class AST:
__match_args__ = () __match_args__ = ()
_attributes: ClassVar[tuple[str, ...]] _attributes: ClassVar[tuple[str, ...]]
_fields: ClassVar[tuple[str, ...]] _fields: ClassVar[tuple[str, ...]]
if sys.version_info >= (3, 13): if sys.version_info >= (3, 13):
_field_types: ClassVar[dict[str, Any]] _field_types: ClassVar[dict[str, Any]]
if sys.version_info >= (3, 14): if sys.version_info >= (3, 14):
def __replace__(self) -> Self: def __replace__(self) -> Self:
"""Return a copy of the AST node with new values for the specified fields.""" """Return a copy of the AST node with new values for the specified fields."""
else:
class AST:
if sys.version_info >= (3, 10):
__match_args__ = ()
_attributes: ClassVar[tuple[str, ...]]
_fields: ClassVar[tuple[str, ...]]
class mod(AST): class mod(AST):
"""mod = Module(stmt* body, type_ignore* type_ignores) """mod = Module(stmt* body, type_ignore* type_ignores)

View file

@ -25,7 +25,7 @@ from asyncio.transports import BaseTransport, DatagramTransport, ReadTransport,
from collections.abc import Callable, Iterable, Sequence from collections.abc import Callable, Iterable, Sequence
from concurrent.futures import Executor, ThreadPoolExecutor from concurrent.futures import Executor, ThreadPoolExecutor
from contextvars import Context from contextvars import Context
from socket import AddressFamily, SocketKind, _Address, _RetAddress, socket from socket import AddressFamily, AddressInfo, SocketKind, _Address, _RetAddress, socket
from typing import IO, Any, Literal, TypeVar, overload from typing import IO, Any, Literal, TypeVar, overload
from typing_extensions import TypeAlias, TypeVarTuple, Unpack from typing_extensions import TypeAlias, TypeVarTuple, Unpack
@ -392,8 +392,8 @@ class BaseEventLoop(AbstractEventLoop):
host: str | Sequence[str] | None = None, host: str | Sequence[str] | None = None,
port: int = ..., port: int = ...,
*, *,
family: int = ..., family: int = 0,
flags: int = ..., flags: int = 1,
sock: None = None, sock: None = None,
backlog: int = 100, backlog: int = 100,
ssl: _SSLContext = None, ssl: _SSLContext = None,
@ -427,8 +427,8 @@ class BaseEventLoop(AbstractEventLoop):
host: None = None, host: None = None,
port: None = None, port: None = None,
*, *,
family: int = ..., family: int = 0,
flags: int = ..., flags: int = 1,
sock: socket = ..., sock: socket = ...,
backlog: int = 100, backlog: int = 100,
ssl: _SSLContext = None, ssl: _SSLContext = None,
@ -447,8 +447,8 @@ class BaseEventLoop(AbstractEventLoop):
host: str | Sequence[str] | None = None, host: str | Sequence[str] | None = None,
port: int = ..., port: int = ...,
*, *,
family: int = ..., family: int = AddressFamily.AF_UNSPEC,
flags: int = ..., flags: int = AddressInfo.AI_PASSIVE,
sock: None = None, sock: None = None,
backlog: int = 100, backlog: int = 100,
ssl: _SSLContext = None, ssl: _SSLContext = None,
@ -481,8 +481,8 @@ class BaseEventLoop(AbstractEventLoop):
host: None = None, host: None = None,
port: None = None, port: None = None,
*, *,
family: int = ..., family: int = AddressFamily.AF_UNSPEC,
flags: int = ..., flags: int = AddressInfo.AI_PASSIVE,
sock: socket = ..., sock: socket = ...,
backlog: int = 100, backlog: int = 100,
ssl: _SSLContext = None, ssl: _SSLContext = None,
@ -500,8 +500,8 @@ class BaseEventLoop(AbstractEventLoop):
host: str | Sequence[str] | None = None, host: str | Sequence[str] | None = None,
port: int = ..., port: int = ...,
*, *,
family: int = ..., family: int = AddressFamily.AF_UNSPEC,
flags: int = ..., flags: int = AddressInfo.AI_PASSIVE,
sock: None = None, sock: None = None,
backlog: int = 100, backlog: int = 100,
ssl: _SSLContext = None, ssl: _SSLContext = None,
@ -533,8 +533,8 @@ class BaseEventLoop(AbstractEventLoop):
host: None = None, host: None = None,
port: None = None, port: None = None,
*, *,
family: int = ..., family: int = AddressFamily.AF_UNSPEC,
flags: int = ..., flags: int = AddressInfo.AI_PASSIVE,
sock: socket = ..., sock: socket = ...,
backlog: int = 100, backlog: int = 100,
ssl: _SSLContext = None, ssl: _SSLContext = None,

View file

@ -13,7 +13,7 @@ from abc import ABCMeta, abstractmethod
from collections.abc import Callable, Sequence from collections.abc import Callable, Sequence
from concurrent.futures import Executor from concurrent.futures import Executor
from contextvars import Context from contextvars import Context
from socket import AddressFamily, SocketKind, _Address, _RetAddress, socket from socket import AddressFamily, AddressInfo, SocketKind, _Address, _RetAddress, socket
from typing import IO, Any, Literal, Protocol, TypeVar, overload, type_check_only from typing import IO, Any, Literal, Protocol, TypeVar, overload, type_check_only
from typing_extensions import Self, TypeAlias, TypeVarTuple, Unpack, deprecated from typing_extensions import Self, TypeAlias, TypeVarTuple, Unpack, deprecated
@ -352,8 +352,8 @@ class AbstractEventLoop:
host: str | Sequence[str] | None = None, host: str | Sequence[str] | None = None,
port: int = ..., port: int = ...,
*, *,
family: int = ..., family: int = AddressFamily.AF_UNSPEC,
flags: int = ..., flags: int = AddressInfo.AI_PASSIVE,
sock: None = None, sock: None = None,
backlog: int = 100, backlog: int = 100,
ssl: _SSLContext = None, ssl: _SSLContext = None,
@ -424,8 +424,8 @@ class AbstractEventLoop:
host: None = None, host: None = None,
port: None = None, port: None = None,
*, *,
family: int = ..., family: int = AddressFamily.AF_UNSPEC,
flags: int = ..., flags: int = AddressInfo.AI_PASSIVE,
sock: socket = ..., sock: socket = ...,
backlog: int = 100, backlog: int = 100,
ssl: _SSLContext = None, ssl: _SSLContext = None,
@ -445,8 +445,8 @@ class AbstractEventLoop:
host: str | Sequence[str] | None = None, host: str | Sequence[str] | None = None,
port: int = ..., port: int = ...,
*, *,
family: int = ..., family: int = AddressFamily.AF_UNSPEC,
flags: int = ..., flags: int = AddressInfo.AI_PASSIVE,
sock: None = None, sock: None = None,
backlog: int = 100, backlog: int = 100,
ssl: _SSLContext = None, ssl: _SSLContext = None,
@ -513,8 +513,8 @@ class AbstractEventLoop:
host: None = None, host: None = None,
port: None = None, port: None = None,
*, *,
family: int = ..., family: int = AddressFamily.AF_UNSPEC,
flags: int = ..., flags: int = AddressInfo.AI_PASSIVE,
sock: socket = ..., sock: socket = ...,
backlog: int = 100, backlog: int = 100,
ssl: _SSLContext = None, ssl: _SSLContext = None,
@ -533,8 +533,8 @@ class AbstractEventLoop:
host: str | Sequence[str] | None = None, host: str | Sequence[str] | None = None,
port: int = ..., port: int = ...,
*, *,
family: int = ..., family: int = AddressFamily.AF_UNSPEC,
flags: int = ..., flags: int = AddressInfo.AI_PASSIVE,
sock: None = None, sock: None = None,
backlog: int = 100, backlog: int = 100,
ssl: _SSLContext = None, ssl: _SSLContext = None,
@ -596,8 +596,8 @@ class AbstractEventLoop:
host: None = None, host: None = None,
port: None = None, port: None = None,
*, *,
family: int = ..., family: int = AddressFamily.AF_UNSPEC,
flags: int = ..., flags: int = AddressInfo.AI_PASSIVE,
sock: socket = ..., sock: socket = ...,
backlog: int = 100, backlog: int = 100,
ssl: _SSLContext = None, ssl: _SSLContext = None,
@ -872,7 +872,7 @@ class AbstractEventLoop:
bufsize: Literal[0] = 0, bufsize: Literal[0] = 0,
encoding: None = None, encoding: None = None,
errors: None = None, errors: None = None,
text: Literal[False] | None = ..., text: Literal[False] | None = None,
**kwargs: Any, **kwargs: Any,
) -> tuple[SubprocessTransport, _ProtocolT]: ... ) -> tuple[SubprocessTransport, _ProtocolT]: ...
@abstractmethod @abstractmethod

View file

@ -1,72 +1,74 @@
"""Introspection utils for tasks call graphs.""" """Introspection utils for tasks call graphs."""
import sys
from _typeshed import SupportsWrite from _typeshed import SupportsWrite
from asyncio import Future from asyncio import Future
from dataclasses import dataclass from dataclasses import dataclass
from types import FrameType from types import FrameType
from typing import Any, overload from typing import Any, overload
__all__ = ("capture_call_graph", "format_call_graph", "print_call_graph", "FrameCallGraphEntry", "FutureCallGraph") if sys.version_info >= (3, 14):
__all__ = ("capture_call_graph", "format_call_graph", "print_call_graph", "FrameCallGraphEntry", "FutureCallGraph")
@dataclass(frozen=True) @dataclass(frozen=True, slots=True)
class FrameCallGraphEntry: class FrameCallGraphEntry:
"""FrameCallGraphEntry(frame: frame)""" """FrameCallGraphEntry(frame: frame)"""
frame: FrameType frame: FrameType
@dataclass(frozen=True) @dataclass(frozen=True, slots=True)
class FutureCallGraph: class FutureCallGraph:
"""FutureCallGraph(future: _asyncio.Future, call_stack: tuple['FrameCallGraphEntry', ...], awaited_by: tuple['FutureCallGraph', ...])""" """FutureCallGraph(future: _asyncio.Future, call_stack: tuple['FrameCallGraphEntry', ...], awaited_by: tuple['FutureCallGraph', ...])"""
future: Future[Any] future: Future[Any]
call_stack: tuple[FrameCallGraphEntry, ...] call_stack: tuple[FrameCallGraphEntry, ...]
awaited_by: tuple[FutureCallGraph, ...] awaited_by: tuple[FutureCallGraph, ...]
@overload @overload
def capture_call_graph(future: None = None, /, *, depth: int = 1, limit: int | None = None) -> FutureCallGraph | None: def capture_call_graph(future: None = None, /, *, depth: int = 1, limit: int | None = None) -> FutureCallGraph | None:
"""Capture the async call graph for the current task or the provided Future. """Capture the async call graph for the current task or the provided Future.
The graph is represented with three data structures: The graph is represented with three data structures:
* FutureCallGraph(future, call_stack, awaited_by) * FutureCallGraph(future, call_stack, awaited_by)
Where 'future' is an instance of asyncio.Future or asyncio.Task. Where 'future' is an instance of asyncio.Future or asyncio.Task.
'call_stack' is a tuple of FrameGraphEntry objects. 'call_stack' is a tuple of FrameGraphEntry objects.
'awaited_by' is a tuple of FutureCallGraph objects. 'awaited_by' is a tuple of FutureCallGraph objects.
* FrameCallGraphEntry(frame) * FrameCallGraphEntry(frame)
Where 'frame' is a frame object of a regular Python function Where 'frame' is a frame object of a regular Python function
in the call stack. in the call stack.
Receives an optional 'future' argument. If not passed, Receives an optional 'future' argument. If not passed,
the current task will be used. If there's no current task, the function the current task will be used. If there's no current task, the function
returns None. returns None.
If "capture_call_graph()" is introspecting *the current task*, the If "capture_call_graph()" is introspecting *the current task*, the
optional keyword-only 'depth' argument can be used to skip the specified optional keyword-only 'depth' argument can be used to skip the specified
number of frames from top of the stack. number of frames from top of the stack.
If the optional keyword-only 'limit' argument is provided, each call stack If the optional keyword-only 'limit' argument is provided, each call stack
in the resulting graph is truncated to include at most ``abs(limit)`` in the resulting graph is truncated to include at most ``abs(limit)``
entries. If 'limit' is positive, the entries left are the closest to entries. If 'limit' is positive, the entries left are the closest to
the invocation point. If 'limit' is negative, the topmost entries are the invocation point. If 'limit' is negative, the topmost entries are
left. If 'limit' is omitted or None, all entries are present. left. If 'limit' is omitted or None, all entries are present.
If 'limit' is 0, the call stack is not captured at all, only If 'limit' is 0, the call stack is not captured at all, only
"awaited by" information is present. "awaited by" information is present.
""" """
@overload @overload
def capture_call_graph(future: Future[Any], /, *, depth: int = 1, limit: int | None = None) -> FutureCallGraph | None: ... def capture_call_graph(future: Future[Any], /, *, depth: int = 1, limit: int | None = None) -> FutureCallGraph | None: ...
def format_call_graph(future: Future[Any] | None = None, /, *, depth: int = 1, limit: int | None = None) -> str: def format_call_graph(future: Future[Any] | None = None, /, *, depth: int = 1, limit: int | None = None) -> str:
"""Return the async call graph as a string for `future`. """Return the async call graph as a string for `future`.
If `future` is not provided, format the call graph for the current task. If `future` is not provided, format the call graph for the current task.
""" """
def print_call_graph( def print_call_graph(
future: Future[Any] | None = None, /, *, file: SupportsWrite[str] | None = None, depth: int = 1, limit: int | None = None future: Future[Any] | None = None, /, *, file: SupportsWrite[str] | None = None, depth: int = 1, limit: int | None = None
) -> None: ) -> None:
"""Print the async call graph for the current task or the provided Future.""" """Print the async call graph for the current task or the provided Future."""

View file

@ -34,7 +34,7 @@ if sys.version_info >= (3, 10):
port: int | str | None = None, port: int | str | None = None,
*, *,
limit: int = 65536, limit: int = 65536,
ssl_handshake_timeout: float | None = ..., ssl_handshake_timeout: float | None = None,
**kwds: Any, **kwds: Any,
) -> tuple[StreamReader, StreamWriter]: ) -> tuple[StreamReader, StreamWriter]:
"""A wrapper for create_connection() returning a (reader, writer) pair. """A wrapper for create_connection() returning a (reader, writer) pair.
@ -61,7 +61,7 @@ if sys.version_info >= (3, 10):
port: int | str | None = None, port: int | str | None = None,
*, *,
limit: int = 65536, limit: int = 65536,
ssl_handshake_timeout: float | None = ..., ssl_handshake_timeout: float | None = None,
**kwds: Any, **kwds: Any,
) -> Server: ) -> Server:
"""Start a socket server, call back for each client connected. """Start a socket server, call back for each client connected.
@ -92,7 +92,7 @@ else:
*, *,
loop: events.AbstractEventLoop | None = None, loop: events.AbstractEventLoop | None = None,
limit: int = 65536, limit: int = 65536,
ssl_handshake_timeout: float | None = ..., ssl_handshake_timeout: float | None = None,
**kwds: Any, **kwds: Any,
) -> tuple[StreamReader, StreamWriter]: ) -> tuple[StreamReader, StreamWriter]:
"""A wrapper for create_connection() returning a (reader, writer) pair. """A wrapper for create_connection() returning a (reader, writer) pair.
@ -120,7 +120,7 @@ else:
*, *,
loop: events.AbstractEventLoop | None = None, loop: events.AbstractEventLoop | None = None,
limit: int = 65536, limit: int = 65536,
ssl_handshake_timeout: float | None = ..., ssl_handshake_timeout: float | None = None,
**kwds: Any, **kwds: Any,
) -> Server: ) -> Server:
"""Start a socket server, call back for each client connected. """Start a socket server, call back for each client connected.

View file

@ -64,7 +64,7 @@ if sys.version_info >= (3, 11):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
group: None | str | int = None, group: None | str | int = None,
extra_groups: None | Collection[str | int] = None, extra_groups: None | Collection[str | int] = None,
user: None | str | int = None, user: None | str | int = None,
@ -96,7 +96,7 @@ if sys.version_info >= (3, 11):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
group: None | str | int = None, group: None | str | int = None,
extra_groups: None | Collection[str | int] = None, extra_groups: None | Collection[str | int] = None,
user: None | str | int = None, user: None | str | int = None,
@ -130,7 +130,7 @@ elif sys.version_info >= (3, 10):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
group: None | str | int = None, group: None | str | int = None,
extra_groups: None | Collection[str | int] = None, extra_groups: None | Collection[str | int] = None,
user: None | str | int = None, user: None | str | int = None,
@ -161,7 +161,7 @@ elif sys.version_info >= (3, 10):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
group: None | str | int = None, group: None | str | int = None,
extra_groups: None | Collection[str | int] = None, extra_groups: None | Collection[str | int] = None,
user: None | str | int = None, user: None | str | int = None,
@ -195,7 +195,7 @@ else: # >= 3.9
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
group: None | str | int = None, group: None | str | int = None,
extra_groups: None | Collection[str | int] = None, extra_groups: None | Collection[str | int] = None,
user: None | str | int = None, user: None | str | int = None,
@ -226,7 +226,7 @@ else: # >= 3.9
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
group: None | str | int = None, group: None | str | int = None,
extra_groups: None | Collection[str | int] = None, extra_groups: None | Collection[str | int] = None,
user: None | str | int = None, user: None | str | int = None,

View file

@ -70,7 +70,7 @@ class TransportSocket:
@deprecated("Removed in Python 3.11") @deprecated("Removed in Python 3.11")
def makefile(self) -> BinaryIO: ... def makefile(self) -> BinaryIO: ...
@deprecated("Rmoved in Python 3.11") @deprecated("Rmoved in Python 3.11")
def sendfile(self, file: BinaryIO, offset: int = ..., count: int | None = ...) -> int: ... def sendfile(self, file: BinaryIO, offset: int = 0, count: int | None = None) -> int: ...
@deprecated("Removed in Python 3.11") @deprecated("Removed in Python 3.11")
def close(self) -> None: ... def close(self) -> None: ...
@deprecated("Removed in Python 3.11") @deprecated("Removed in Python 3.11")
@ -78,17 +78,22 @@ class TransportSocket:
if sys.platform == "linux": if sys.platform == "linux":
@deprecated("Removed in Python 3.11") @deprecated("Removed in Python 3.11")
def sendmsg_afalg( def sendmsg_afalg(
self, msg: Iterable[ReadableBuffer] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = ... self, msg: Iterable[ReadableBuffer] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = 0
) -> int: ... ) -> int: ...
else: else:
@deprecated("Removed in Python 3.11.") @deprecated("Removed in Python 3.11.")
def sendmsg_afalg( def sendmsg_afalg(
self, msg: Iterable[ReadableBuffer] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = ... self, msg: Iterable[ReadableBuffer] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = 0
) -> NoReturn: ... ) -> NoReturn: ...
@deprecated("Removed in Python 3.11.") @deprecated("Removed in Python 3.11.")
def sendmsg( def sendmsg(
self, buffers: Iterable[ReadableBuffer], ancdata: Iterable[_CMSG] = ..., flags: int = ..., address: _Address = ..., / self,
buffers: Iterable[ReadableBuffer],
ancdata: Iterable[_CMSG] = ...,
flags: int = 0,
address: _Address | None = None,
/,
) -> int: ... ) -> int: ...
@overload @overload
@deprecated("Removed in Python 3.11.") @deprecated("Removed in Python 3.11.")
@ -97,9 +102,9 @@ class TransportSocket:
@deprecated("Removed in Python 3.11.") @deprecated("Removed in Python 3.11.")
def sendto(self, data: ReadableBuffer, flags: int, address: _Address) -> int: ... def sendto(self, data: ReadableBuffer, flags: int, address: _Address) -> int: ...
@deprecated("Removed in Python 3.11.") @deprecated("Removed in Python 3.11.")
def send(self, data: ReadableBuffer, flags: int = ...) -> int: ... def send(self, data: ReadableBuffer, flags: int = 0) -> int: ...
@deprecated("Removed in Python 3.11.") @deprecated("Removed in Python 3.11.")
def sendall(self, data: ReadableBuffer, flags: int = ...) -> None: ... def sendall(self, data: ReadableBuffer, flags: int = 0) -> None: ...
@deprecated("Removed in Python 3.11.") @deprecated("Removed in Python 3.11.")
def set_inheritable(self, inheritable: bool) -> None: ... def set_inheritable(self, inheritable: bool) -> None: ...
if sys.platform == "win32": if sys.platform == "win32":
@ -110,19 +115,19 @@ class TransportSocket:
def share(self, process_id: int) -> NoReturn: ... def share(self, process_id: int) -> NoReturn: ...
@deprecated("Removed in Python 3.11.") @deprecated("Removed in Python 3.11.")
def recv_into(self, buffer: _WriteBuffer, nbytes: int = ..., flags: int = ...) -> int: ... def recv_into(self, buffer: _WriteBuffer, nbytes: int = 0, flags: int = 0) -> int: ...
@deprecated("Removed in Python 3.11.") @deprecated("Removed in Python 3.11.")
def recvfrom_into(self, buffer: _WriteBuffer, nbytes: int = ..., flags: int = ...) -> tuple[int, _RetAddress]: ... def recvfrom_into(self, buffer: _WriteBuffer, nbytes: int = 0, flags: int = 0) -> tuple[int, _RetAddress]: ...
@deprecated("Removed in Python 3.11.") @deprecated("Removed in Python 3.11.")
def recvmsg_into( def recvmsg_into(
self, buffers: Iterable[_WriteBuffer], ancbufsize: int = ..., flags: int = ..., / self, buffers: Iterable[_WriteBuffer], ancbufsize: int = 0, flags: int = 0, /
) -> tuple[int, list[_CMSG], int, Any]: ... ) -> tuple[int, list[_CMSG], int, Any]: ...
@deprecated("Removed in Python 3.11.") @deprecated("Removed in Python 3.11.")
def recvmsg(self, bufsize: int, ancbufsize: int = ..., flags: int = ..., /) -> tuple[bytes, list[_CMSG], int, Any]: ... def recvmsg(self, bufsize: int, ancbufsize: int = 0, flags: int = 0, /) -> tuple[bytes, list[_CMSG], int, Any]: ...
@deprecated("Removed in Python 3.11.") @deprecated("Removed in Python 3.11.")
def recvfrom(self, bufsize: int, flags: int = ...) -> tuple[bytes, _RetAddress]: ... def recvfrom(self, bufsize: int, flags: int = 0) -> tuple[bytes, _RetAddress]: ...
@deprecated("Removed in Python 3.11.") @deprecated("Removed in Python 3.11.")
def recv(self, bufsize: int, flags: int = ...) -> bytes: ... def recv(self, bufsize: int, flags: int = 0) -> bytes: ...
@deprecated("Removed in Python 3.11.") @deprecated("Removed in Python 3.11.")
def __enter__(self) -> socket.socket: ... def __enter__(self) -> socket.socket: ...
@deprecated("Removed in Python 3.11.") @deprecated("Removed in Python 3.11.")

View file

@ -140,6 +140,6 @@ if sys.platform == "win32":
if sys.version_info >= (3, 14): if sys.version_info >= (3, 14):
_DefaultEventLoopPolicy = _WindowsProactorEventLoopPolicy _DefaultEventLoopPolicy = _WindowsProactorEventLoopPolicy
else: else:
DefaultEventLoopPolicy = WindowsSelectorEventLoopPolicy DefaultEventLoopPolicy = WindowsProactorEventLoopPolicy
if sys.version_info >= (3, 13): if sys.version_info >= (3, 13):
EventLoop = ProactorEventLoop EventLoop = ProactorEventLoop

View file

@ -47,9 +47,9 @@ if sys.platform == "win32":
def __new__( def __new__(
cls, cls,
args: subprocess._CMD, args: subprocess._CMD,
stdin: subprocess._FILE | None = ..., stdin: subprocess._FILE | None = None,
stdout: subprocess._FILE | None = ..., stdout: subprocess._FILE | None = None,
stderr: subprocess._FILE | None = ..., stderr: subprocess._FILE | None = None,
**kwds: Any, **kwds: Any,
) -> Self: ... ) -> Self: ...
def __init__( def __init__(

View file

@ -64,7 +64,7 @@ def crc_hqx(data: ReadableBuffer, crc: int, /) -> int:
def crc32(data: ReadableBuffer, crc: int = 0, /) -> int: def crc32(data: ReadableBuffer, crc: int = 0, /) -> int:
"""Compute CRC-32 incrementally.""" """Compute CRC-32 incrementally."""
def b2a_hex(data: ReadableBuffer, sep: str | bytes = ..., bytes_per_sep: int = ...) -> bytes: def b2a_hex(data: ReadableBuffer, sep: str | bytes = ..., bytes_per_sep: int = 1) -> bytes:
"""Hexadecimal representation of binary data. """Hexadecimal representation of binary data.
sep sep
@ -85,7 +85,7 @@ def b2a_hex(data: ReadableBuffer, sep: str | bytes = ..., bytes_per_sep: int = .
b'b9_01ef' b'b9_01ef'
""" """
def hexlify(data: ReadableBuffer, sep: str | bytes = ..., bytes_per_sep: int = ...) -> bytes: def hexlify(data: ReadableBuffer, sep: str | bytes = ..., bytes_per_sep: int = 1) -> bytes:
"""Hexadecimal representation of binary data. """Hexadecimal representation of binary data.
sep sep

View file

@ -83,6 +83,7 @@ from typing_extensions import ( # noqa: Y023
TypeIs, TypeIs,
TypeVarTuple, TypeVarTuple,
deprecated, deprecated,
disjoint_base,
) )
if sys.version_info >= (3, 14): if sys.version_info >= (3, 14):
@ -115,6 +116,7 @@ _StopT_co = TypeVar("_StopT_co", covariant=True, default=_StartT_co) # slice[A
# FIXME: https://github.com/python/typing/issues/213 (replace step=start|stop with step=start&stop) # FIXME: https://github.com/python/typing/issues/213 (replace step=start|stop with step=start&stop)
_StepT_co = TypeVar("_StepT_co", covariant=True, default=_StartT_co | _StopT_co) # slice[A,B] -> slice[A, B, A|B] _StepT_co = TypeVar("_StepT_co", covariant=True, default=_StartT_co | _StopT_co) # slice[A,B] -> slice[A, B, A|B]
@disjoint_base
class object: class object:
"""The base class of the class hierarchy. """The base class of the class hierarchy.
@ -156,6 +158,7 @@ class object:
@classmethod @classmethod
def __subclasshook__(cls, subclass: type, /) -> bool: ... def __subclasshook__(cls, subclass: type, /) -> bool: ...
@disjoint_base
class staticmethod(Generic[_P, _R_co]): class staticmethod(Generic[_P, _R_co]):
"""Convert a function to be a static method. """Convert a function to be a static method.
@ -197,6 +200,7 @@ class staticmethod(Generic[_P, _R_co]):
def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...
__annotate__: AnnotateFunc | None __annotate__: AnnotateFunc | None
@disjoint_base
class classmethod(Generic[_T, _P, _R_co]): class classmethod(Generic[_T, _P, _R_co]):
"""Convert a function to be a class method. """Convert a function to be a class method.
@ -238,6 +242,7 @@ class classmethod(Generic[_T, _P, _R_co]):
def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...
__annotate__: AnnotateFunc | None __annotate__: AnnotateFunc | None
@disjoint_base
class type: class type:
"""type(object) -> the object's type """type(object) -> the object's type
type(name, bases, dict, **kwds) -> a new type type(name, bases, dict, **kwds) -> a new type
@ -307,6 +312,7 @@ class type:
if sys.version_info >= (3, 14): if sys.version_info >= (3, 14):
__annotate__: AnnotateFunc | None __annotate__: AnnotateFunc | None
@disjoint_base
class super: class super:
"""super() -> same as super(__class__, <first argument>) """super() -> same as super(__class__, <first argument>)
super(type) -> unbound super object super(type) -> unbound super object
@ -334,6 +340,7 @@ _PositiveInteger: TypeAlias = Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
_NegativeInteger: TypeAlias = Literal[-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -20] _NegativeInteger: TypeAlias = Literal[-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -20]
_LiteralInteger = _PositiveInteger | _NegativeInteger | Literal[0] # noqa: Y026 # TODO: Use TypeAlias once mypy bugs are fixed _LiteralInteger = _PositiveInteger | _NegativeInteger | Literal[0] # noqa: Y026 # TODO: Use TypeAlias once mypy bugs are fixed
@disjoint_base
class int: class int:
"""int([x]) -> integer """int([x]) -> integer
int(x, base=10) -> integer int(x, base=10) -> integer
@ -646,6 +653,7 @@ class int:
def __format__(self, format_spec: str, /) -> str: def __format__(self, format_spec: str, /) -> str:
"""Convert to a string according to format_spec.""" """Convert to a string according to format_spec."""
@disjoint_base
class float: class float:
"""Convert a string or number to a floating-point number, if possible.""" """Convert a string or number to a floating-point number, if possible."""
@ -806,6 +814,7 @@ class float:
def from_number(cls, number: float | SupportsIndex | SupportsFloat, /) -> Self: def from_number(cls, number: float | SupportsIndex | SupportsFloat, /) -> Self:
"""Convert real number to a floating-point number.""" """Convert real number to a floating-point number."""
@disjoint_base
class complex: class complex:
"""Create a complex number from a string or numbers. """Create a complex number from a string or numbers.
@ -898,6 +907,7 @@ class _FormatMapMapping(Protocol):
class _TranslateTable(Protocol): class _TranslateTable(Protocol):
def __getitem__(self, key: int, /) -> str | int | None: ... def __getitem__(self, key: int, /) -> str | int | None: ...
@disjoint_base
class str(Sequence[str]): class str(Sequence[str]):
"""str(object='') -> str """str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str
@ -1430,6 +1440,7 @@ class str(Sequence[str]):
def __format__(self, format_spec: str, /) -> str: def __format__(self, format_spec: str, /) -> str:
"""Return a formatted version of the string as described by format_spec.""" """Return a formatted version of the string as described by format_spec."""
@disjoint_base
class bytes(Sequence[int]): class bytes(Sequence[int]):
"""bytes(iterable_of_ints) -> bytes """bytes(iterable_of_ints) -> bytes
bytes(string, encoding[, errors]) -> bytes bytes(string, encoding[, errors]) -> bytes
@ -1881,6 +1892,7 @@ class bytes(Sequence[int]):
def __buffer__(self, flags: int, /) -> memoryview: def __buffer__(self, flags: int, /) -> memoryview:
"""Return a buffer object that exposes the underlying memory of the object.""" """Return a buffer object that exposes the underlying memory of the object."""
@disjoint_base
class bytearray(MutableSequence[int]): class bytearray(MutableSequence[int]):
"""bytearray(iterable_of_ints) -> bytearray """bytearray(iterable_of_ints) -> bytearray
bytearray(string, encoding[, errors]) -> bytearray bytearray(string, encoding[, errors]) -> bytearray
@ -2675,6 +2687,8 @@ class slice(Generic[_StartT_co, _StopT_co, _StepT_co]):
handling of normal slices. handling of normal slices.
""" """
# Making this a disjoint_base upsets pyright
# @disjoint_base
class tuple(Sequence[_T_co]): class tuple(Sequence[_T_co]):
"""Built-in immutable sequence. """Built-in immutable sequence.
@ -2781,6 +2795,7 @@ class function:
# mypy uses `builtins.function.__get__` to represent methods, properties, and getset_descriptors so we type the return as Any. # mypy uses `builtins.function.__get__` to represent methods, properties, and getset_descriptors so we type the return as Any.
def __get__(self, instance: object, owner: type | None = None, /) -> Any: ... def __get__(self, instance: object, owner: type | None = None, /) -> Any: ...
@disjoint_base
class list(MutableSequence[_T]): class list(MutableSequence[_T]):
"""Built-in mutable sequence. """Built-in mutable sequence.
@ -2898,6 +2913,7 @@ class list(MutableSequence[_T]):
def __class_getitem__(cls, item: Any, /) -> GenericAlias: def __class_getitem__(cls, item: Any, /) -> GenericAlias:
"""See PEP 585""" """See PEP 585"""
@disjoint_base
class dict(MutableMapping[_KT, _VT]): class dict(MutableMapping[_KT, _VT]):
"""dict() -> new empty dictionary """dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's dict(mapping) -> new dictionary initialized from a mapping object's
@ -3027,6 +3043,7 @@ class dict(MutableMapping[_KT, _VT]):
@overload @overload
def __ior__(self, value: Iterable[tuple[_KT, _VT]], /) -> Self: ... def __ior__(self, value: Iterable[tuple[_KT, _VT]], /) -> Self: ...
@disjoint_base
class set(MutableSet[_T]): class set(MutableSet[_T]):
"""Build an unordered collection of unique elements.""" """Build an unordered collection of unique elements."""
@ -3131,6 +3148,7 @@ class set(MutableSet[_T]):
def __class_getitem__(cls, item: Any, /) -> GenericAlias: def __class_getitem__(cls, item: Any, /) -> GenericAlias:
"""See PEP 585""" """See PEP 585"""
@disjoint_base
class frozenset(AbstractSet[_T_co]): class frozenset(AbstractSet[_T_co]):
"""Build an immutable unordered collection of unique elements.""" """Build an immutable unordered collection of unique elements."""
@ -3192,6 +3210,7 @@ class frozenset(AbstractSet[_T_co]):
def __class_getitem__(cls, item: Any, /) -> GenericAlias: def __class_getitem__(cls, item: Any, /) -> GenericAlias:
"""See PEP 585""" """See PEP 585"""
@disjoint_base
class enumerate(Generic[_T]): class enumerate(Generic[_T]):
"""Return an enumerate object. """Return an enumerate object.
@ -3265,6 +3284,7 @@ class range(Sequence[int]):
def __reversed__(self) -> Iterator[int]: def __reversed__(self) -> Iterator[int]:
"""Return a reverse iterator.""" """Return a reverse iterator."""
@disjoint_base
class property: class property:
"""Property attribute. """Property attribute.
@ -3599,6 +3619,7 @@ else:
exit: _sitebuiltins.Quitter exit: _sitebuiltins.Quitter
@disjoint_base
class filter(Generic[_T]): class filter(Generic[_T]):
"""Return an iterator yielding those items of iterable for which function(item) """Return an iterator yielding those items of iterable for which function(item)
is true. If function is None, return the items that are true. is true. If function is None, return the items that are true.
@ -3752,6 +3773,7 @@ def locals() -> dict[str, Any]:
covered by any backwards compatibility guarantees. covered by any backwards compatibility guarantees.
""" """
@disjoint_base
class map(Generic[_S]): class map(Generic[_S]):
"""Make an iterator that computes the function using arguments from """Make an iterator that computes the function using arguments from
each of the iterables. Stops when the shortest iterable is exhausted. each of the iterables. Stops when the shortest iterable is exhausted.
@ -4231,6 +4253,7 @@ def pow(base: _SupportsSomeKindOfPow, exp: complex, mod: None = None) -> complex
quit: _sitebuiltins.Quitter quit: _sitebuiltins.Quitter
@disjoint_base
class reversed(Generic[_T]): class reversed(Generic[_T]):
"""Return a reverse iterator over the values of the given sequence.""" """Return a reverse iterator over the values of the given sequence."""
@ -4335,7 +4358,7 @@ def vars(object: type, /) -> types.MappingProxyType[str, Any]:
@overload @overload
def vars(object: Any = ..., /) -> dict[str, Any]: ... def vars(object: Any = ..., /) -> dict[str, Any]: ...
@disjoint_base
class zip(Generic[_T_co]): class zip(Generic[_T_co]):
"""The zip object yields n-length tuples, where n is the number of iterables """The zip object yields n-length tuples, where n is the number of iterables
passed as positional arguments to zip(). The i-th element in every tuple passed as positional arguments to zip(). The i-th element in every tuple
@ -4475,6 +4498,7 @@ else:
Ellipsis: ellipsis Ellipsis: ellipsis
@disjoint_base
class BaseException: class BaseException:
"""Common base class for all exceptions""" """Common base class for all exceptions"""
@ -4500,6 +4524,7 @@ class GeneratorExit(BaseException):
class KeyboardInterrupt(BaseException): class KeyboardInterrupt(BaseException):
"""Program interrupted by user.""" """Program interrupted by user."""
@disjoint_base
class SystemExit(BaseException): class SystemExit(BaseException):
"""Request to exit from the interpreter.""" """Request to exit from the interpreter."""
@ -4508,11 +4533,13 @@ class SystemExit(BaseException):
class Exception(BaseException): class Exception(BaseException):
"""Common base class for all non-exit exceptions.""" """Common base class for all non-exit exceptions."""
@disjoint_base
class StopIteration(Exception): class StopIteration(Exception):
"""Signal the end from iterator.__next__().""" """Signal the end from iterator.__next__()."""
value: Any value: Any
@disjoint_base
class OSError(Exception): class OSError(Exception):
"""Base class for I/O related errors.""" """Base class for I/O related errors."""
@ -4535,20 +4562,26 @@ class ArithmeticError(Exception):
class AssertionError(Exception): class AssertionError(Exception):
"""Assertion failed.""" """Assertion failed."""
class AttributeError(Exception): if sys.version_info >= (3, 10):
"""Attribute not found.""" @disjoint_base
class AttributeError(Exception):
"""Attribute not found."""
if sys.version_info >= (3, 10):
def __init__(self, *args: object, name: str | None = ..., obj: object = ...) -> None: ... def __init__(self, *args: object, name: str | None = ..., obj: object = ...) -> None: ...
name: str name: str
obj: object obj: object
else:
class AttributeError(Exception):
"""Attribute not found."""
class BufferError(Exception): class BufferError(Exception):
"""Buffer error.""" """Buffer error."""
class EOFError(Exception): class EOFError(Exception):
"""Read beyond end of file.""" """Read beyond end of file."""
@disjoint_base
class ImportError(Exception): class ImportError(Exception):
"""Import can't find module, or can't find name in module.""" """Import can't find module, or can't find name in module."""
@ -4565,13 +4598,18 @@ class LookupError(Exception):
class MemoryError(Exception): class MemoryError(Exception):
"""Out of memory.""" """Out of memory."""
class NameError(Exception): if sys.version_info >= (3, 10):
"""Name not found globally.""" @disjoint_base
class NameError(Exception):
"""Name not found globally."""
if sys.version_info >= (3, 10):
def __init__(self, *args: object, name: str | None = ...) -> None: ... def __init__(self, *args: object, name: str | None = ...) -> None: ...
name: str name: str
else:
class NameError(Exception):
"""Name not found globally."""
class ReferenceError(Exception): class ReferenceError(Exception):
"""Weak ref proxy used after referent went away.""" """Weak ref proxy used after referent went away."""
@ -4581,6 +4619,7 @@ class RuntimeError(Exception):
class StopAsyncIteration(Exception): class StopAsyncIteration(Exception):
"""Signal the end from iterator.__anext__().""" """Signal the end from iterator.__anext__()."""
@disjoint_base
class SyntaxError(Exception): class SyntaxError(Exception):
"""Invalid syntax.""" """Invalid syntax."""
@ -4708,6 +4747,7 @@ class TabError(IndentationError):
class UnicodeError(ValueError): class UnicodeError(ValueError):
"""Unicode related error.""" """Unicode related error."""
@disjoint_base
class UnicodeDecodeError(UnicodeError): class UnicodeDecodeError(UnicodeError):
"""Unicode decoding error.""" """Unicode decoding error."""
@ -4718,6 +4758,7 @@ class UnicodeDecodeError(UnicodeError):
reason: str reason: str
def __init__(self, encoding: str, object: ReadableBuffer, start: int, end: int, reason: str, /) -> None: ... def __init__(self, encoding: str, object: ReadableBuffer, start: int, end: int, reason: str, /) -> None: ...
@disjoint_base
class UnicodeEncodeError(UnicodeError): class UnicodeEncodeError(UnicodeError):
"""Unicode encoding error.""" """Unicode encoding error."""
@ -4728,6 +4769,7 @@ class UnicodeEncodeError(UnicodeError):
reason: str reason: str
def __init__(self, encoding: str, object: str, start: int, end: int, reason: str, /) -> None: ... def __init__(self, encoding: str, object: str, start: int, end: int, reason: str, /) -> None: ...
@disjoint_base
class UnicodeTranslateError(UnicodeError): class UnicodeTranslateError(UnicodeError):
"""Unicode translation error.""" """Unicode translation error."""
@ -4790,6 +4832,7 @@ if sys.version_info >= (3, 11):
_ExceptionT = TypeVar("_ExceptionT", bound=Exception) _ExceptionT = TypeVar("_ExceptionT", bound=Exception)
# See `check_exception_group.py` for use-cases and comments. # See `check_exception_group.py` for use-cases and comments.
@disjoint_base
class BaseExceptionGroup(BaseException, Generic[_BaseExceptionT_co]): class BaseExceptionGroup(BaseException, Generic[_BaseExceptionT_co]):
"""A combination of multiple unrelated exceptions.""" """A combination of multiple unrelated exceptions."""

View file

@ -9,6 +9,7 @@ ValueError being raised during parsing. The default value of this variable is 0,
meaning the request size is unlimited. meaning the request size is unlimited.
""" """
import os
from _typeshed import SupportsContainsAndGetItem, SupportsGetItem, SupportsItemAccess, Unused from _typeshed import SupportsContainsAndGetItem, SupportsGetItem, SupportsItemAccess, Unused
from builtins import list as _list, type as _type from builtins import list as _list, type as _type
from collections.abc import Iterable, Iterator, Mapping from collections.abc import Iterable, Iterator, Mapping
@ -34,7 +35,7 @@ __all__ = [
def parse( def parse(
fp: IO[Any] | None = None, fp: IO[Any] | None = None,
environ: SupportsItemAccess[str, str] = ..., environ: SupportsItemAccess[str, str] = os.environ,
keep_blank_values: bool = ..., keep_blank_values: bool = ...,
strict_parsing: bool = ..., strict_parsing: bool = ...,
separator: str = "&", separator: str = "&",
@ -90,7 +91,7 @@ def parse_header(line: str) -> tuple[str, dict[str, str]]:
""" """
def test(environ: _Environ = ...) -> None: def test(environ: _Environ = os.environ) -> None:
"""Robust test CGI script, usable as main program. """Robust test CGI script, usable as main program.
Write minimal HTTP headers and dump all information provided to Write minimal HTTP headers and dump all information provided to
@ -98,7 +99,7 @@ def test(environ: _Environ = ...) -> None:
""" """
def print_environ(environ: _Environ = ...) -> None: def print_environ(environ: _Environ = os.environ) -> None:
"""Dump the shell environment as HTML.""" """Dump the shell environment as HTML."""
def print_form(form: dict[str, Any]) -> None: def print_form(form: dict[str, Any]) -> None:
@ -197,7 +198,7 @@ class FieldStorage:
fp: IO[Any] | None = None, fp: IO[Any] | None = None,
headers: Mapping[str, str] | Message | None = None, headers: Mapping[str, str] | Message | None = None,
outerboundary: bytes = b"", outerboundary: bytes = b"",
environ: SupportsContainsAndGetItem[str, str] = ..., environ: SupportsContainsAndGetItem[str, str] = os.environ,
keep_blank_values: int = 0, keep_blank_values: int = 0,
strict_parsing: int = 0, strict_parsing: int = 0,
limit: int | None = None, limit: int | None = None,

View file

@ -7,13 +7,14 @@ Written by Marc-Andre Lemburg (mal@lemburg.com).
""" """
import sys
import types import types
from _codecs import * from _codecs import *
from _typeshed import ReadableBuffer from _typeshed import ReadableBuffer
from abc import abstractmethod from abc import abstractmethod
from collections.abc import Callable, Generator, Iterable from collections.abc import Callable, Generator, Iterable
from typing import Any, BinaryIO, ClassVar, Final, Literal, Protocol, TextIO, overload, type_check_only from typing import Any, BinaryIO, ClassVar, Final, Literal, Protocol, TextIO, overload, type_check_only
from typing_extensions import Self, TypeAlias from typing_extensions import Self, TypeAlias, disjoint_base
__all__ = [ __all__ = [
"register", "register",
@ -131,35 +132,68 @@ class _IncrementalDecoder(Protocol):
class _BufferedIncrementalDecoder(Protocol): class _BufferedIncrementalDecoder(Protocol):
def __call__(self, errors: str = ...) -> BufferedIncrementalDecoder: ... def __call__(self, errors: str = ...) -> BufferedIncrementalDecoder: ...
class CodecInfo(tuple[_Encoder, _Decoder, _StreamReader, _StreamWriter]): if sys.version_info >= (3, 12):
"""Codec details when looking up the codec registry""" class CodecInfo(tuple[_Encoder, _Decoder, _StreamReader, _StreamWriter]):
"""Codec details when looking up the codec registry"""
_is_text_encoding: bool _is_text_encoding: bool
@property @property
def encode(self) -> _Encoder: ... def encode(self) -> _Encoder: ...
@property @property
def decode(self) -> _Decoder: ... def decode(self) -> _Decoder: ...
@property @property
def streamreader(self) -> _StreamReader: ... def streamreader(self) -> _StreamReader: ...
@property @property
def streamwriter(self) -> _StreamWriter: ... def streamwriter(self) -> _StreamWriter: ...
@property @property
def incrementalencoder(self) -> _IncrementalEncoder: ... def incrementalencoder(self) -> _IncrementalEncoder: ...
@property @property
def incrementaldecoder(self) -> _IncrementalDecoder: ... def incrementaldecoder(self) -> _IncrementalDecoder: ...
name: str name: str
def __new__( def __new__(
cls, cls,
encode: _Encoder, encode: _Encoder,
decode: _Decoder, decode: _Decoder,
streamreader: _StreamReader | None = None, streamreader: _StreamReader | None = None,
streamwriter: _StreamWriter | None = None, streamwriter: _StreamWriter | None = None,
incrementalencoder: _IncrementalEncoder | None = None, incrementalencoder: _IncrementalEncoder | None = None,
incrementaldecoder: _IncrementalDecoder | None = None, incrementaldecoder: _IncrementalDecoder | None = None,
name: str | None = None, name: str | None = None,
*, *,
_is_text_encoding: bool | None = None, _is_text_encoding: bool | None = None,
) -> Self: ... ) -> Self: ...
else:
@disjoint_base
class CodecInfo(tuple[_Encoder, _Decoder, _StreamReader, _StreamWriter]):
"""Codec details when looking up the codec registry"""
_is_text_encoding: bool
@property
def encode(self) -> _Encoder: ...
@property
def decode(self) -> _Decoder: ...
@property
def streamreader(self) -> _StreamReader: ...
@property
def streamwriter(self) -> _StreamWriter: ...
@property
def incrementalencoder(self) -> _IncrementalEncoder: ...
@property
def incrementaldecoder(self) -> _IncrementalDecoder: ...
name: str
def __new__(
cls,
encode: _Encoder,
decode: _Decoder,
streamreader: _StreamReader | None = None,
streamwriter: _StreamWriter | None = None,
incrementalencoder: _IncrementalEncoder | None = None,
incrementaldecoder: _IncrementalDecoder | None = None,
name: str | None = None,
*,
_is_text_encoding: bool | None = None,
) -> Self: ...
def getencoder(encoding: str) -> _Encoder: def getencoder(encoding: str) -> _Encoder:
"""Lookup up the codec for the given encoding and return """Lookup up the codec for the given encoding and return

View file

@ -19,7 +19,7 @@ from _collections_abc import dict_items, dict_keys, dict_values
from _typeshed import SupportsItems, SupportsKeysAndGetItem, SupportsRichComparison, SupportsRichComparisonT from _typeshed import SupportsItems, SupportsKeysAndGetItem, SupportsRichComparison, SupportsRichComparisonT
from types import GenericAlias from types import GenericAlias
from typing import Any, ClassVar, Generic, NoReturn, SupportsIndex, TypeVar, final, overload, type_check_only from typing import Any, ClassVar, Generic, NoReturn, SupportsIndex, TypeVar, final, overload, type_check_only
from typing_extensions import Self from typing_extensions import Self, disjoint_base
if sys.version_info >= (3, 10): if sys.version_info >= (3, 10):
from collections.abc import ( from collections.abc import (
@ -271,6 +271,7 @@ class UserString(Sequence[UserString]):
def upper(self) -> Self: ... def upper(self) -> Self: ...
def zfill(self, width: int) -> Self: ... def zfill(self, width: int) -> Self: ...
@disjoint_base
class deque(MutableSequence[_T]): class deque(MutableSequence[_T]):
"""A list-like sequence optimized for data accesses near its endpoints.""" """A list-like sequence optimized for data accesses near its endpoints."""
@ -645,6 +646,7 @@ class _odict_items(dict_items[_KT_co, _VT_co]): # type: ignore[misc] # pyright
class _odict_values(dict_values[_KT_co, _VT_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] class _odict_values(dict_values[_KT_co, _VT_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues]
def __reversed__(self) -> Iterator[_VT_co]: ... def __reversed__(self) -> Iterator[_VT_co]: ...
@disjoint_base
class OrderedDict(dict[_KT, _VT]): class OrderedDict(dict[_KT, _VT]):
"""Dictionary that remembers insertion order""" """Dictionary that remembers insertion order"""
@ -717,6 +719,7 @@ class OrderedDict(dict[_KT, _VT]):
@overload @overload
def __ror__(self, value: dict[_T1, _T2], /) -> OrderedDict[_KT | _T1, _VT | _T2]: ... # type: ignore[misc] def __ror__(self, value: dict[_T1, _T2], /) -> OrderedDict[_KT | _T1, _VT | _T2]: ... # type: ignore[misc]
@disjoint_base
class defaultdict(dict[_KT, _VT]): class defaultdict(dict[_KT, _VT]):
"""defaultdict(default_factory=None, /, [...]) --> dict with default factory """defaultdict(default_factory=None, /, [...]) --> dict with default factory
@ -852,15 +855,23 @@ class ChainMap(MutableMapping[_KT, _VT]):
__copy__ = copy __copy__ = copy
# All arguments to `fromkeys` are passed to `dict.fromkeys` at runtime, # All arguments to `fromkeys` are passed to `dict.fromkeys` at runtime,
# so the signature should be kept in line with `dict.fromkeys`. # so the signature should be kept in line with `dict.fromkeys`.
@classmethod if sys.version_info >= (3, 13):
@overload @classmethod
def fromkeys(cls, iterable: Iterable[_T]) -> ChainMap[_T, Any | None]: @overload
"""Create a new ChainMap with keys from iterable and values set to value.""" def fromkeys(cls, iterable: Iterable[_T], /) -> ChainMap[_T, Any | None]:
"""Create a new ChainMap with keys from iterable and values set to value."""
else:
@classmethod
@overload
def fromkeys(cls, iterable: Iterable[_T]) -> ChainMap[_T, Any | None]:
"""Create a ChainMap with a single dict created from the iterable."""
@classmethod @classmethod
@overload @overload
# Special-case None: the user probably wants to add non-None values later. # Special-case None: the user probably wants to add non-None values later.
def fromkeys(cls, iterable: Iterable[_T], value: None, /) -> ChainMap[_T, Any | None]: ... def fromkeys(cls, iterable: Iterable[_T], value: None, /) -> ChainMap[_T, Any | None]:
"""Create a new ChainMap with keys from iterable and values set to value."""
@classmethod @classmethod
@overload @overload
def fromkeys(cls, iterable: Iterable[_T], value: _S, /) -> ChainMap[_T, _S]: ... def fromkeys(cls, iterable: Iterable[_T], value: _S, /) -> ChainMap[_T, _S]: ...

View file

@ -39,6 +39,7 @@ COMPRESSION_LEVEL_DEFAULT: Final = _zstd.ZSTD_CLEVEL_DEFAULT
class FrameInfo: class FrameInfo:
"""Information about a Zstandard frame.""" """Information about a Zstandard frame."""
__slots__ = ("decompressed_size", "dictionary_id")
decompressed_size: int decompressed_size: int
dictionary_id: int dictionary_id: int
def __init__(self, decompressed_size: int, dictionary_id: int) -> None: ... def __init__(self, decompressed_size: int, dictionary_id: int) -> None: ...

View file

@ -22,6 +22,7 @@ if sys.version_info >= (3, 13): # needed to satisfy pyright checks for Python <
cross-interpreter container is destroyed. cross-interpreter container is destroyed.
""" """
__slots__ = ()
def __new__(cls) -> Never: ... def __new__(cls) -> Never: ...
@classonly @classonly
def singleton(cls, kind: str, module: str, name: str = "UNBOUND") -> Self: def singleton(cls, kind: str, module: str, name: str = "UNBOUND") -> Self:

View file

@ -77,7 +77,7 @@ if sys.version_info >= (3, 13): # needed to satisfy pyright checks for Python <
timeout: SupportsIndex | None = None, timeout: SupportsIndex | None = None,
*, *,
unbounditems: _AnyUnbound | None = None, unbounditems: _AnyUnbound | None = None,
_delay: float = ..., _delay: float = 0.01,
) -> None: ) -> None:
"""Add the object to the queue. """Add the object to the queue.
@ -116,7 +116,7 @@ if sys.version_info >= (3, 13): # needed to satisfy pyright checks for Python <
""" """
def put_nowait(self, obj: object, *, unbounditems: _AnyUnbound | None = None) -> None: ... def put_nowait(self, obj: object, *, unbounditems: _AnyUnbound | None = None) -> None: ...
def get(self, timeout: SupportsIndex | None = None, *, _delay: float = ...) -> object: def get(self, timeout: SupportsIndex | None = None, *, _delay: float = 0.01) -> object:
"""Return the next object from the queue. """Return the next object from the queue.
This blocks while the queue is empty. This blocks while the queue is empty.

View file

@ -784,10 +784,13 @@ class ParsingError(Error):
def __init__(self, source: str) -> None: ... def __init__(self, source: str) -> None: ...
else: else:
@overload @overload
def __init__(self, source: str, filename: None = None) -> None: ... def __init__(self, source: str) -> None: ...
@overload @overload
@deprecated("The `filename` parameter removed in Python 3.12. Use `source` instead.") @deprecated("The `filename` parameter removed in Python 3.12. Use `source` instead.")
def __init__(self, source: None = None, filename: str = ...) -> None: ... def __init__(self, source: None, filename: str | None) -> None: ...
@overload
@deprecated("The `filename` parameter removed in Python 3.12. Use `source` instead.")
def __init__(self, source: None = None, *, filename: str | None) -> None: ...
def append(self, lineno: int, line: str) -> None: ... def append(self, lineno: int, line: str) -> None: ...

View file

@ -2,6 +2,7 @@
import sys import sys
from typing import Final, NamedTuple, type_check_only from typing import Final, NamedTuple, type_check_only
from typing_extensions import disjoint_base
if sys.platform != "win32": if sys.platform != "win32":
@type_check_only @type_check_only
@ -11,10 +12,18 @@ if sys.platform != "win32":
salt_chars: int salt_chars: int
total_size: int total_size: int
class _Method(_MethodBase): if sys.version_info >= (3, 12):
"""Class representing a salt method per the Modular Crypt Format or the class _Method(_MethodBase):
legacy 2-character crypt method. """Class representing a salt method per the Modular Crypt Format or the
""" legacy 2-character crypt method.
"""
else:
@disjoint_base
class _Method(_MethodBase):
"""Class representing a salt method per the Modular Crypt Format or the
legacy 2-character crypt method.
"""
METHOD_CRYPT: Final[_Method] METHOD_CRYPT: Final[_Method]
METHOD_MD5: Final[_Method] METHOD_MD5: Final[_Method]

View file

@ -8,7 +8,7 @@ import sys
from abc import abstractmethod from abc import abstractmethod
from time import struct_time from time import struct_time
from typing import ClassVar, Final, NoReturn, SupportsIndex, final, overload, type_check_only from typing import ClassVar, Final, NoReturn, SupportsIndex, final, overload, type_check_only
from typing_extensions import CapsuleType, Self, TypeAlias, deprecated from typing_extensions import CapsuleType, Self, TypeAlias, deprecated, disjoint_base
if sys.version_info >= (3, 11): if sys.version_info >= (3, 11):
__all__ = ("date", "datetime", "time", "timedelta", "timezone", "tzinfo", "MINYEAR", "MAXYEAR", "UTC") __all__ = ("date", "datetime", "time", "timedelta", "timezone", "tzinfo", "MINYEAR", "MAXYEAR", "UTC")
@ -74,6 +74,7 @@ class _IsoCalendarDate(tuple[int, int, int]):
@property @property
def weekday(self) -> int: ... def weekday(self) -> int: ...
@disjoint_base
class date: class date:
"""date(year, month, day) --> date object""" """date(year, month, day) --> date object"""
@ -181,6 +182,7 @@ class date:
def isocalendar(self) -> _IsoCalendarDate: def isocalendar(self) -> _IsoCalendarDate:
"""Return a named tuple containing ISO year, week number, and weekday.""" """Return a named tuple containing ISO year, week number, and weekday."""
@disjoint_base
class time: class time:
"""time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object """time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object
@ -284,6 +286,7 @@ class time:
_Date: TypeAlias = date _Date: TypeAlias = date
_Time: TypeAlias = time _Time: TypeAlias = time
@disjoint_base
class timedelta: class timedelta:
"""Difference between two datetime values. """Difference between two datetime values.
@ -376,6 +379,7 @@ class timedelta:
def __hash__(self) -> int: ... def __hash__(self) -> int: ...
@disjoint_base
class datetime(date): class datetime(date):
"""datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]]) """datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])

View file

@ -127,7 +127,7 @@ from _decimal import (
from collections.abc import Container, Sequence from collections.abc import Container, Sequence
from types import TracebackType from types import TracebackType
from typing import Any, ClassVar, Literal, NamedTuple, final, overload, type_check_only from typing import Any, ClassVar, Literal, NamedTuple, final, overload, type_check_only
from typing_extensions import Self, TypeAlias from typing_extensions import Self, TypeAlias, disjoint_base
if sys.version_info >= (3, 14): if sys.version_info >= (3, 14):
from _decimal import IEEE_CONTEXT_MAX_BITS as IEEE_CONTEXT_MAX_BITS, IEEEContext as IEEEContext from _decimal import IEEE_CONTEXT_MAX_BITS as IEEE_CONTEXT_MAX_BITS, IEEEContext as IEEEContext
@ -170,6 +170,7 @@ class Overflow(Inexact, Rounded): ...
class Underflow(Inexact, Rounded, Subnormal): ... class Underflow(Inexact, Rounded, Subnormal): ...
class FloatOperation(DecimalException, TypeError): ... class FloatOperation(DecimalException, TypeError): ...
@disjoint_base
class Decimal: class Decimal:
"""Construct a new Decimal object. 'value' can be an integer, string, tuple, """Construct a new Decimal object. 'value' can be an integer, string, tuple,
or another Decimal object. If no value is given, return Decimal('0'). The or another Decimal object. If no value is given, return Decimal('0'). The
@ -693,6 +694,7 @@ class Decimal:
def __deepcopy__(self, memo: Any, /) -> Self: ... def __deepcopy__(self, memo: Any, /) -> Self: ...
def __format__(self, specifier: str, context: Context | None = None, /) -> str: ... def __format__(self, specifier: str, context: Context | None = None, /) -> str: ...
@disjoint_base
class Context: class Context:
"""The context affects almost all operations and controls rounding, """The context affects almost all operations and controls rounding,
Over/Underflow, raising of exceptions and much more. A new context Over/Underflow, raising of exceptions and much more. A new context

View file

@ -5,7 +5,7 @@ import types
from collections.abc import Callable, Iterator from collections.abc import Callable, Iterator
from opcode import * # `dis` re-exports it as a part of public API from opcode import * # `dis` re-exports it as a part of public API
from typing import IO, Any, Final, NamedTuple from typing import IO, Any, Final, NamedTuple
from typing_extensions import Self, TypeAlias from typing_extensions import Self, TypeAlias, disjoint_base
__all__ = [ __all__ = [
"code_info", "code_info",
@ -98,28 +98,107 @@ else:
starts_line: int | None starts_line: int | None
is_jump_target: bool is_jump_target: bool
class Instruction(_Instruction): if sys.version_info >= (3, 12):
"""Details for a bytecode operation. class Instruction(_Instruction):
"""Details for a bytecode operation.
Defined fields: Defined fields:
opname - human readable name for operation opname - human readable name for operation
opcode - numeric code for operation opcode - numeric code for operation
arg - numeric argument to operation (if any), otherwise None arg - numeric argument to operation (if any), otherwise None
argval - resolved arg value (if known), otherwise same as arg argval - resolved arg value (if known), otherwise same as arg
argrepr - human readable description of operation argument argrepr - human readable description of operation argument
offset - start index of operation within bytecode sequence offset - start index of operation within bytecode sequence
start_offset - start index of operation within bytecode sequence including extended args if present; start_offset - start index of operation within bytecode sequence including extended args if present;
otherwise equal to Instruction.offset otherwise equal to Instruction.offset
starts_line - True if this opcode starts a source line, otherwise False starts_line - True if this opcode starts a source line, otherwise False
line_number - source line number associated with this opcode (if any), otherwise None line_number - source line number associated with this opcode (if any), otherwise None
label - A label if this instruction is a jump target, otherwise None label - A label if this instruction is a jump target, otherwise None
positions - Optional dis.Positions object holding the span of source code positions - Optional dis.Positions object holding the span of source code
covered by this instruction covered by this instruction
cache_info - information about the format and content of the instruction's cache cache_info - information about the format and content of the instruction's cache
entries (if any) entries (if any)
""" """
if sys.version_info < (3, 13):
def _disassemble(self, lineno_width: int = 3, mark_as_current: bool = False, offset_width: int = 4) -> str:
"""Format instruction details for inclusion in disassembly output
*lineno_width* sets the width of the line number field (0 omits it)
*mark_as_current* inserts a '-->' marker arrow as part of the line
*offset_width* sets the width of the instruction offset field
"""
if sys.version_info >= (3, 13):
@property
def oparg(self) -> int:
"""Alias for Instruction.arg."""
@property
def baseopcode(self) -> int:
"""Numeric code for the base operation if operation is specialized.
Otherwise equal to Instruction.opcode.
"""
@property
def baseopname(self) -> str:
"""Human readable name for the base operation if operation is specialized.
Otherwise equal to Instruction.opname.
"""
@property
def cache_offset(self) -> int:
"""Start index of the cache entries following the operation."""
@property
def end_offset(self) -> int:
"""End index of the cache entries following the operation."""
@property
def jump_target(self) -> int:
"""Bytecode index of the jump target if this is a jump operation.
Otherwise return None.
"""
@property
def is_jump_target(self) -> bool:
"""True if other code jumps to here, otherwise False"""
if sys.version_info >= (3, 14):
@staticmethod
def make(
opname: str,
arg: int | None,
argval: Any,
argrepr: str,
offset: int,
start_offset: int,
starts_line: bool,
line_number: int | None,
label: int | None = None,
positions: Positions | None = None,
cache_info: list[tuple[str, int, Any]] | None = None,
) -> Instruction: ...
else:
@disjoint_base
class Instruction(_Instruction):
"""Details for a bytecode operation
Defined fields:
opname - human readable name for operation
opcode - numeric code for operation
arg - numeric argument to operation (if any), otherwise None
argval - resolved arg value (if known), otherwise same as arg
argrepr - human readable description of operation argument
offset - start index of operation within bytecode sequence
starts_line - line started by this opcode (if any), otherwise None
is_jump_target - True if other code jumps to here, otherwise False
positions - Optional dis.Positions object holding the span of source code
covered by this instruction
"""
if sys.version_info < (3, 13):
def _disassemble(self, lineno_width: int = 3, mark_as_current: bool = False, offset_width: int = 4) -> str: def _disassemble(self, lineno_width: int = 3, mark_as_current: bool = False, offset_width: int = 4) -> str:
"""Format instruction details for inclusion in disassembly output """Format instruction details for inclusion in disassembly output
@ -127,58 +206,6 @@ class Instruction(_Instruction):
*mark_as_current* inserts a '-->' marker arrow as part of the line *mark_as_current* inserts a '-->' marker arrow as part of the line
*offset_width* sets the width of the instruction offset field *offset_width* sets the width of the instruction offset field
""" """
if sys.version_info >= (3, 13):
@property
def oparg(self) -> int:
"""Alias for Instruction.arg."""
@property
def baseopcode(self) -> int:
"""Numeric code for the base operation if operation is specialized.
Otherwise equal to Instruction.opcode.
"""
@property
def baseopname(self) -> str:
"""Human readable name for the base operation if operation is specialized.
Otherwise equal to Instruction.opname.
"""
@property
def cache_offset(self) -> int:
"""Start index of the cache entries following the operation."""
@property
def end_offset(self) -> int:
"""End index of the cache entries following the operation."""
@property
def jump_target(self) -> int:
"""Bytecode index of the jump target if this is a jump operation.
Otherwise return None.
"""
@property
def is_jump_target(self) -> bool:
"""True if other code jumps to here, otherwise False"""
if sys.version_info >= (3, 14):
@staticmethod
def make(
opname: str,
arg: int | None,
argval: Any,
argrepr: str,
offset: int,
start_offset: int,
starts_line: bool,
line_number: int | None,
label: int | None = None,
positions: Positions | None = None,
cache_info: list[tuple[str, int, Any]] | None = None,
) -> Instruction: ...
class Bytecode: class Bytecode:
"""The bytecode operations of a piece of code """The bytecode operations of a piece of code

View file

@ -59,7 +59,7 @@ def copy_file(
) -> tuple[_BytesPathT | bytes, bool]: ... ) -> tuple[_BytesPathT | bytes, bool]: ...
@overload @overload
def move_file( def move_file(
src: StrPath, dst: _StrPathT, verbose: bool | Literal[0, 1] = 0, dry_run: bool | Literal[0, 1] = 0 src: StrPath, dst: _StrPathT, verbose: bool | Literal[0, 1] = 1, dry_run: bool | Literal[0, 1] = 0
) -> _StrPathT | str: ) -> _StrPathT | str:
"""Move a file 'src' to 'dst'. If 'dst' is a directory, the file will """Move a file 'src' to 'dst'. If 'dst' is a directory, the file will
be moved into it with the same name; otherwise, 'src' is just renamed be moved into it with the same name; otherwise, 'src' is just renamed
@ -71,7 +71,7 @@ def move_file(
@overload @overload
def move_file( def move_file(
src: BytesPath, dst: _BytesPathT, verbose: bool | Literal[0, 1] = 0, dry_run: bool | Literal[0, 1] = 0 src: BytesPath, dst: _BytesPathT, verbose: bool | Literal[0, 1] = 1, dry_run: bool | Literal[0, 1] = 0
) -> _BytesPathT | bytes: ... ) -> _BytesPathT | bytes: ...
def write_file(filename: StrOrBytesPath, contents: Iterable[str]) -> None: def write_file(filename: StrOrBytesPath, contents: Iterable[str]) -> None:
"""Create a file with the specified name and write 'contents' (a """Create a file with the specified name and write 'contents' (a

View file

@ -5,7 +5,7 @@ from _typeshed import SupportsKeysAndGetItem, Unused
from builtins import property as _builtins_property from builtins import property as _builtins_property
from collections.abc import Callable, Iterable, Iterator, Mapping from collections.abc import Callable, Iterable, Iterator, Mapping
from typing import Any, Final, Generic, Literal, TypeVar, overload from typing import Any, Final, Generic, Literal, TypeVar, overload
from typing_extensions import Self, TypeAlias from typing_extensions import Self, TypeAlias, disjoint_base
__all__ = ["EnumMeta", "Enum", "IntEnum", "Flag", "IntFlag", "auto", "unique"] __all__ = ["EnumMeta", "Enum", "IntEnum", "Flag", "IntFlag", "auto", "unique"]
@ -464,22 +464,37 @@ if sys.version_info >= (3, 11):
Only changes the repr(), leaving str() and format() to the mixed-in type. Only changes the repr(), leaving str() and format() to the mixed-in type.
""" """
if sys.version_info >= (3, 11): if sys.version_info >= (3, 12):
_IntEnumBase = ReprEnum class IntEnum(int, ReprEnum):
"""
Enum where members are also (and must be) ints
"""
_value_: int
@_magic_enum_attr
def value(self) -> int:
"""The value of the Enum member."""
def __new__(cls, value: int) -> Self: ...
else: else:
_IntEnumBase = Enum if sys.version_info >= (3, 11):
_IntEnumBase = ReprEnum
else:
_IntEnumBase = Enum
class IntEnum(int, _IntEnumBase): @disjoint_base
""" class IntEnum(int, _IntEnumBase):
Enum where members are also (and must be) ints """
""" Enum where members are also (and must be) ints
"""
_value_: int _value_: int
@_magic_enum_attr @_magic_enum_attr
def value(self) -> int: def value(self) -> int:
"""The value of the Enum member.""" """The value of the Enum member."""
def __new__(cls, value: int) -> Self: ... def __new__(cls, value: int) -> Self: ...
def unique(enumeration: _EnumerationT) -> _EnumerationT: def unique(enumeration: _EnumerationT) -> _EnumerationT:
""" """
@ -608,7 +623,7 @@ if sys.version_info >= (3, 11):
the module is the last module in case of a multi-module name the module is the last module in case of a multi-module name
""" """
if sys.version_info >= (3, 11): if sys.version_info >= (3, 12):
# The body of the class is the same, but the base classes are different. # The body of the class is the same, but the base classes are different.
class IntFlag(int, ReprEnum, Flag, boundary=KEEP): # type: ignore[misc] # complaints about incompatible bases class IntFlag(int, ReprEnum, Flag, boundary=KEEP): # type: ignore[misc] # complaints about incompatible bases
""" """
@ -624,7 +639,25 @@ if sys.version_info >= (3, 11):
__rand__ = __and__ __rand__ = __and__
__rxor__ = __xor__ __rxor__ = __xor__
elif sys.version_info >= (3, 11):
# The body of the class is the same, but the base classes are different.
@disjoint_base
class IntFlag(int, ReprEnum, Flag, boundary=KEEP): # type: ignore[misc] # complaints about incompatible bases
"""
Support for integer-based Flags
"""
def __new__(cls, value: int) -> Self: ...
def __or__(self, other: int) -> Self: ...
def __and__(self, other: int) -> Self: ...
def __xor__(self, other: int) -> Self: ...
def __invert__(self) -> Self: ...
__ror__ = __or__
__rand__ = __and__
__rxor__ = __xor__
else: else:
@disjoint_base
class IntFlag(int, Flag): # type: ignore[misc] # complaints about incompatible bases class IntFlag(int, Flag): # type: ignore[misc] # complaints about incompatible bases
""" """
Support for integer-based Flags Support for integer-based Flags

View file

@ -6,7 +6,7 @@ from _typeshed import SupportsAllComparisons, SupportsItems
from collections.abc import Callable, Hashable, Iterable, Sized from collections.abc import Callable, Hashable, Iterable, Sized
from types import GenericAlias from types import GenericAlias
from typing import Any, Final, Generic, Literal, NamedTuple, TypedDict, TypeVar, final, overload, type_check_only from typing import Any, Final, Generic, Literal, NamedTuple, TypedDict, TypeVar, final, overload, type_check_only
from typing_extensions import ParamSpec, Self, TypeAlias from typing_extensions import ParamSpec, Self, TypeAlias, disjoint_base
__all__ = [ __all__ = [
"update_wrapper", "update_wrapper",
@ -292,6 +292,7 @@ def cmp_to_key(mycmp: Callable[[_T, _T], int]) -> Callable[[_T], SupportsAllComp
Function that compares two objects. Function that compares two objects.
""" """
@disjoint_base
class partial(Generic[_T]): class partial(Generic[_T]):
"""Create a new function with partial application of the given arguments """Create a new function with partial application of the given arguments
and keywords. and keywords.
@ -330,10 +331,17 @@ class partialmethod(Generic[_T]):
func: Callable[..., _T] | _Descriptor func: Callable[..., _T] | _Descriptor
args: tuple[Any, ...] args: tuple[Any, ...]
keywords: dict[str, Any] keywords: dict[str, Any]
@overload if sys.version_info >= (3, 14):
def __init__(self, func: Callable[..., _T], /, *args: Any, **keywords: Any) -> None: ... @overload
@overload def __new__(self, func: Callable[..., _T], /, *args: Any, **keywords: Any) -> Self: ...
def __init__(self, func: _Descriptor, /, *args: Any, **keywords: Any) -> None: ... @overload
def __new__(self, func: _Descriptor, /, *args: Any, **keywords: Any) -> Self: ...
else:
@overload
def __init__(self, func: Callable[..., _T], /, *args: Any, **keywords: Any) -> None: ...
@overload
def __init__(self, func: _Descriptor, /, *args: Any, **keywords: Any) -> None: ...
def __get__(self, obj: Any, cls: type[Any] | None = None) -> Callable[..., _T]: ... def __get__(self, obj: Any, cls: type[Any] | None = None) -> Callable[..., _T]: ...
@property @property
def __isabstractmethod__(self) -> bool: ... def __isabstractmethod__(self) -> bool: ...

View file

@ -132,7 +132,7 @@ else:
languages: Iterable[str] | None = None, languages: Iterable[str] | None = None,
class_: None = None, class_: None = None,
fallback: Literal[False] = False, fallback: Literal[False] = False,
codeset: str | None = None, codeset: str | None = ...,
) -> GNUTranslations: ... ) -> GNUTranslations: ...
@overload @overload
def translation( def translation(
@ -142,7 +142,7 @@ else:
*, *,
class_: Callable[[io.BufferedReader], _NullTranslationsT], class_: Callable[[io.BufferedReader], _NullTranslationsT],
fallback: Literal[False] = False, fallback: Literal[False] = False,
codeset: str | None = None, codeset: str | None = ...,
) -> _NullTranslationsT: ... ) -> _NullTranslationsT: ...
@overload @overload
def translation( def translation(
@ -151,7 +151,7 @@ else:
languages: Iterable[str] | None, languages: Iterable[str] | None,
class_: Callable[[io.BufferedReader], _NullTranslationsT], class_: Callable[[io.BufferedReader], _NullTranslationsT],
fallback: Literal[False] = False, fallback: Literal[False] = False,
codeset: str | None = None, codeset: str | None = ...,
) -> _NullTranslationsT: ... ) -> _NullTranslationsT: ...
@overload @overload
def translation( def translation(
@ -160,18 +160,18 @@ else:
languages: Iterable[str] | None = None, languages: Iterable[str] | None = None,
class_: Callable[[io.BufferedReader], NullTranslations] | None = None, class_: Callable[[io.BufferedReader], NullTranslations] | None = None,
fallback: bool = False, fallback: bool = False,
codeset: str | None = None, codeset: str | None = ...,
) -> NullTranslations: ... ) -> NullTranslations: ...
@overload @overload
def install(domain: str, localedir: StrPath | None = None, names: Container[str] | None = None) -> None: ...
@overload
@deprecated("The `codeset` parameter is deprecated since Python 3.8; removed in Python 3.11.")
def install(domain: str, localedir: StrPath | None, codeset: str | None, /, names: Container[str] | None = None) -> None: ...
@overload
@deprecated("The `codeset` parameter is deprecated since Python 3.8; removed in Python 3.11.")
def install( def install(
domain: str, localedir: StrPath | None = None, codeset: None = None, names: Container[str] | None = None domain: str, localedir: StrPath | None = None, *, codeset: str | None, names: Container[str] | None = None
) -> None: ... ) -> None: ...
@overload
@deprecated("The `codeset` parameter is deprecated since Python 3.8; removed in Python 3.11.")
def install(domain: str, localedir: StrPath | None, codeset: str, /, names: Container[str] | None = None) -> None: ...
@overload
@deprecated("The `codeset` parameter is deprecated since Python 3.8; removed in Python 3.11.")
def install(domain: str, localedir: StrPath | None = None, *, codeset: str, names: Container[str] | None = None) -> None: ...
def textdomain(domain: str | None = None) -> str: ... def textdomain(domain: str | None = None) -> str: ...
def bindtextdomain(domain: str, localedir: StrPath | None = None) -> str: ... def bindtextdomain(domain: str, localedir: StrPath | None = None) -> str: ...

View file

@ -11,7 +11,7 @@ from os import PathLike
from pathlib import Path from pathlib import Path
from re import Pattern from re import Pattern
from typing import Any, ClassVar, Generic, NamedTuple, TypeVar, overload from typing import Any, ClassVar, Generic, NamedTuple, TypeVar, overload
from typing_extensions import Self, TypeAlias, deprecated from typing_extensions import Self, TypeAlias, deprecated, disjoint_base
_T = TypeVar("_T") _T = TypeVar("_T")
_KT = TypeVar("_KT") _KT = TypeVar("_KT")
@ -83,44 +83,42 @@ else:
value: str value: str
group: str group: str
class EntryPoint(_EntryPointBase): if sys.version_info >= (3, 11):
"""An entry point as defined by Python packaging conventions. class EntryPoint(_EntryPointBase):
"""An entry point as defined by Python packaging conventions.
See `the packaging docs on entry points See `the packaging docs on entry points
<https://packaging.python.org/specifications/entry-points/>`_ <https://packaging.python.org/specifications/entry-points/>`_
for more information. for more information.
>>> ep = EntryPoint( >>> ep = EntryPoint(
... name=None, group=None, value='package.module:attr [extra1, extra2]') ... name=None, group=None, value='package.module:attr [extra1, extra2]')
>>> ep.module >>> ep.module
'package.module' 'package.module'
>>> ep.attr >>> ep.attr
'attr' 'attr'
>>> ep.extras >>> ep.extras
['extra1', 'extra2'] ['extra1', 'extra2']
""" """
pattern: ClassVar[Pattern[str]] pattern: ClassVar[Pattern[str]]
if sys.version_info >= (3, 11):
name: str name: str
value: str value: str
group: str group: str
def __init__(self, name: str, value: str, group: str) -> None: ... def __init__(self, name: str, value: str, group: str) -> None: ...
def load(self) -> Any: # Callable[[], Any] or an importable module
"""Load the entry point from its definition. If only a module
is indicated by the value, return that module. Otherwise,
return the named object.
"""
def load(self) -> Any: # Callable[[], Any] or an importable module @property
"""Load the entry point from its definition. If only a module def extras(self) -> list[str]: ...
is indicated by the value, return that module. Otherwise, @property
return the named object. def module(self) -> str: ...
""" @property
def attr(self) -> str: ...
@property
def extras(self) -> list[str]: ...
@property
def module(self) -> str: ...
@property
def attr(self) -> str: ...
if sys.version_info >= (3, 10):
dist: ClassVar[Distribution | None] dist: ClassVar[Distribution | None]
def matches( def matches(
self, self,
@ -152,11 +150,81 @@ class EntryPoint(_EntryPointBase):
True True
""" """
def __hash__(self) -> int: ... def __hash__(self) -> int: ...
if sys.version_info >= (3, 11):
def __eq__(self, other: object) -> bool: ... def __eq__(self, other: object) -> bool: ...
def __lt__(self, other: object) -> bool: ... def __lt__(self, other: object) -> bool: ...
if sys.version_info < (3, 12): if sys.version_info < (3, 12):
def __iter__(self) -> Iterator[Any]: # result of iter((str, Self)), really
"""
Supply iter so one may construct dicts of EntryPoints by name.
"""
else:
@disjoint_base
class EntryPoint(_EntryPointBase):
"""An entry point as defined by Python packaging conventions.
See `the packaging docs on entry points
<https://packaging.python.org/specifications/entry-points/>`_
for more information.
>>> ep = EntryPoint(
... name=None, group=None, value='package.module:attr [extra1, extra2]')
>>> ep.module
'package.module'
>>> ep.attr
'attr'
>>> ep.extras
['extra1', 'extra2']
"""
pattern: ClassVar[Pattern[str]]
def load(self) -> Any: # Callable[[], Any] or an importable module
"""Load the entry point from its definition. If only a module
is indicated by the value, return that module. Otherwise,
return the named object.
"""
@property
def extras(self) -> list[str]: ...
@property
def module(self) -> str: ...
@property
def attr(self) -> str: ...
if sys.version_info >= (3, 10):
dist: ClassVar[Distribution | None]
def matches(
self,
*,
name: str = ...,
value: str = ...,
group: str = ...,
module: str = ...,
attr: str = ...,
extras: list[str] = ...,
) -> bool: # undocumented
"""
EntryPoint matches the given parameters.
>>> ep = EntryPoint(group='foo', name='bar', value='bing:bong [extra1, extra2]')
>>> ep.matches(group='foo')
True
>>> ep.matches(name='bar', value='bing:bong [extra1, extra2]')
True
>>> ep.matches(group='foo', name='other')
False
>>> ep.matches()
True
>>> ep.matches(extras=['extra1', 'extra2'])
True
>>> ep.matches(module='bing')
True
>>> ep.matches(attr='bong')
True
"""
def __hash__(self) -> int: ...
def __iter__(self) -> Iterator[Any]: # result of iter((str, Self)), really def __iter__(self) -> Iterator[Any]: # result of iter((str, Self)), really
""" """
Supply iter so one may construct dicts of EntryPoints by name. Supply iter so one may construct dicts of EntryPoints by name.
@ -234,12 +302,15 @@ elif sys.version_info >= (3, 10):
1 1
""" """
__slots__ = ()
class EntryPoints(DeprecatedList[EntryPoint]): # use as list is deprecated since 3.10 class EntryPoints(DeprecatedList[EntryPoint]): # use as list is deprecated since 3.10
""" """
An immutable collection of selectable EntryPoint objects. An immutable collection of selectable EntryPoint objects.
""" """
# int argument is deprecated since 3.10 # int argument is deprecated since 3.10
__slots__ = ()
def __getitem__(self, name: int | str) -> EntryPoint: # type: ignore[override] def __getitem__(self, name: int | str) -> EntryPoint: # type: ignore[override]
""" """
Get the EntryPoint in self matching name. Get the EntryPoint in self matching name.

View file

@ -54,7 +54,7 @@ from types import (
WrapperDescriptorType, WrapperDescriptorType,
) )
from typing import Any, ClassVar, Final, Literal, NamedTuple, Protocol, TypeVar, overload, type_check_only from typing import Any, ClassVar, Final, Literal, NamedTuple, Protocol, TypeVar, overload, type_check_only
from typing_extensions import ParamSpec, Self, TypeAlias, TypeGuard, TypeIs, deprecated from typing_extensions import ParamSpec, Self, TypeAlias, TypeGuard, TypeIs, deprecated, disjoint_base
if sys.version_info >= (3, 14): if sys.version_info >= (3, 14):
from annotationlib import Format from annotationlib import Format
@ -1143,19 +1143,6 @@ if sys.version_info >= (3, 11):
code_context: list[str] | None code_context: list[str] | None
index: int | None # type: ignore[assignment] index: int | None # type: ignore[assignment]
class Traceback(_Traceback):
positions: dis.Positions | None
def __new__(
cls,
filename: str,
lineno: int,
function: str,
code_context: list[str] | None,
index: int | None,
*,
positions: dis.Positions | None = None,
) -> Self: ...
class _FrameInfo(NamedTuple): class _FrameInfo(NamedTuple):
"""_FrameInfo(frame, filename, lineno, function, code_context, index)""" """_FrameInfo(frame, filename, lineno, function, code_context, index)"""
@ -1166,19 +1153,63 @@ if sys.version_info >= (3, 11):
code_context: list[str] | None code_context: list[str] | None
index: int | None # type: ignore[assignment] index: int | None # type: ignore[assignment]
class FrameInfo(_FrameInfo): if sys.version_info >= (3, 12):
positions: dis.Positions | None class Traceback(_Traceback):
def __new__( positions: dis.Positions | None
cls, def __new__(
frame: FrameType, cls,
filename: str, filename: str,
lineno: int, lineno: int,
function: str, function: str,
code_context: list[str] | None, code_context: list[str] | None,
index: int | None, index: int | None,
*, *,
positions: dis.Positions | None = None, positions: dis.Positions | None = None,
) -> Self: ... ) -> Self: ...
class FrameInfo(_FrameInfo):
positions: dis.Positions | None
def __new__(
cls,
frame: FrameType,
filename: str,
lineno: int,
function: str,
code_context: list[str] | None,
index: int | None,
*,
positions: dis.Positions | None = None,
) -> Self: ...
else:
@disjoint_base
class Traceback(_Traceback):
positions: dis.Positions | None
def __new__(
cls,
filename: str,
lineno: int,
function: str,
code_context: list[str] | None,
index: int | None,
*,
positions: dis.Positions | None = None,
) -> Self: ...
@disjoint_base
class FrameInfo(_FrameInfo):
positions: dis.Positions | None
def __new__(
cls,
frame: FrameType,
filename: str,
lineno: int,
function: str,
code_context: list[str] | None,
index: int | None,
*,
positions: dis.Positions | None = None,
) -> Self: ...
else: else:
class Traceback(NamedTuple): class Traceback(NamedTuple):

View file

@ -162,6 +162,7 @@ if sys.version_info >= (3, 14):
This protocol only supports blocking I/O. This protocol only supports blocking I/O.
""" """
__slots__ = ()
def read(self, size: int = ..., /) -> _T_co: def read(self, size: int = ..., /) -> _T_co:
"""Read data from the input stream and return it. """Read data from the input stream and return it.
@ -175,5 +176,6 @@ if sys.version_info >= (3, 14):
This protocol only supports blocking I/O. This protocol only supports blocking I/O.
""" """
__slots__ = ()
def write(self, data: _T_contra, /) -> int: def write(self, data: _T_contra, /) -> int:
"""Write *data* to the output stream and return the number of items written.""" """Write *data* to the output stream and return the number of items written."""

View file

@ -34,7 +34,7 @@ from _typeshed import MaybeNone
from collections.abc import Callable, Iterable, Iterator from collections.abc import Callable, Iterable, Iterator
from types import GenericAlias from types import GenericAlias
from typing import Any, Generic, Literal, SupportsComplex, SupportsFloat, SupportsIndex, SupportsInt, TypeVar, overload from typing import Any, Generic, Literal, SupportsComplex, SupportsFloat, SupportsIndex, SupportsInt, TypeVar, overload
from typing_extensions import Self, TypeAlias from typing_extensions import Self, TypeAlias, disjoint_base
_T = TypeVar("_T") _T = TypeVar("_T")
_S = TypeVar("_S") _S = TypeVar("_S")
@ -58,6 +58,7 @@ _Predicate: TypeAlias = Callable[[_T], object]
# Technically count can take anything that implements a number protocol and has an add method # Technically count can take anything that implements a number protocol and has an add method
# but we can't enforce the add method # but we can't enforce the add method
@disjoint_base
class count(Generic[_N]): class count(Generic[_N]):
"""Return a count object whose .__next__() method returns consecutive values. """Return a count object whose .__next__() method returns consecutive values.
@ -81,6 +82,7 @@ class count(Generic[_N]):
def __iter__(self) -> Self: def __iter__(self) -> Self:
"""Implement iter(self).""" """Implement iter(self)."""
@disjoint_base
class cycle(Generic[_T]): class cycle(Generic[_T]):
"""Return elements from the iterable until it is exhausted. Then repeat the sequence indefinitely.""" """Return elements from the iterable until it is exhausted. Then repeat the sequence indefinitely."""
@ -91,6 +93,7 @@ class cycle(Generic[_T]):
def __iter__(self) -> Self: def __iter__(self) -> Self:
"""Implement iter(self).""" """Implement iter(self)."""
@disjoint_base
class repeat(Generic[_T]): class repeat(Generic[_T]):
"""repeat(object [,times]) -> create an iterator which returns the object """repeat(object [,times]) -> create an iterator which returns the object
for the specified number of times. If not specified, returns the object for the specified number of times. If not specified, returns the object
@ -110,6 +113,7 @@ class repeat(Generic[_T]):
def __length_hint__(self) -> int: def __length_hint__(self) -> int:
"""Private method returning an estimate of len(list(it)).""" """Private method returning an estimate of len(list(it))."""
@disjoint_base
class accumulate(Generic[_T]): class accumulate(Generic[_T]):
"""Return series of accumulated sums (or other binary function results).""" """Return series of accumulated sums (or other binary function results)."""
@ -123,6 +127,7 @@ class accumulate(Generic[_T]):
def __next__(self) -> _T: def __next__(self) -> _T:
"""Implement next(self).""" """Implement next(self)."""
@disjoint_base
class chain(Generic[_T]): class chain(Generic[_T]):
"""Return a chain object whose .__next__() method returns elements from the """Return a chain object whose .__next__() method returns elements from the
first iterable until it is exhausted, then elements from the next first iterable until it is exhausted, then elements from the next
@ -144,6 +149,7 @@ class chain(Generic[_T]):
def __class_getitem__(cls, item: Any, /) -> GenericAlias: def __class_getitem__(cls, item: Any, /) -> GenericAlias:
"""See PEP 585""" """See PEP 585"""
@disjoint_base
class compress(Generic[_T]): class compress(Generic[_T]):
"""Return data elements corresponding to true selector elements. """Return data elements corresponding to true selector elements.
@ -158,6 +164,7 @@ class compress(Generic[_T]):
def __next__(self) -> _T: def __next__(self) -> _T:
"""Implement next(self).""" """Implement next(self)."""
@disjoint_base
class dropwhile(Generic[_T]): class dropwhile(Generic[_T]):
"""Drop items from the iterable while predicate(item) is true. """Drop items from the iterable while predicate(item) is true.
@ -171,6 +178,7 @@ class dropwhile(Generic[_T]):
def __next__(self) -> _T: def __next__(self) -> _T:
"""Implement next(self).""" """Implement next(self)."""
@disjoint_base
class filterfalse(Generic[_T]): class filterfalse(Generic[_T]):
"""Return those items of iterable for which function(item) is false. """Return those items of iterable for which function(item) is false.
@ -184,6 +192,7 @@ class filterfalse(Generic[_T]):
def __next__(self) -> _T: def __next__(self) -> _T:
"""Implement next(self).""" """Implement next(self)."""
@disjoint_base
class groupby(Generic[_T_co, _S_co]): class groupby(Generic[_T_co, _S_co]):
"""make an iterator that returns consecutive keys and groups from the iterable """make an iterator that returns consecutive keys and groups from the iterable
@ -205,6 +214,7 @@ class groupby(Generic[_T_co, _S_co]):
def __next__(self) -> tuple[_T_co, Iterator[_S_co]]: def __next__(self) -> tuple[_T_co, Iterator[_S_co]]:
"""Implement next(self).""" """Implement next(self)."""
@disjoint_base
class islice(Generic[_T]): class islice(Generic[_T]):
"""islice(iterable, stop) --> islice object """islice(iterable, stop) --> islice object
islice(iterable, start, stop[, step]) --> islice object islice(iterable, start, stop[, step]) --> islice object
@ -227,6 +237,7 @@ class islice(Generic[_T]):
def __next__(self) -> _T: def __next__(self) -> _T:
"""Implement next(self).""" """Implement next(self)."""
@disjoint_base
class starmap(Generic[_T_co]): class starmap(Generic[_T_co]):
"""Return an iterator whose values are returned from the function evaluated with an argument tuple taken from the given sequence.""" """Return an iterator whose values are returned from the function evaluated with an argument tuple taken from the given sequence."""
@ -237,6 +248,7 @@ class starmap(Generic[_T_co]):
def __next__(self) -> _T_co: def __next__(self) -> _T_co:
"""Implement next(self).""" """Implement next(self)."""
@disjoint_base
class takewhile(Generic[_T]): class takewhile(Generic[_T]):
"""Return successive entries from an iterable as long as the predicate evaluates to true for each entry.""" """Return successive entries from an iterable as long as the predicate evaluates to true for each entry."""
@ -250,6 +262,7 @@ class takewhile(Generic[_T]):
def tee(iterable: Iterable[_T], n: int = 2, /) -> tuple[Iterator[_T], ...]: def tee(iterable: Iterable[_T], n: int = 2, /) -> tuple[Iterator[_T], ...]:
"""Returns a tuple of n independent iterators.""" """Returns a tuple of n independent iterators."""
@disjoint_base
class zip_longest(Generic[_T_co]): class zip_longest(Generic[_T_co]):
"""Return a zip_longest object whose .__next__() method returns a tuple where """Return a zip_longest object whose .__next__() method returns a tuple where
the i-th element comes from the i-th iterable argument. The .__next__() the i-th element comes from the i-th iterable argument. The .__next__()
@ -339,6 +352,7 @@ class zip_longest(Generic[_T_co]):
def __next__(self) -> _T_co: def __next__(self) -> _T_co:
"""Implement next(self).""" """Implement next(self)."""
@disjoint_base
class product(Generic[_T_co]): class product(Generic[_T_co]):
"""Cartesian product of input iterables. Equivalent to nested for-loops. """Cartesian product of input iterables. Equivalent to nested for-loops.
@ -442,6 +456,7 @@ class product(Generic[_T_co]):
def __next__(self) -> _T_co: def __next__(self) -> _T_co:
"""Implement next(self).""" """Implement next(self)."""
@disjoint_base
class permutations(Generic[_T_co]): class permutations(Generic[_T_co]):
"""Return successive r-length permutations of elements in the iterable. """Return successive r-length permutations of elements in the iterable.
@ -464,6 +479,7 @@ class permutations(Generic[_T_co]):
def __next__(self) -> _T_co: def __next__(self) -> _T_co:
"""Implement next(self).""" """Implement next(self)."""
@disjoint_base
class combinations(Generic[_T_co]): class combinations(Generic[_T_co]):
"""Return successive r-length combinations of elements in the iterable. """Return successive r-length combinations of elements in the iterable.
@ -486,6 +502,7 @@ class combinations(Generic[_T_co]):
def __next__(self) -> _T_co: def __next__(self) -> _T_co:
"""Implement next(self).""" """Implement next(self)."""
@disjoint_base
class combinations_with_replacement(Generic[_T_co]): class combinations_with_replacement(Generic[_T_co]):
"""Return successive r-length combinations of elements in the iterable allowing individual elements to have successive repeats. """Return successive r-length combinations of elements in the iterable allowing individual elements to have successive repeats.
@ -509,6 +526,7 @@ class combinations_with_replacement(Generic[_T_co]):
"""Implement next(self).""" """Implement next(self)."""
if sys.version_info >= (3, 10): if sys.version_info >= (3, 10):
@disjoint_base
class pairwise(Generic[_T_co]): class pairwise(Generic[_T_co]):
"""Return an iterator of overlapping pairs taken from the input iterator. """Return an iterator of overlapping pairs taken from the input iterator.
@ -523,6 +541,7 @@ if sys.version_info >= (3, 10):
"""Implement next(self).""" """Implement next(self)."""
if sys.version_info >= (3, 12): if sys.version_info >= (3, 12):
@disjoint_base
class batched(Generic[_T_co]): class batched(Generic[_T_co]):
"""Batch data into tuples of length n. The last batch may be shorter than n. """Batch data into tuples of length n. The last batch may be shorter than n.

View file

@ -17,7 +17,6 @@ It will also support lambdas:
lambda (x): x + y -> lambda x: x + y lambda (x): x + y -> lambda x: x + y
""" """
from _typeshed import Incomplete
from typing import ClassVar, Literal from typing import ClassVar, Literal
from .. import fixer_base from .. import fixer_base
@ -32,5 +31,5 @@ class FixTupleParams(fixer_base.BaseFix):
def simplify_args(node): ... def simplify_args(node): ...
def find_params(node): ... def find_params(node): ...
def map_to_index(param_list, prefix=..., d: Incomplete | None = ...): ... def map_to_index(param_list, prefix=[], d=None): ...
def tuple_name(param_list): ... def tuple_name(param_list): ...

View file

@ -15,7 +15,7 @@ from configparser import RawConfigParser
from re import Pattern from re import Pattern
from threading import Thread from threading import Thread
from typing import IO, Any, Final, Literal, SupportsIndex, TypedDict, overload, type_check_only from typing import IO, Any, Final, Literal, SupportsIndex, TypedDict, overload, type_check_only
from typing_extensions import Required, TypeAlias from typing_extensions import Required, TypeAlias, disjoint_base
from . import Filter, Filterer, Formatter, Handler, Logger, _FilterType, _FormatStyle, _Level from . import Filter, Filterer, Formatter, Handler, Logger, _FilterType, _FormatStyle, _Level
@ -155,13 +155,24 @@ class ConvertingList(list[Any], ConvertingMixin): # undocumented
def __getitem__(self, key: slice) -> Any: ... def __getitem__(self, key: slice) -> Any: ...
def pop(self, idx: SupportsIndex = -1) -> Any: ... def pop(self, idx: SupportsIndex = -1) -> Any: ...
class ConvertingTuple(tuple[Any, ...], ConvertingMixin): # undocumented if sys.version_info >= (3, 12):
"""A converting tuple wrapper.""" class ConvertingTuple(tuple[Any, ...], ConvertingMixin): # undocumented
"""A converting tuple wrapper."""
@overload @overload
def __getitem__(self, key: SupportsIndex) -> Any: ... def __getitem__(self, key: SupportsIndex) -> Any: ...
@overload @overload
def __getitem__(self, key: slice) -> Any: ... def __getitem__(self, key: slice) -> Any: ...
else:
@disjoint_base
class ConvertingTuple(tuple[Any, ...], ConvertingMixin): # undocumented
"""A converting tuple wrapper."""
@overload
def __getitem__(self, key: SupportsIndex) -> Any: ...
@overload
def __getitem__(self, key: slice) -> Any: ...
class BaseConfigurator: class BaseConfigurator:
""" """

View file

@ -3,7 +3,7 @@ import sys
from _typeshed import ReadableBuffer, Unused from _typeshed import ReadableBuffer, Unused
from collections.abc import Iterator from collections.abc import Iterator
from typing import Final, Literal, NoReturn, overload from typing import Final, Literal, NoReturn, overload
from typing_extensions import Self from typing_extensions import Self, disjoint_base
ACCESS_DEFAULT: Final = 0 ACCESS_DEFAULT: Final = 0
ACCESS_READ: Final = 1 ACCESS_READ: Final = 1
@ -31,6 +31,7 @@ if sys.platform != "win32":
PAGESIZE: Final[int] PAGESIZE: Final[int]
@disjoint_base
class mmap: class mmap:
"""Windows: mmap(fileno, length[, tagname[, access[, offset]]]) """Windows: mmap(fileno, length[, tagname[, access[, offset]]])
@ -56,7 +57,7 @@ class mmap:
""" """
if sys.platform == "win32": if sys.platform == "win32":
def __init__(self, fileno: int, length: int, tagname: str | None = None, access: int = 0, offset: int = 0) -> None: ... def __new__(self, fileno: int, length: int, tagname: str | None = None, access: int = 0, offset: int = 0) -> Self: ...
else: else:
if sys.version_info >= (3, 13): if sys.version_info >= (3, 13):
def __new__( def __new__(

View file

@ -1746,7 +1746,7 @@ def getcwd() -> str:
def getcwdb() -> bytes: def getcwdb() -> bytes:
"""Return a bytes string representing the current working directory.""" """Return a bytes string representing the current working directory."""
def chmod(path: FileDescriptorOrPath, mode: int, *, dir_fd: int | None = None, follow_symlinks: bool = ...) -> None: def chmod(path: FileDescriptorOrPath, mode: int, *, dir_fd: int | None = None, follow_symlinks: bool = True) -> None:
"""Change the access permissions of a file. """Change the access permissions of a file.
path path

View file

@ -292,6 +292,7 @@ class Path(PurePath):
__slots__ = () __slots__ = ()
else: else:
__slots__ = ("_accessor",) __slots__ = ("_accessor",)
if sys.version_info >= (3, 12): if sys.version_info >= (3, 12):
def __new__(cls, *args: StrPath, **kwargs: Unused) -> Self: ... # pyright: ignore[reportInconsistentConstructor] def __new__(cls, *args: StrPath, **kwargs: Unused) -> Self: ... # pyright: ignore[reportInconsistentConstructor]
else: else:

View file

@ -606,23 +606,40 @@ class Pdb(Bdb, Cmd):
print anything, you will see no sign that the breakpoint was print anything, you will see no sign that the breakpoint was
reached. reached.
""" """
if sys.version_info >= (3, 14):
def do_break(self, arg: str, temporary: bool = False) -> bool | None:
"""b(reak) [ ([filename:]lineno | function) [, condition] ]
def do_break(self, arg: str, temporary: bool = ...) -> bool | None: Without argument, list all breaks.
"""b(reak) [ ([filename:]lineno | function) [, condition] ]
Without argument, list all breaks. With a line number argument, set a break at this line in the
current file. With a function name, set a break at the first
executable line of that function. If a second argument is
present, it is a string specifying an expression which must
evaluate to true before the breakpoint is honored.
With a line number argument, set a break at this line in the The line number may be prefixed with a filename and a colon,
current file. With a function name, set a break at the first to specify a breakpoint in another file (probably one that
executable line of that function. If a second argument is hasn't been loaded yet). The file is searched for on
present, it is a string specifying an expression which must sys.path; the .py suffix may be omitted.
evaluate to true before the breakpoint is honored. """
else:
def do_break(self, arg: str, temporary: bool | Literal[0, 1] = 0) -> bool | None:
"""b(reak) [ ([filename:]lineno | function) [, condition] ]
The line number may be prefixed with a filename and a colon, Without argument, list all breaks.
to specify a breakpoint in another file (probably one that
hasn't been loaded yet). The file is searched for on With a line number argument, set a break at this line in the
sys.path; the .py suffix may be omitted. current file. With a function name, set a break at the first
""" executable line of that function. If a second argument is
present, it is a string specifying an expression which must
evaluate to true before the breakpoint is honored.
The line number may be prefixed with a filename and a colon,
to specify a breakpoint in another file (probably one that
hasn't been loaded yet). The file is searched for on
sys.path; the .py suffix may be omitted.
"""
def do_tbreak(self, arg: str) -> bool | None: def do_tbreak(self, arg: str) -> bool | None:
"""tbreak [ ([filename:]lineno | function) [, condition] ] """tbreak [ ([filename:]lineno | function) [, condition] ]

View file

@ -9,7 +9,7 @@ format is usable as part of a filename.
import sys import sys
from typing import NamedTuple, type_check_only from typing import NamedTuple, type_check_only
from typing_extensions import Self, deprecated from typing_extensions import Self, deprecated, disjoint_base
def libc_ver(executable: str | None = None, lib: str = "", version: str = "", chunksize: int = 16384) -> tuple[str, str]: def libc_ver(executable: str | None = None, lib: str = "", version: str = "", chunksize: int = 16384) -> tuple[str, str]:
"""Tries to determine the libc version that the file executable """Tries to determine the libc version that the file executable
@ -123,22 +123,41 @@ class _uname_result_base(NamedTuple):
# uname_result emulates a 6-field named tuple, but the processor field # uname_result emulates a 6-field named tuple, but the processor field
# is lazily evaluated rather than being passed in to the constructor. # is lazily evaluated rather than being passed in to the constructor.
class uname_result(_uname_result_base): if sys.version_info >= (3, 12):
""" class uname_result(_uname_result_base):
A uname_result that's largely compatible with a """
simple namedtuple except that 'processor' is A uname_result that's largely compatible with a
resolved late and cached to avoid calling "uname" simple namedtuple except that 'processor' is
except when needed. resolved late and cached to avoid calling "uname"
""" except when needed.
"""
if sys.version_info >= (3, 10):
__match_args__ = ("system", "node", "release", "version", "machine") # pyright: ignore[reportAssignmentType] __match_args__ = ("system", "node", "release", "version", "machine") # pyright: ignore[reportAssignmentType]
def __new__(_cls, system: str, node: str, release: str, version: str, machine: str) -> Self: def __new__(_cls, system: str, node: str, release: str, version: str, machine: str) -> Self:
"""Create new instance of uname_result_base(system, node, release, version, machine)""" """Create new instance of uname_result_base(system, node, release, version, machine)"""
@property @property
def processor(self) -> str: ... def processor(self) -> str: ...
else:
@disjoint_base
class uname_result(_uname_result_base):
"""
A uname_result that's largely compatible with a
simple namedtuple except that 'processor' is
resolved late and cached to avoid calling "uname"
except when needed.
"""
if sys.version_info >= (3, 10):
__match_args__ = ("system", "node", "release", "version", "machine") # pyright: ignore[reportAssignmentType]
def __new__(_cls, system: str, node: str, release: str, version: str, machine: str) -> Self:
"""Create new instance of uname_result_base(system, node, release, version, machine)"""
@property
def processor(self) -> str: ...
def uname() -> uname_result: def uname() -> uname_result:
"""Fairly portable uname interface. Returns a tuple """Fairly portable uname interface. Returns a tuple

View file

@ -52,6 +52,7 @@ from _typeshed import SupportsLenAndGetItem
from collections.abc import Callable, Iterable, MutableSequence, Sequence, Set as AbstractSet from collections.abc import Callable, Iterable, MutableSequence, Sequence, Set as AbstractSet
from fractions import Fraction from fractions import Fraction
from typing import Any, ClassVar, NoReturn, TypeVar from typing import Any, ClassVar, NoReturn, TypeVar
from typing_extensions import Self
__all__ = [ __all__ = [
"Random", "Random",
@ -109,6 +110,10 @@ class Random(_random.Random):
# Using other `seed` types is deprecated since 3.9 and removed in 3.11 # Using other `seed` types is deprecated since 3.9 and removed in 3.11
# Ignore Y041, since random.seed doesn't treat int like a float subtype. Having an explicit # Ignore Y041, since random.seed doesn't treat int like a float subtype. Having an explicit
# int better documents conventional usage of random.seed. # int better documents conventional usage of random.seed.
if sys.version_info < (3, 10):
# this is a workaround for pyright correctly flagging an inconsistent inherited constructor, see #14624
def __new__(cls, x: int | float | str | bytes | bytearray | None = None) -> Self: ... # noqa: Y041
def seed(self, a: int | float | str | bytes | bytearray | None = None, version: int = 2) -> None: # type: ignore[override] # noqa: Y041 def seed(self, a: int | float | str | bytes | bytearray | None = None, version: int = 2) -> None: # type: ignore[override] # noqa: Y041
"""Initialize internal state from a seed. """Initialize internal state from a seed.

View file

@ -207,7 +207,7 @@ if sys.platform == "linux":
the maximum number of monitored events. the maximum number of monitored events.
""" """
def __init__(self, sizehint: int = ..., flags: int = ...) -> None: ... def __new__(self, sizehint: int = ..., flags: int = ...) -> Self: ...
def __enter__(self) -> Self: ... def __enter__(self) -> Self: ...
def __exit__( def __exit__(
self, self,

View file

@ -97,7 +97,7 @@ from sqlite3.dbapi2 import (
) )
from types import TracebackType from types import TracebackType
from typing import Any, Literal, Protocol, SupportsIndex, TypeVar, final, overload, type_check_only from typing import Any, Literal, Protocol, SupportsIndex, TypeVar, final, overload, type_check_only
from typing_extensions import Self, TypeAlias from typing_extensions import Self, TypeAlias, disjoint_base
if sys.version_info < (3, 14): if sys.version_info < (3, 14):
from sqlite3.dbapi2 import version_info as version_info from sqlite3.dbapi2 import version_info as version_info
@ -302,6 +302,7 @@ class OperationalError(DatabaseError): ...
class ProgrammingError(DatabaseError): ... class ProgrammingError(DatabaseError): ...
class Warning(Exception): ... class Warning(Exception): ...
@disjoint_base
class Connection: class Connection:
"""SQLite database connection object.""" """SQLite database connection object."""
@ -610,6 +611,7 @@ class Connection:
If there was any exception, a rollback takes place; otherwise we commit. If there was any exception, a rollback takes place; otherwise we commit.
""" """
@disjoint_base
class Cursor: class Cursor:
"""SQLite database cursor class.""" """SQLite database cursor class."""
@ -669,6 +671,7 @@ class PrepareProtocol:
def __init__(self, *args: object, **kwargs: object) -> None: ... def __init__(self, *args: object, **kwargs: object) -> None: ...
@disjoint_base
class Row(Sequence[Any]): class Row(Sequence[Any]):
def __new__(cls, cursor: Cursor, data: tuple[Any, ...], /) -> Self: ... def __new__(cls, cursor: Cursor, data: tuple[Any, ...], /) -> Self: ...
def keys(self) -> list[str]: def keys(self) -> list[str]:

View file

@ -3,15 +3,22 @@
import sys import sys
from re import error as error from re import error as error
from typing import Final from typing import Final
from typing_extensions import Self from typing_extensions import Self, disjoint_base
MAXGROUPS: Final[int] MAXGROUPS: Final[int]
MAGIC: Final[int] MAGIC: Final[int]
class _NamedIntConstant(int): if sys.version_info >= (3, 12):
name: str class _NamedIntConstant(int):
def __new__(cls, value: int, name: str) -> Self: ... name: str
def __new__(cls, value: int, name: str) -> Self: ...
else:
@disjoint_base
class _NamedIntConstant(int):
name: str
def __new__(cls, value: int, name: str) -> Self: ...
MAXREPEAT: Final[_NamedIntConstant] MAXREPEAT: Final[_NamedIntConstant]
OPCODES: list[_NamedIntConstant] OPCODES: list[_NamedIntConstant]

View file

@ -157,7 +157,7 @@ if sys.version_info >= (3, 11):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
capture_output: bool = False, capture_output: bool = False,
check: bool = False, check: bool = False,
@ -220,7 +220,7 @@ if sys.version_info >= (3, 11):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
capture_output: bool = False, capture_output: bool = False,
check: bool = False, check: bool = False,
@ -254,7 +254,7 @@ if sys.version_info >= (3, 11):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
capture_output: bool = False, capture_output: bool = False,
check: bool = False, check: bool = False,
@ -289,7 +289,7 @@ if sys.version_info >= (3, 11):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
# where the *real* keyword only args start # where the *real* keyword only args start
capture_output: bool = False, capture_output: bool = False,
check: bool = False, check: bool = False,
@ -323,7 +323,7 @@ if sys.version_info >= (3, 11):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
capture_output: bool = False, capture_output: bool = False,
check: bool = False, check: bool = False,
@ -357,7 +357,7 @@ if sys.version_info >= (3, 11):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
capture_output: bool = False, capture_output: bool = False,
check: bool = False, check: bool = False,
@ -394,7 +394,7 @@ elif sys.version_info >= (3, 10):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
capture_output: bool = False, capture_output: bool = False,
check: bool = False, check: bool = False,
@ -456,7 +456,7 @@ elif sys.version_info >= (3, 10):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
capture_output: bool = False, capture_output: bool = False,
check: bool = False, check: bool = False,
@ -489,7 +489,7 @@ elif sys.version_info >= (3, 10):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
capture_output: bool = False, capture_output: bool = False,
check: bool = False, check: bool = False,
@ -523,7 +523,7 @@ elif sys.version_info >= (3, 10):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
# where the *real* keyword only args start # where the *real* keyword only args start
capture_output: bool = False, capture_output: bool = False,
check: bool = False, check: bool = False,
@ -556,7 +556,7 @@ elif sys.version_info >= (3, 10):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
capture_output: bool = False, capture_output: bool = False,
check: bool = False, check: bool = False,
@ -589,7 +589,7 @@ elif sys.version_info >= (3, 10):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
capture_output: bool = False, capture_output: bool = False,
check: bool = False, check: bool = False,
@ -625,7 +625,7 @@ else:
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
capture_output: bool = False, capture_output: bool = False,
check: bool = False, check: bool = False,
@ -685,7 +685,7 @@ else:
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
capture_output: bool = False, capture_output: bool = False,
check: bool = False, check: bool = False,
@ -717,7 +717,7 @@ else:
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
capture_output: bool = False, capture_output: bool = False,
check: bool = False, check: bool = False,
@ -750,7 +750,7 @@ else:
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
# where the *real* keyword only args start # where the *real* keyword only args start
capture_output: bool = False, capture_output: bool = False,
check: bool = False, check: bool = False,
@ -782,7 +782,7 @@ else:
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
capture_output: bool = False, capture_output: bool = False,
check: bool = False, check: bool = False,
@ -814,7 +814,7 @@ else:
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
capture_output: bool = False, capture_output: bool = False,
check: bool = False, check: bool = False,
@ -849,7 +849,7 @@ if sys.version_info >= (3, 11):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
encoding: str | None = None, encoding: str | None = None,
timeout: float | None = None, timeout: float | None = None,
@ -888,7 +888,7 @@ elif sys.version_info >= (3, 10):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
encoding: str | None = None, encoding: str | None = None,
timeout: float | None = None, timeout: float | None = None,
@ -925,7 +925,7 @@ else:
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
encoding: str | None = None, encoding: str | None = None,
timeout: float | None = None, timeout: float | None = None,
@ -963,8 +963,8 @@ if sys.version_info >= (3, 11):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
timeout: float | None = ..., timeout: float | None = None,
*, *,
encoding: str | None = None, encoding: str | None = None,
text: bool | None = None, text: bool | None = None,
@ -1004,8 +1004,8 @@ elif sys.version_info >= (3, 10):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
timeout: float | None = ..., timeout: float | None = None,
*, *,
encoding: str | None = None, encoding: str | None = None,
text: bool | None = None, text: bool | None = None,
@ -1043,8 +1043,8 @@ else:
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
timeout: float | None = ..., timeout: float | None = None,
*, *,
encoding: str | None = None, encoding: str | None = None,
text: bool | None = None, text: bool | None = None,
@ -1082,10 +1082,10 @@ if sys.version_info >= (3, 11):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
timeout: float | None = None, timeout: float | None = None,
input: _InputString | None = ..., input: _InputString | None = None,
encoding: str | None = None, encoding: str | None = None,
errors: str | None = None, errors: str | None = None,
text: Literal[True], text: Literal[True],
@ -1148,10 +1148,10 @@ if sys.version_info >= (3, 11):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
timeout: float | None = None, timeout: float | None = None,
input: _InputString | None = ..., input: _InputString | None = None,
encoding: str, encoding: str,
errors: str | None = None, errors: str | None = None,
text: bool | None = None, text: bool | None = None,
@ -1179,10 +1179,10 @@ if sys.version_info >= (3, 11):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
timeout: float | None = None, timeout: float | None = None,
input: _InputString | None = ..., input: _InputString | None = None,
encoding: str | None = None, encoding: str | None = None,
errors: str, errors: str,
text: bool | None = None, text: bool | None = None,
@ -1211,10 +1211,10 @@ if sys.version_info >= (3, 11):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
# where the real keyword only ones start # where the real keyword only ones start
timeout: float | None = None, timeout: float | None = None,
input: _InputString | None = ..., input: _InputString | None = None,
encoding: str | None = None, encoding: str | None = None,
errors: str | None = None, errors: str | None = None,
text: bool | None = None, text: bool | None = None,
@ -1242,10 +1242,10 @@ if sys.version_info >= (3, 11):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
timeout: float | None = None, timeout: float | None = None,
input: _InputString | None = ..., input: _InputString | None = None,
encoding: None = None, encoding: None = None,
errors: None = None, errors: None = None,
text: Literal[False] | None = None, text: Literal[False] | None = None,
@ -1273,10 +1273,10 @@ if sys.version_info >= (3, 11):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
timeout: float | None = None, timeout: float | None = None,
input: _InputString | None = ..., input: _InputString | None = None,
encoding: str | None = None, encoding: str | None = None,
errors: str | None = None, errors: str | None = None,
text: bool | None = None, text: bool | None = None,
@ -1307,10 +1307,10 @@ elif sys.version_info >= (3, 10):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
timeout: float | None = None, timeout: float | None = None,
input: _InputString | None = ..., input: _InputString | None = None,
encoding: str | None = None, encoding: str | None = None,
errors: str | None = None, errors: str | None = None,
text: Literal[True], text: Literal[True],
@ -1372,10 +1372,10 @@ elif sys.version_info >= (3, 10):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
timeout: float | None = None, timeout: float | None = None,
input: _InputString | None = ..., input: _InputString | None = None,
encoding: str, encoding: str,
errors: str | None = None, errors: str | None = None,
text: bool | None = None, text: bool | None = None,
@ -1402,10 +1402,10 @@ elif sys.version_info >= (3, 10):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
timeout: float | None = None, timeout: float | None = None,
input: _InputString | None = ..., input: _InputString | None = None,
encoding: str | None = None, encoding: str | None = None,
errors: str, errors: str,
text: bool | None = None, text: bool | None = None,
@ -1433,10 +1433,10 @@ elif sys.version_info >= (3, 10):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
# where the real keyword only ones start # where the real keyword only ones start
timeout: float | None = None, timeout: float | None = None,
input: _InputString | None = ..., input: _InputString | None = None,
encoding: str | None = None, encoding: str | None = None,
errors: str | None = None, errors: str | None = None,
text: bool | None = None, text: bool | None = None,
@ -1463,10 +1463,10 @@ elif sys.version_info >= (3, 10):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
timeout: float | None = None, timeout: float | None = None,
input: _InputString | None = ..., input: _InputString | None = None,
encoding: None = None, encoding: None = None,
errors: None = None, errors: None = None,
text: Literal[False] | None = None, text: Literal[False] | None = None,
@ -1493,10 +1493,10 @@ elif sys.version_info >= (3, 10):
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
timeout: float | None = None, timeout: float | None = None,
input: _InputString | None = ..., input: _InputString | None = None,
encoding: str | None = None, encoding: str | None = None,
errors: str | None = None, errors: str | None = None,
text: bool | None = None, text: bool | None = None,
@ -1525,10 +1525,10 @@ else:
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
timeout: float | None = None, timeout: float | None = None,
input: _InputString | None = ..., input: _InputString | None = None,
encoding: str | None = None, encoding: str | None = None,
errors: str | None = None, errors: str | None = None,
text: Literal[True], text: Literal[True],
@ -1589,10 +1589,10 @@ else:
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
timeout: float | None = None, timeout: float | None = None,
input: _InputString | None = ..., input: _InputString | None = None,
encoding: str, encoding: str,
errors: str | None = None, errors: str | None = None,
text: bool | None = None, text: bool | None = None,
@ -1618,10 +1618,10 @@ else:
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
timeout: float | None = None, timeout: float | None = None,
input: _InputString | None = ..., input: _InputString | None = None,
encoding: str | None = None, encoding: str | None = None,
errors: str, errors: str,
text: bool | None = None, text: bool | None = None,
@ -1648,10 +1648,10 @@ else:
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
# where the real keyword only ones start # where the real keyword only ones start
timeout: float | None = None, timeout: float | None = None,
input: _InputString | None = ..., input: _InputString | None = None,
encoding: str | None = None, encoding: str | None = None,
errors: str | None = None, errors: str | None = None,
text: bool | None = None, text: bool | None = None,
@ -1677,10 +1677,10 @@ else:
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
timeout: float | None = None, timeout: float | None = None,
input: _InputString | None = ..., input: _InputString | None = None,
encoding: None = None, encoding: None = None,
errors: None = None, errors: None = None,
text: Literal[False] | None = None, text: Literal[False] | None = None,
@ -1706,10 +1706,10 @@ else:
creationflags: int = 0, creationflags: int = 0,
restore_signals: bool = True, restore_signals: bool = True,
start_new_session: bool = False, start_new_session: bool = False,
pass_fds: Collection[int] = ..., pass_fds: Collection[int] = (),
*, *,
timeout: float | None = None, timeout: float | None = None,
input: _InputString | None = ..., input: _InputString | None = None,
encoding: str | None = None, encoding: str | None = None,
errors: str | None = None, errors: str | None = None,
text: bool | None = None, text: bool | None = None,

View file

@ -1053,6 +1053,28 @@ class TarInfo:
usually created internally. usually created internally.
""" """
__slots__ = (
"name",
"mode",
"uid",
"gid",
"size",
"mtime",
"chksum",
"type",
"linkname",
"uname",
"gname",
"devmajor",
"devminor",
"offset",
"offset_data",
"pax_headers",
"sparse",
"_tarfile",
"_sparse_structs",
"_link_target",
)
name: str name: str
path: str path: str
size: int size: int

View file

@ -38,7 +38,7 @@ from tkinter.constants import *
from tkinter.font import _FontDescription from tkinter.font import _FontDescription
from types import GenericAlias, TracebackType from types import GenericAlias, TracebackType
from typing import Any, ClassVar, Final, Generic, Literal, NamedTuple, Protocol, TypedDict, TypeVar, overload, type_check_only from typing import Any, ClassVar, Final, Generic, Literal, NamedTuple, Protocol, TypedDict, TypeVar, overload, type_check_only
from typing_extensions import TypeAlias, TypeVarTuple, Unpack, deprecated from typing_extensions import TypeAlias, TypeVarTuple, Unpack, deprecated, disjoint_base
if sys.version_info >= (3, 11): if sys.version_info >= (3, 11):
from enum import StrEnum from enum import StrEnum
@ -230,7 +230,11 @@ if sys.version_info >= (3, 11):
releaselevel: str releaselevel: str
serial: int serial: int
class _VersionInfoType(_VersionInfoTypeBase): ... if sys.version_info >= (3, 12):
class _VersionInfoType(_VersionInfoTypeBase): ...
else:
@disjoint_base
class _VersionInfoType(_VersionInfoTypeBase): ...
if sys.version_info >= (3, 11): if sys.version_info >= (3, 11):
class EventType(StrEnum): class EventType(StrEnum):
@ -5683,7 +5687,7 @@ class Text(Widget, XView, YView):
def image_configure( def image_configure(
self, self,
index: _TextIndex, index: _TextIndex,
cnf: dict[str, Any] | None = {}, cnf: dict[str, Any] | None = None,
*, *,
align: Literal["baseline", "bottom", "center", "top"] = ..., align: Literal["baseline", "bottom", "center", "top"] = ...,
image: _ImageSpec = ..., image: _ImageSpec = ...,

View file

@ -26,7 +26,7 @@ from collections.abc import Callable, Generator, Iterable, Sequence
from re import Pattern from re import Pattern
from token import * from token import *
from typing import Any, Final, NamedTuple, TextIO, type_check_only from typing import Any, Final, NamedTuple, TextIO, type_check_only
from typing_extensions import TypeAlias from typing_extensions import TypeAlias, disjoint_base
if sys.version_info < (3, 12): if sys.version_info < (3, 12):
# Avoid double assignment to Final name by imports, which pyright objects to. # Avoid double assignment to Final name by imports, which pyright objects to.
@ -137,9 +137,16 @@ class _TokenInfo(NamedTuple):
end: _Position end: _Position
line: str line: str
class TokenInfo(_TokenInfo): if sys.version_info >= (3, 12):
@property class TokenInfo(_TokenInfo):
def exact_type(self) -> int: ... @property
def exact_type(self) -> int: ...
else:
@disjoint_base
class TokenInfo(_TokenInfo):
@property
def exact_type(self) -> int: ...
# Backwards compatible tokens can be sequences of a shorter length too # Backwards compatible tokens can be sequences of a shorter length too
_Token: TypeAlias = TokenInfo | Sequence[int | str | _Position] _Token: TypeAlias = TokenInfo | Sequence[int | str | _Position]

View file

@ -81,7 +81,7 @@ from collections.abc import Callable, Generator, Sequence
from contextlib import contextmanager from contextlib import contextmanager
from tkinter import Canvas, Frame, Misc, PhotoImage, Scrollbar from tkinter import Canvas, Frame, Misc, PhotoImage, Scrollbar
from typing import Any, ClassVar, Literal, TypedDict, overload, type_check_only from typing import Any, ClassVar, Literal, TypedDict, overload, type_check_only
from typing_extensions import Self, TypeAlias, deprecated from typing_extensions import Self, TypeAlias, deprecated, disjoint_base
__all__ = [ __all__ = [
"ScrolledCanvas", "ScrolledCanvas",
@ -240,33 +240,64 @@ class _PenState(TypedDict):
_Speed: TypeAlias = str | float _Speed: TypeAlias = str | float
_PolygonCoords: TypeAlias = Sequence[tuple[float, float]] _PolygonCoords: TypeAlias = Sequence[tuple[float, float]]
class Vec2D(tuple[float, float]): if sys.version_info >= (3, 12):
"""A 2 dimensional vector class, used as a helper class class Vec2D(tuple[float, float]):
for implementing turtle graphics. """A 2 dimensional vector class, used as a helper class
May be useful for turtle graphics programs also. for implementing turtle graphics.
Derived from tuple, so a vector is a tuple! May be useful for turtle graphics programs also.
Derived from tuple, so a vector is a tuple!
Provides (for a, b vectors, k number): Provides (for a, b vectors, k number):
a+b vector addition a+b vector addition
a-b vector subtraction a-b vector subtraction
a*b inner product a*b inner product
k*a and a*k multiplication with scalar k*a and a*k multiplication with scalar
|a| absolute value of a |a| absolute value of a
a.rotate(angle) rotation a.rotate(angle) rotation
""" """
def __new__(cls, x: float, y: float) -> Self: ... def __new__(cls, x: float, y: float) -> Self: ...
def __add__(self, other: tuple[float, float]) -> Vec2D: ... # type: ignore[override] def __add__(self, other: tuple[float, float]) -> Vec2D: ... # type: ignore[override]
@overload # type: ignore[override] @overload # type: ignore[override]
def __mul__(self, other: Vec2D) -> float: ... def __mul__(self, other: Vec2D) -> float: ...
@overload @overload
def __mul__(self, other: float) -> Vec2D: ... def __mul__(self, other: float) -> Vec2D: ...
def __rmul__(self, other: float) -> Vec2D: ... # type: ignore[override] def __rmul__(self, other: float) -> Vec2D: ... # type: ignore[override]
def __sub__(self, other: tuple[float, float]) -> Vec2D: ... def __sub__(self, other: tuple[float, float]) -> Vec2D: ...
def __neg__(self) -> Vec2D: ... def __neg__(self) -> Vec2D: ...
def __abs__(self) -> float: ... def __abs__(self) -> float: ...
def rotate(self, angle: float) -> Vec2D: def rotate(self, angle: float) -> Vec2D:
"""rotate self counterclockwise by angle""" """rotate self counterclockwise by angle"""
else:
@disjoint_base
class Vec2D(tuple[float, float]):
"""A 2 dimensional vector class, used as a helper class
for implementing turtle graphics.
May be useful for turtle graphics programs also.
Derived from tuple, so a vector is a tuple!
Provides (for a, b vectors, k number):
a+b vector addition
a-b vector subtraction
a*b inner product
k*a and a*k multiplication with scalar
|a| absolute value of a
a.rotate(angle) rotation
"""
def __new__(cls, x: float, y: float) -> Self: ...
def __add__(self, other: tuple[float, float]) -> Vec2D: ... # type: ignore[override]
@overload # type: ignore[override]
def __mul__(self, other: Vec2D) -> float: ...
@overload
def __mul__(self, other: float) -> Vec2D: ...
def __rmul__(self, other: float) -> Vec2D: ... # type: ignore[override]
def __sub__(self, other: tuple[float, float]) -> Vec2D: ...
def __neg__(self) -> Vec2D: ...
def __abs__(self) -> float: ...
def rotate(self, angle: float) -> Vec2D:
"""rotate self counterclockwise by angle"""
# Does not actually inherit from Canvas, but dynamically gets all methods of Canvas # Does not actually inherit from Canvas, but dynamically gets all methods of Canvas
class ScrolledCanvas(Canvas, Frame): # type: ignore[misc] class ScrolledCanvas(Canvas, Frame): # type: ignore[misc]

View file

@ -21,7 +21,7 @@ from collections.abc import (
) )
from importlib.machinery import ModuleSpec from importlib.machinery import ModuleSpec
from typing import Any, ClassVar, Literal, TypeVar, final, overload from typing import Any, ClassVar, Literal, TypeVar, final, overload
from typing_extensions import ParamSpec, Self, TypeAliasType, TypeVarTuple, deprecated from typing_extensions import ParamSpec, Self, TypeAliasType, TypeVarTuple, deprecated, disjoint_base
if sys.version_info >= (3, 14): if sys.version_info >= (3, 14):
from _typeshed import AnnotateFunc from _typeshed import AnnotateFunc
@ -384,23 +384,42 @@ class MappingProxyType(Mapping[_KT, _VT_co]):
def __ror__(self, value: Mapping[_T1, _T2], /) -> dict[_KT | _T1, _VT_co | _T2]: def __ror__(self, value: Mapping[_T1, _T2], /) -> dict[_KT | _T1, _VT_co | _T2]:
"""Return value|self.""" """Return value|self."""
class SimpleNamespace: if sys.version_info >= (3, 12):
"""A simple attribute-based namespace.""" @disjoint_base
class SimpleNamespace:
"""A simple attribute-based namespace."""
__hash__: ClassVar[None] # type: ignore[assignment] __hash__: ClassVar[None] # type: ignore[assignment]
if sys.version_info >= (3, 13): if sys.version_info >= (3, 13):
def __init__(self, mapping_or_iterable: Mapping[str, Any] | Iterable[tuple[str, Any]] = (), /, **kwargs: Any) -> None: ... def __init__(
else: self, mapping_or_iterable: Mapping[str, Any] | Iterable[tuple[str, Any]] = (), /, **kwargs: Any
) -> None: ...
else:
def __init__(self, **kwargs: Any) -> None: ...
def __eq__(self, value: object, /) -> bool: ...
def __getattribute__(self, name: str, /) -> Any: ...
def __setattr__(self, name: str, value: Any, /) -> None: ...
def __delattr__(self, name: str, /) -> None: ...
if sys.version_info >= (3, 13):
def __replace__(self, **kwargs: Any) -> Self:
"""Return a copy of the namespace object with new values for the specified attributes."""
else:
class SimpleNamespace:
"""A simple attribute-based namespace.
SimpleNamespace(**kwargs)
"""
__hash__: ClassVar[None] # type: ignore[assignment]
def __init__(self, **kwargs: Any) -> None: ... def __init__(self, **kwargs: Any) -> None: ...
def __eq__(self, value: object, /) -> bool: ...
def __getattribute__(self, name: str, /) -> Any: ...
def __setattr__(self, name: str, value: Any, /) -> None: ...
def __delattr__(self, name: str, /) -> None: ...
def __eq__(self, value: object, /) -> bool: ... @disjoint_base
def __getattribute__(self, name: str, /) -> Any: ...
def __setattr__(self, name: str, value: Any, /) -> None: ...
def __delattr__(self, name: str, /) -> None: ...
if sys.version_info >= (3, 13):
def __replace__(self, **kwargs: Any) -> Self:
"""Return a copy of the namespace object with new values for the specified attributes."""
class ModuleType: class ModuleType:
"""Create a module object. """Create a module object.
@ -881,7 +900,7 @@ def coroutine(func: Callable[_P, Generator[Any, Any, _R]]) -> Callable[_P, Await
@overload @overload
def coroutine(func: _Fn) -> _Fn: ... def coroutine(func: _Fn) -> _Fn: ...
@disjoint_base
class GenericAlias: class GenericAlias:
"""Represent a PEP 585 generic type """Represent a PEP 585 generic type

View file

@ -1204,6 +1204,7 @@ class MutableSet(AbstractSet[_T]):
def __isub__(self, it: AbstractSet[Any]) -> typing_extensions.Self: ... def __isub__(self, it: AbstractSet[Any]) -> typing_extensions.Self: ...
class MappingView(Sized): class MappingView(Sized):
__slots__ = ("_mapping",)
def __init__(self, mapping: Sized) -> None: ... # undocumented def __init__(self, mapping: Sized) -> None: ... # undocumented
def __len__(self) -> int: ... def __len__(self) -> int: ...

View file

@ -265,7 +265,27 @@ def final(f: _F) -> _F:
object to allow runtime introspection. object to allow runtime introspection.
""" """
def disjoint_base(cls: _TC) -> _TC: ... def disjoint_base(cls: _TC) -> _TC:
"""This decorator marks a class as a disjoint base.
Child classes of a disjoint base cannot inherit from other disjoint bases that are
not parent classes of the disjoint base.
For example:
@disjoint_base
class Disjoint1: pass
@disjoint_base
class Disjoint2: pass
class Disjoint3(Disjoint1, Disjoint2): pass # Type checker error
Type checkers can use knowledge of disjoint bases to detect unreachable code
and determine when two types can overlap.
See PEP 800.
"""
Literal: _SpecialForm Literal: _SpecialForm
@ -780,6 +800,7 @@ else:
class SupportsInt(Protocol, metaclass=abc.ABCMeta): class SupportsInt(Protocol, metaclass=abc.ABCMeta):
"""An ABC with one abstract method __int__.""" """An ABC with one abstract method __int__."""
__slots__ = ()
@abc.abstractmethod @abc.abstractmethod
def __int__(self) -> int: ... def __int__(self) -> int: ...
@ -787,6 +808,7 @@ else:
class SupportsFloat(Protocol, metaclass=abc.ABCMeta): class SupportsFloat(Protocol, metaclass=abc.ABCMeta):
"""An ABC with one abstract method __float__.""" """An ABC with one abstract method __float__."""
__slots__ = ()
@abc.abstractmethod @abc.abstractmethod
def __float__(self) -> float: ... def __float__(self) -> float: ...
@ -794,6 +816,7 @@ else:
class SupportsComplex(Protocol, metaclass=abc.ABCMeta): class SupportsComplex(Protocol, metaclass=abc.ABCMeta):
"""An ABC with one abstract method __complex__.""" """An ABC with one abstract method __complex__."""
__slots__ = ()
@abc.abstractmethod @abc.abstractmethod
def __complex__(self) -> complex: ... def __complex__(self) -> complex: ...
@ -801,11 +824,13 @@ else:
class SupportsBytes(Protocol, metaclass=abc.ABCMeta): class SupportsBytes(Protocol, metaclass=abc.ABCMeta):
"""An ABC with one abstract method __bytes__.""" """An ABC with one abstract method __bytes__."""
__slots__ = ()
@abc.abstractmethod @abc.abstractmethod
def __bytes__(self) -> bytes: ... def __bytes__(self) -> bytes: ...
@runtime_checkable @runtime_checkable
class SupportsIndex(Protocol, metaclass=abc.ABCMeta): class SupportsIndex(Protocol, metaclass=abc.ABCMeta):
__slots__ = ()
@abc.abstractmethod @abc.abstractmethod
def __index__(self) -> int: ... def __index__(self) -> int: ...
@ -815,6 +840,7 @@ else:
An ABC with one abstract method __abs__ that is covariant in its return type. An ABC with one abstract method __abs__ that is covariant in its return type.
""" """
__slots__ = ()
@abc.abstractmethod @abc.abstractmethod
def __abs__(self) -> _T_co: ... def __abs__(self) -> _T_co: ...
@ -824,6 +850,7 @@ else:
An ABC with one abstract method __round__ that is covariant in its return type. An ABC with one abstract method __round__ that is covariant in its return type.
""" """
__slots__ = ()
@overload @overload
@abc.abstractmethod @abc.abstractmethod
def __round__(self) -> int: ... def __round__(self) -> int: ...
@ -1298,7 +1325,14 @@ else:
format: Format | None = None, format: Format | None = None,
_recursive_guard: Container[str] = ..., _recursive_guard: Container[str] = ...,
) -> AnnotationForm: ... ) -> AnnotationForm: ...
def type_repr(value: object) -> str: ... def type_repr(value: object) -> str:
"""Convert a Python value to a format suitable for use with the STRING format.
This is intended as a helper for tools that support the STRING format but do
not have access to the code that originally produced the annotations. It uses
repr() for most objects.
"""
# PEP 661 # PEP 661
class Sentinel: class Sentinel:

View file

@ -4,7 +4,7 @@ from collections.abc import Awaitable, Callable, Coroutine, Iterable, Mapping, S
from contextlib import _GeneratorContextManager from contextlib import _GeneratorContextManager
from types import TracebackType from types import TracebackType
from typing import Any, ClassVar, Final, Generic, Literal, TypeVar, overload, type_check_only from typing import Any, ClassVar, Final, Generic, Literal, TypeVar, overload, type_check_only
from typing_extensions import ParamSpec, Self, TypeAlias from typing_extensions import ParamSpec, Self, TypeAlias, disjoint_base
_T = TypeVar("_T") _T = TypeVar("_T")
_TT = TypeVar("_TT", bound=type[Any]) _TT = TypeVar("_TT", bound=type[Any])
@ -72,52 +72,112 @@ _ArgsKwargs: TypeAlias = tuple[tuple[Any, ...], Mapping[str, Any]]
_NameArgsKwargs: TypeAlias = tuple[str, tuple[Any, ...], Mapping[str, Any]] _NameArgsKwargs: TypeAlias = tuple[str, tuple[Any, ...], Mapping[str, Any]]
_CallValue: TypeAlias = str | tuple[Any, ...] | Mapping[str, Any] | _ArgsKwargs | _NameArgsKwargs _CallValue: TypeAlias = str | tuple[Any, ...] | Mapping[str, Any] | _ArgsKwargs | _NameArgsKwargs
class _Call(tuple[Any, ...]): if sys.version_info >= (3, 12):
""" class _Call(tuple[Any, ...]):
A tuple for holding the results of a call to a mock, either in the form
`(args, kwargs)` or `(name, args, kwargs)`.
If args or kwargs are empty then a call tuple will compare equal to
a tuple without those values. This makes comparisons less verbose::
_Call(('name', (), {})) == ('name',)
_Call(('name', (1,), {})) == ('name', (1,))
_Call(((), {'a': 'b'})) == ({'a': 'b'},)
The `_Call` object provides a useful shortcut for comparing with call::
_Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
_Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
If the _Call has no name then it will match any name.
"""
def __new__(
cls, value: _CallValue = (), name: str | None = "", parent: _Call | None = None, two: bool = False, from_kall: bool = True
) -> Self: ...
def __init__(
self,
value: _CallValue = (),
name: str | None = None,
parent: _Call | None = None,
two: bool = False,
from_kall: bool = True,
) -> None: ...
__hash__: ClassVar[None] # type: ignore[assignment]
def __eq__(self, other: object) -> bool: ...
def __ne__(self, value: object, /) -> bool: ...
def __call__(self, *args: Any, **kwargs: Any) -> _Call: ...
def __getattr__(self, attr: str) -> Any: ...
def __getattribute__(self, attr: str) -> Any: ...
@property
def args(self) -> tuple[Any, ...]: ...
@property
def kwargs(self) -> Mapping[str, Any]: ...
def call_list(self) -> Any:
"""For a call object that represents multiple calls, `call_list`
returns a list of all the intermediate calls as well as the
final call.
""" """
A tuple for holding the results of a call to a mock, either in the form
`(args, kwargs)` or `(name, args, kwargs)`.
If args or kwargs are empty then a call tuple will compare equal to
a tuple without those values. This makes comparisons less verbose::
_Call(('name', (), {})) == ('name',)
_Call(('name', (1,), {})) == ('name', (1,))
_Call(((), {'a': 'b'})) == ({'a': 'b'},)
The `_Call` object provides a useful shortcut for comparing with call::
_Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
_Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
If the _Call has no name then it will match any name.
"""
def __new__(
cls,
value: _CallValue = (),
name: str | None = "",
parent: _Call | None = None,
two: bool = False,
from_kall: bool = True,
) -> Self: ...
def __init__(
self,
value: _CallValue = (),
name: str | None = None,
parent: _Call | None = None,
two: bool = False,
from_kall: bool = True,
) -> None: ...
__hash__: ClassVar[None] # type: ignore[assignment]
def __eq__(self, other: object) -> bool: ...
def __ne__(self, value: object, /) -> bool: ...
def __call__(self, *args: Any, **kwargs: Any) -> _Call: ...
def __getattr__(self, attr: str) -> Any: ...
def __getattribute__(self, attr: str) -> Any: ...
@property
def args(self) -> tuple[Any, ...]: ...
@property
def kwargs(self) -> Mapping[str, Any]: ...
def call_list(self) -> Any:
"""For a call object that represents multiple calls, `call_list`
returns a list of all the intermediate calls as well as the
final call.
"""
else:
@disjoint_base
class _Call(tuple[Any, ...]):
"""
A tuple for holding the results of a call to a mock, either in the form
`(args, kwargs)` or `(name, args, kwargs)`.
If args or kwargs are empty then a call tuple will compare equal to
a tuple without those values. This makes comparisons less verbose::
_Call(('name', (), {})) == ('name',)
_Call(('name', (1,), {})) == ('name', (1,))
_Call(((), {'a': 'b'})) == ({'a': 'b'},)
The `_Call` object provides a useful shortcut for comparing with call::
_Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
_Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
If the _Call has no name then it will match any name.
"""
def __new__(
cls,
value: _CallValue = (),
name: str | None = "",
parent: _Call | None = None,
two: bool = False,
from_kall: bool = True,
) -> Self: ...
def __init__(
self,
value: _CallValue = (),
name: str | None = None,
parent: _Call | None = None,
two: bool = False,
from_kall: bool = True,
) -> None: ...
__hash__: ClassVar[None] # type: ignore[assignment]
def __eq__(self, other: object) -> bool: ...
def __ne__(self, value: object, /) -> bool: ...
def __call__(self, *args: Any, **kwargs: Any) -> _Call: ...
def __getattr__(self, attr: str) -> Any: ...
def __getattribute__(self, attr: str) -> Any: ...
@property
def args(self) -> tuple[Any, ...]: ...
@property
def kwargs(self) -> Mapping[str, Any]: ...
def call_list(self) -> Any:
"""For a call object that represents multiple calls, `call_list`
returns a list of all the intermediate calls as well as the
final call.
"""
call: _Call call: _Call
@ -523,27 +583,32 @@ class _patcher:
# Ideally we'd be able to add an overload for it so that the return type is _patch[MagicMock], # Ideally we'd be able to add an overload for it so that the return type is _patch[MagicMock],
# but that's impossible with the current type system. # but that's impossible with the current type system.
@overload @overload
def __call__( def __call__( # type: ignore[overload-overlap]
self, self,
target: str, target: str,
new: _T, new: _T,
spec: Any | None = ..., spec: Literal[False] | None = None,
create: bool = ..., create: bool = False,
spec_set: Any | None = ..., spec_set: Literal[False] | None = None,
autospec: Any | None = ..., autospec: Literal[False] | None = None,
new_callable: Callable[..., Any] | None = ..., new_callable: None = None,
**kwargs: Any, *,
unsafe: bool = False,
) -> _patch[_T]: ... ) -> _patch[_T]: ...
@overload @overload
def __call__( def __call__(
self, self,
target: str, target: str,
*, *,
spec: Any | None = ..., # If not False or None, this is passed to new_callable
create: bool = ..., spec: Any | Literal[False] | None = None,
spec_set: Any | None = ..., create: bool = False,
autospec: Any | None = ..., # If not False or None, this is passed to new_callable
spec_set: Any | Literal[False] | None = None,
autospec: Literal[False] | None = None,
new_callable: Callable[..., _T], new_callable: Callable[..., _T],
unsafe: bool = False,
# kwargs are passed to new_callable
**kwargs: Any, **kwargs: Any,
) -> _patch_pass_arg[_T]: ... ) -> _patch_pass_arg[_T]: ...
@overload @overload
@ -551,25 +616,31 @@ class _patcher:
self, self,
target: str, target: str,
*, *,
spec: Any | None = ..., spec: Any | bool | None = None,
create: bool = ..., create: bool = False,
spec_set: Any | None = ..., spec_set: Any | bool | None = None,
autospec: Any | None = ..., autospec: Any | bool | None = None,
new_callable: None = None, new_callable: None = None,
unsafe: bool = False,
# kwargs are passed to the MagicMock/AsyncMock constructor
**kwargs: Any, **kwargs: Any,
) -> _patch_pass_arg[MagicMock | AsyncMock]: ... ) -> _patch_pass_arg[MagicMock | AsyncMock]: ...
# This overload also covers the case, where new==DEFAULT. In this case, the return type is _patch[Any].
# Ideally we'd be able to add an overload for it so that the return type is _patch[MagicMock],
# but that's impossible with the current type system.
@overload @overload
@staticmethod @staticmethod
def object( def object(
target: Any, target: Any,
attribute: str, attribute: str,
new: _T, new: _T,
spec: Any | None = ..., spec: Literal[False] | None = None,
create: bool = ..., create: bool = False,
spec_set: Any | None = ..., spec_set: Literal[False] | None = None,
autospec: Any | None = ..., autospec: Literal[False] | None = None,
new_callable: Callable[..., Any] | None = ..., new_callable: None = None,
**kwargs: Any, *,
unsafe: bool = False,
) -> _patch[_T]: ... ) -> _patch[_T]: ...
@overload @overload
@staticmethod @staticmethod
@ -577,11 +648,15 @@ class _patcher:
target: Any, target: Any,
attribute: str, attribute: str,
*, *,
spec: Any | None = ..., # If not False or None, this is passed to new_callable
create: bool = ..., spec: Any | Literal[False] | None = None,
spec_set: Any | None = ..., create: bool = False,
autospec: Any | None = ..., # If not False or None, this is passed to new_callable
spec_set: Any | Literal[False] | None = None,
autospec: Literal[False] | None = None,
new_callable: Callable[..., _T], new_callable: Callable[..., _T],
unsafe: bool = False,
# kwargs are passed to new_callable
**kwargs: Any, **kwargs: Any,
) -> _patch_pass_arg[_T]: ... ) -> _patch_pass_arg[_T]: ...
@overload @overload
@ -590,21 +665,54 @@ class _patcher:
target: Any, target: Any,
attribute: str, attribute: str,
*, *,
spec: Any | None = ..., spec: Any | bool | None = None,
create: bool = ..., create: bool = False,
spec_set: Any | None = ..., spec_set: Any | bool | None = None,
autospec: Any | None = ..., autospec: Any | bool | None = None,
new_callable: None = None, new_callable: None = None,
unsafe: bool = False,
# kwargs are passed to the MagicMock/AsyncMock constructor
**kwargs: Any, **kwargs: Any,
) -> _patch_pass_arg[MagicMock | AsyncMock]: ... ) -> _patch_pass_arg[MagicMock | AsyncMock]: ...
@overload
@staticmethod @staticmethod
def multiple( def multiple(
target: Any, target: Any | str,
spec: Any | None = ..., # If not False or None, this is passed to new_callable
create: bool = ..., spec: Any | Literal[False] | None = None,
spec_set: Any | None = ..., create: bool = False,
autospec: Any | None = ..., # If not False or None, this is passed to new_callable
new_callable: Any | None = ..., spec_set: Any | Literal[False] | None = None,
autospec: Literal[False] | None = None,
*,
new_callable: Callable[..., _T],
# The kwargs must be DEFAULT
**kwargs: Any,
) -> _patch_pass_arg[_T]: ...
@overload
@staticmethod
def multiple(
target: Any | str,
# If not False or None, this is passed to new_callable
spec: Any | Literal[False] | None,
create: bool,
# If not False or None, this is passed to new_callable
spec_set: Any | Literal[False] | None,
autospec: Literal[False] | None,
new_callable: Callable[..., _T],
# The kwargs must be DEFAULT
**kwargs: Any,
) -> _patch_pass_arg[_T]: ...
@overload
@staticmethod
def multiple(
target: Any | str,
spec: Any | bool | None = None,
create: bool = False,
spec_set: Any | bool | None = None,
autospec: Any | bool | None = None,
new_callable: None = None,
# The kwargs are the mock objects or DEFAULT
**kwargs: Any, **kwargs: Any,
) -> _patch[Any]: ... ) -> _patch[Any]: ...
@staticmethod @staticmethod

View file

@ -11,7 +11,7 @@ from _weakrefset import WeakSet as WeakSet
from collections.abc import Callable, Iterable, Iterator, Mapping, MutableMapping from collections.abc import Callable, Iterable, Iterator, Mapping, MutableMapping
from types import GenericAlias from types import GenericAlias
from typing import Any, ClassVar, Generic, TypeVar, final, overload from typing import Any, ClassVar, Generic, TypeVar, final, overload
from typing_extensions import ParamSpec, Self from typing_extensions import ParamSpec, Self, disjoint_base
__all__ = [ __all__ = [
"ref", "ref",
@ -59,6 +59,7 @@ class ProxyType(Generic[_T]): # "weakproxy"
def __getattr__(self, attr: str) -> Any: ... def __getattr__(self, attr: str) -> Any: ...
__hash__: ClassVar[None] # type: ignore[assignment] __hash__: ClassVar[None] # type: ignore[assignment]
@disjoint_base
class ReferenceType(Generic[_T]): # "weakref" class ReferenceType(Generic[_T]): # "weakref"
__callback__: Callable[[Self], Any] __callback__: Callable[[Self], Any]
def __new__(cls, o: _T, callback: Callable[[Self], Any] | None = ..., /) -> Self: ... def __new__(cls, o: _T, callback: Callable[[Self], Any] | None = ..., /) -> Self: ...

View file

@ -38,7 +38,7 @@ from _collections_abc import dict_keys
from _typeshed import FileDescriptorOrPath, ReadableBuffer, SupportsRead, SupportsWrite from _typeshed import FileDescriptorOrPath, ReadableBuffer, SupportsRead, SupportsWrite
from collections.abc import Callable, Generator, ItemsView, Iterable, Iterator, Mapping, Sequence from collections.abc import Callable, Generator, ItemsView, Iterable, Iterator, Mapping, Sequence
from typing import Any, Final, Generic, Literal, Protocol, SupportsIndex, TypeVar, overload, type_check_only from typing import Any, Final, Generic, Literal, Protocol, SupportsIndex, TypeVar, overload, type_check_only
from typing_extensions import TypeAlias, TypeGuard, deprecated from typing_extensions import TypeAlias, TypeGuard, deprecated, disjoint_base
from xml.parsers.expat import XMLParserType from xml.parsers.expat import XMLParserType
__all__ = [ __all__ = [
@ -134,6 +134,7 @@ _ElementCallable: TypeAlias = Callable[..., Element[_ElementCallable]]
_Tag = TypeVar("_Tag", default=str, bound=str | _ElementCallable) _Tag = TypeVar("_Tag", default=str, bound=str | _ElementCallable)
_OtherTag = TypeVar("_OtherTag", default=str, bound=str | _ElementCallable) _OtherTag = TypeVar("_OtherTag", default=str, bound=str | _ElementCallable)
@disjoint_base
class Element(Generic[_Tag]): class Element(Generic[_Tag]):
tag: _Tag tag: _Tag
attrib: dict[str, str] attrib: dict[str, str]
@ -592,6 +593,7 @@ def fromstringlist(sequence: Sequence[str | ReadableBuffer], parser: XMLParser |
# elementfactories. # elementfactories.
_ElementFactory: TypeAlias = Callable[[Any, dict[Any, Any]], Element] _ElementFactory: TypeAlias = Callable[[Any, dict[Any, Any]], Element]
@disjoint_base
class TreeBuilder: class TreeBuilder:
# comment_factory can take None because passing None to Comment is not an error # comment_factory can take None because passing None to Comment is not an error
def __init__( def __init__(
@ -679,6 +681,7 @@ _E = TypeVar("_E", default=Element)
# The default target is TreeBuilder, which returns Element. # The default target is TreeBuilder, which returns Element.
# C14NWriterTarget does not implement a close method, so using it results # C14NWriterTarget does not implement a close method, so using it results
# in a type of XMLParser[None]. # in a type of XMLParser[None].
@disjoint_base
class XMLParser(Generic[_E]): class XMLParser(Generic[_E]):
parser: XMLParserType parser: XMLParserType
target: _Target target: _Target

View file

@ -1,7 +1,7 @@
import sys import sys
from collections.abc import Iterable from collections.abc import Iterable
from datetime import datetime, timedelta, tzinfo from datetime import datetime, timedelta, tzinfo
from typing_extensions import Self from typing_extensions import Self, disjoint_base
from zoneinfo._common import ZoneInfoNotFoundError as ZoneInfoNotFoundError, _IOBytes from zoneinfo._common import ZoneInfoNotFoundError as ZoneInfoNotFoundError, _IOBytes
from zoneinfo._tzpath import ( from zoneinfo._tzpath import (
TZPATH as TZPATH, TZPATH as TZPATH,
@ -12,6 +12,7 @@ from zoneinfo._tzpath import (
__all__ = ["ZoneInfo", "reset_tzpath", "available_timezones", "TZPATH", "ZoneInfoNotFoundError", "InvalidTZPathWarning"] __all__ = ["ZoneInfo", "reset_tzpath", "available_timezones", "TZPATH", "ZoneInfoNotFoundError", "InvalidTZPathWarning"]
@disjoint_base
class ZoneInfo(tzinfo): class ZoneInfo(tzinfo):
@property @property
def key(self) -> str: ... def key(self) -> str: ...