[ty] Sync vendored typeshed stubs (#19607)
Some checks are pending
CI / Determine changes (push) Waiting to run
CI / cargo fmt (push) Waiting to run
CI / cargo clippy (push) Blocked by required conditions
CI / cargo test (linux) (push) Blocked by required conditions
CI / cargo test (linux, release) (push) Blocked by required conditions
CI / cargo test (windows) (push) Blocked by required conditions
CI / cargo test (wasm) (push) Blocked by required conditions
CI / cargo build (release) (push) Waiting to run
CI / cargo build (msrv) (push) Blocked by required conditions
CI / cargo fuzz build (push) Blocked by required conditions
CI / fuzz parser (push) Blocked by required conditions
CI / test scripts (push) Blocked by required conditions
CI / ecosystem (push) Blocked by required conditions
CI / Fuzz for new ty panics (push) Blocked by required conditions
CI / cargo shear (push) Blocked by required conditions
CI / python package (push) Waiting to run
CI / pre-commit (push) Waiting to run
CI / mkdocs (push) Waiting to run
CI / formatter instabilities and black similarity (push) Blocked by required conditions
CI / test ruff-lsp (push) Blocked by required conditions
CI / check playground (push) Blocked by required conditions
CI / benchmarks-instrumented (push) Blocked by required conditions
CI / benchmarks-walltime (push) Blocked by required conditions
[ty Playground] Release / publish (push) Waiting to run

Co-authored-by: typeshedbot <>
Co-authored-by: Alex Waygood <alex.waygood@gmail.com>
This commit is contained in:
github-actions[bot] 2025-07-28 22:06:33 +00:00 committed by GitHub
parent d4f64cd474
commit c6a123290d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
204 changed files with 3265 additions and 1162 deletions

View file

@ -199,14 +199,14 @@ mod tests {
assert_snapshot!(test.goto_type_definition(), @r#"
info[goto-type-definition]: Type definition
--> stdlib/builtins.pyi:890:7
--> stdlib/builtins.pyi:892:7
|
888 | def __getitem__(self, key: int, /) -> str | int | None: ...
889 |
890 | class str(Sequence[str]):
890 | def __getitem__(self, key: int, /) -> str | int | None: ...
891 |
892 | class str(Sequence[str]):
| ^^^
891 | """str(object='') -> str
892 | str(bytes_or_buffer[, encoding[, errors]]) -> str
893 | """str(object='') -> str
894 | str(bytes_or_buffer[, encoding[, errors]]) -> str
|
info: Source
--> main.py:4:13
@ -228,14 +228,14 @@ mod tests {
assert_snapshot!(test.goto_type_definition(), @r#"
info[goto-type-definition]: Type definition
--> stdlib/builtins.pyi:890:7
--> stdlib/builtins.pyi:892:7
|
888 | def __getitem__(self, key: int, /) -> str | int | None: ...
889 |
890 | class str(Sequence[str]):
890 | def __getitem__(self, key: int, /) -> str | int | None: ...
891 |
892 | class str(Sequence[str]):
| ^^^
891 | """str(object='') -> str
892 | str(bytes_or_buffer[, encoding[, errors]]) -> str
893 | """str(object='') -> str
894 | str(bytes_or_buffer[, encoding[, errors]]) -> str
|
info: Source
--> main.py:2:22
@ -344,14 +344,14 @@ mod tests {
assert_snapshot!(test.goto_type_definition(), @r#"
info[goto-type-definition]: Type definition
--> stdlib/builtins.pyi:890:7
--> stdlib/builtins.pyi:892:7
|
888 | def __getitem__(self, key: int, /) -> str | int | None: ...
889 |
890 | class str(Sequence[str]):
890 | def __getitem__(self, key: int, /) -> str | int | None: ...
891 |
892 | class str(Sequence[str]):
| ^^^
891 | """str(object='') -> str
892 | str(bytes_or_buffer[, encoding[, errors]]) -> str
893 | """str(object='') -> str
894 | str(bytes_or_buffer[, encoding[, errors]]) -> str
|
info: Source
--> main.py:4:18
@ -413,14 +413,14 @@ f(**kwargs<CURSOR>)
assert_snapshot!(test.goto_type_definition(), @r#"
info[goto-type-definition]: Type definition
--> stdlib/builtins.pyi:2888:7
--> stdlib/builtins.pyi:2890:7
|
2886 | """See PEP 585"""
2887 |
2888 | class dict(MutableMapping[_KT, _VT]):
2888 | """See PEP 585"""
2889 |
2890 | class dict(MutableMapping[_KT, _VT]):
| ^^^^
2889 | """dict() -> new empty dictionary
2890 | dict(mapping) -> new dictionary initialized from a mapping object's
2891 | """dict() -> new empty dictionary
2892 | dict(mapping) -> new dictionary initialized from a mapping object's
|
info: Source
--> main.py:6:5
@ -444,14 +444,14 @@ f(**kwargs<CURSOR>)
assert_snapshot!(test.goto_type_definition(), @r#"
info[goto-type-definition]: Type definition
--> stdlib/builtins.pyi:890:7
--> stdlib/builtins.pyi:892:7
|
888 | def __getitem__(self, key: int, /) -> str | int | None: ...
889 |
890 | class str(Sequence[str]):
890 | def __getitem__(self, key: int, /) -> str | int | None: ...
891 |
892 | class str(Sequence[str]):
| ^^^
891 | """str(object='') -> str
892 | str(bytes_or_buffer[, encoding[, errors]]) -> str
893 | """str(object='') -> str
894 | str(bytes_or_buffer[, encoding[, errors]]) -> str
|
info: Source
--> main.py:3:17
@ -537,14 +537,14 @@ f(**kwargs<CURSOR>)
assert_snapshot!(test.goto_type_definition(), @r#"
info[goto-type-definition]: Type definition
--> stdlib/builtins.pyi:890:7
--> stdlib/builtins.pyi:892:7
|
888 | def __getitem__(self, key: int, /) -> str | int | None: ...
889 |
890 | class str(Sequence[str]):
890 | def __getitem__(self, key: int, /) -> str | int | None: ...
891 |
892 | class str(Sequence[str]):
| ^^^
891 | """str(object='') -> str
892 | str(bytes_or_buffer[, encoding[, errors]]) -> str
893 | """str(object='') -> str
894 | str(bytes_or_buffer[, encoding[, errors]]) -> str
|
info: Source
--> main.py:4:27
@ -568,13 +568,13 @@ f(**kwargs<CURSOR>)
assert_snapshot!(test.goto_type_definition(), @r#"
info[goto-type-definition]: Type definition
--> stdlib/types.pyi:921:11
--> stdlib/types.pyi:922:11
|
919 | if sys.version_info >= (3, 10):
920 | @final
921 | class NoneType:
920 | if sys.version_info >= (3, 10):
921 | @final
922 | class NoneType:
| ^^^^^^^^
922 | """The type of the None singleton."""
923 | """The type of the None singleton."""
|
info: Source
--> main.py:3:17
@ -585,14 +585,14 @@ f(**kwargs<CURSOR>)
|
info[goto-type-definition]: Type definition
--> stdlib/builtins.pyi:890:7
--> stdlib/builtins.pyi:892:7
|
888 | def __getitem__(self, key: int, /) -> str | int | None: ...
889 |
890 | class str(Sequence[str]):
890 | def __getitem__(self, key: int, /) -> str | int | None: ...
891 |
892 | class str(Sequence[str]):
| ^^^
891 | """str(object='') -> str
892 | str(bytes_or_buffer[, encoding[, errors]]) -> str
893 | """str(object='') -> str
894 | str(bytes_or_buffer[, encoding[, errors]]) -> str
|
info: Source
--> main.py:3:17

View file

@ -29,16 +29,16 @@ error[invalid-argument-type]: Argument to function `loads` is incorrect
| ^ Expected `str | bytes | bytearray`, found `Literal[5]`
|
info: Function defined here
--> stdlib/json/__init__.pyi:218:5
--> stdlib/json/__init__.pyi:220:5
|
216 | """
217 |
218 | def loads(
218 | """
219 |
220 | def loads(
| ^^^^^
219 | s: str | bytes | bytearray,
221 | s: str | bytes | bytearray,
| -------------------------- Parameter declared here
220 | *,
221 | cls: type[JSONDecoder] | None = None,
222 | *,
223 | cls: type[JSONDecoder] | None = None,
|
info: rule `invalid-argument-type` is enabled by default

View file

@ -25,9 +25,9 @@ Typeshed supports Python versions 3.9 to 3.14.
## Using
If you're just using a type checker ([mypy](https://github.com/python/mypy/),
[pyright](https://github.com/microsoft/pyright),
[pytype](https://github.com/google/pytype/), PyCharm, ...), as opposed to
If you're just using a type checker (e.g. [mypy](https://github.com/python/mypy/),
[pyright](https://github.com/microsoft/pyright), or PyCharm's built-in type
checker), as opposed to
developing it, you don't need to interact with the typeshed repo at
all: a copy of standard library part of typeshed is bundled with type checkers.
And type stubs for third party packages and modules you are using can

View file

@ -1 +1 @@
08225953c98cfd375d80bc88865e5aae77d2c07f
9ab7fde0a0cd24ed7a72837fcb21093b811b80d8

View file

@ -124,6 +124,7 @@ compileall: 3.0-
compression: 3.14-
concurrent: 3.2-
concurrent.futures.interpreter: 3.14-
concurrent.interpreters: 3.14-
configparser: 3.0-
contextlib: 3.0-
contextvars: 3.7-

View file

@ -142,7 +142,7 @@ class _PyCPointerType(_CTypeBaseType):
def from_buffer_copy(self: type[_typeshed.Self], buffer: ReadableBuffer, offset: int = 0, /) -> _typeshed.Self: ...
def from_param(self: type[_typeshed.Self], value: Any, /) -> _typeshed.Self | _CArgObject: ...
def in_dll(self: type[_typeshed.Self], dll: CDLL, name: str, /) -> _typeshed.Self: ...
def set_type(self, type: Any, /) -> None: ...
def set_type(self, type: _CTypeBaseType, /) -> None: ...
if sys.version_info < (3, 13):
# Inherited from CType_Type starting on 3.13
def __mul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues]

View file

@ -69,6 +69,7 @@ if sys.version_info >= (3, 11):
on entry to the with-statement and restore the previous default context when
exiting the with-statement. If no context is specified, a copy of the current
default context is used.
"""
else:
@ -77,6 +78,7 @@ else:
on entry to the with-statement and restore the previous default context when
exiting the with-statement. If no context is specified, a copy of the current
default context is used.
"""
if sys.version_info >= (3, 14):
@ -84,6 +86,7 @@ if sys.version_info >= (3, 14):
"""Return a context object initialized to the proper values for one of the
IEEE interchange formats. The argument must be a multiple of 32 and less
than IEEE_CONTEXT_MAX_BITS.
"""
DefaultContext: Context

View file

@ -32,6 +32,7 @@ def __import__(
being imported (e.g. ``from module import <fromlist>``). The 'level'
argument represents the package location to import from in a relative
import (e.g. ``from ..pkg import mod`` would have a 'level' of 2).
"""
def spec_from_loader(
@ -80,6 +81,7 @@ class ModuleSpec:
Only finders (see importlib.abc.MetaPathFinder and
importlib.abc.PathEntryFinder) should modify ModuleSpec instances.
"""
def __init__(
@ -109,6 +111,7 @@ class BuiltinImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader)
All methods are either class or static methods to avoid the need to
instantiate the class.
"""
# MetaPathFinder
@ -120,6 +123,7 @@ class BuiltinImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader)
If 'path' is ever specified then the search is considered a failure.
This method is deprecated. Use find_spec() instead.
"""
@classmethod
@ -136,6 +140,7 @@ class BuiltinImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader)
"""Load the specified module into sys.modules and return it.
This method is deprecated. Use loader.exec_module() instead.
"""
@classmethod
@ -152,6 +157,7 @@ class BuiltinImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader)
"""Return repr for the module.
The method is deprecated. The import machinery does the job itself.
"""
if sys.version_info >= (3, 10):
@staticmethod
@ -175,6 +181,7 @@ class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader):
All methods are either class or static methods to avoid the need to
instantiate the class.
"""
# MetaPathFinder
@ -184,6 +191,7 @@ class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader):
"""Find a frozen module.
This method is deprecated. Use find_spec() instead.
"""
@classmethod
@ -200,6 +208,7 @@ class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader):
"""Load a frozen module.
This method is deprecated. Use exec_module() instead.
"""
@classmethod
@ -216,6 +225,7 @@ class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader):
"""Return repr for the module.
The method is deprecated. The import machinery does the job itself.
"""
if sys.version_info >= (3, 10):
@staticmethod

View file

@ -51,6 +51,7 @@ def cache_from_source(path: StrPath, debug_override: bool | None = None, *, opti
while a False value is equivalent to setting 'optimization' to '1'.
If sys.implementation.cache_tag is None then NotImplementedError is raised.
"""
def source_from_cache(path: StrPath) -> str:
@ -60,6 +61,7 @@ def source_from_cache(path: StrPath) -> str:
the .py file calculated to correspond to the .pyc file. If path does
not conform to PEP 3147/488 format, ValueError will be raised. If
sys.implementation.cache_tag is None then NotImplementedError is raised.
"""
def decode_source(source_bytes: ReadableBuffer) -> str:
@ -83,6 +85,7 @@ def spec_from_file_location(
import system.
The loader must take a spec as its only __init__() arg.
"""
@deprecated(
@ -98,6 +101,7 @@ class WindowsRegistryFinder(importlib.abc.MetaPathFinder):
"""Find module named in the registry.
This method is deprecated. Use find_spec() instead.
"""
@classmethod
@ -123,7 +127,8 @@ class PathFinder(importlib.abc.MetaPathFinder):
if sys.version_info >= (3, 10):
@staticmethod
def find_distributions(context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]:
"""Find distributions.
"""
Find distributions.
Return an iterable of all Distribution instances capable of
loading the metadata for packages matching ``context.name``
@ -133,7 +138,8 @@ class PathFinder(importlib.abc.MetaPathFinder):
else:
@classmethod
def find_distributions(cls, context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]:
"""Find distributions.
"""
Find distributions.
Return an iterable of all Distribution instances capable of
loading the metadata for packages matching ``context.name``
@ -156,6 +162,7 @@ class PathFinder(importlib.abc.MetaPathFinder):
sys.path_importer_cache.
This method is deprecated. Use find_spec() instead.
"""
SOURCE_SUFFIXES: list[str]
@ -169,6 +176,7 @@ class FileFinder(importlib.abc.PathEntryFinder):
Interactions with the file system are cached for performance, being
refreshed when the directory the finder is handling has been modified.
"""
path: str
@ -188,6 +196,7 @@ class FileFinder(importlib.abc.PathEntryFinder):
If the path called on the closure is not a directory, ImportError is
raised.
"""
class _LoaderBasics:
@ -252,6 +261,7 @@ class SourceLoader(_LoaderBasics):
Reading of bytecode requires path_stats to be implemented. To write
bytecode, set_data must also be implemented.
"""
class FileLoader:
@ -276,6 +286,7 @@ class FileLoader:
"""Load a module from a file.
This method is deprecated. Use exec_module() instead.
"""
if sys.version_info >= (3, 10):
def get_resource_reader(self, name: str | None = None) -> importlib.readers.FileReader: ...
@ -318,6 +329,7 @@ class ExtensionFileLoader(FileLoader, _LoaderBasics, importlib.abc.ExecutionLoad
"""Loader for extension modules.
The constructor is designed to work with FileFinder.
"""
def __init__(self, name: str, path: str) -> None: ...
@ -356,6 +368,7 @@ if sys.version_info >= (3, 11):
"""Load a namespace module.
This method is deprecated. Use exec_module() instead.
"""
def get_resource_reader(self, module: types.ModuleType) -> importlib.readers.NamespaceReader: ...
@ -366,6 +379,7 @@ if sys.version_info >= (3, 11):
"""Return repr for the module.
The method is deprecated. The import machinery does the job itself.
"""
_NamespaceLoader = NamespaceLoader
@ -386,6 +400,7 @@ else:
"""Load a namespace module.
This method is deprecated. Use exec_module() instead.
"""
if sys.version_info >= (3, 10):
@staticmethod
@ -394,6 +409,7 @@ else:
"""Return repr for the module.
The method is deprecated. The import machinery does the job itself.
"""
def get_resource_reader(self, module: types.ModuleType) -> importlib.readers.NamespaceReader: ...
@ -404,6 +420,7 @@ else:
"""Return repr for the module.
The method is deprecated. The import machinery does the job itself.
"""
if sys.version_info >= (3, 13):

View file

@ -4,9 +4,11 @@ The 'interpreters' module provides a more convenient interface.
import types
from collections.abc import Callable
from typing import Any, Final, Literal, SupportsIndex
from typing import Any, Final, Literal, SupportsIndex, TypeVar
from typing_extensions import TypeAlias
_R = TypeVar("_R")
_Configs: TypeAlias = Literal["default", "isolated", "legacy", "empty", ""]
_SharedDict: TypeAlias = dict[str, Any] # many objects can be shared
@ -88,7 +90,7 @@ def get_config(id: SupportsIndex, *, restrict: bool = False) -> types.SimpleName
Return a representation of the config used to initialize the interpreter.
"""
def whence(id: SupportsIndex) -> int:
def whence(id: SupportsIndex) -> _Whence:
"""whence(id) -> int
Return an identifier for where the interpreter was created.
@ -120,12 +122,12 @@ def exec(
def call(
id: SupportsIndex,
callable: Callable[..., object],
callable: Callable[..., _R],
args: tuple[object, ...] | None = None,
kwargs: dict[str, object] | None = None,
*,
restrict: bool = False,
) -> object:
) -> tuple[_R, types.SimpleNamespace]:
"""call(id, callable, args=None, kwargs=None, *, restrict=False)
Call the provided object in the identified interpreter.
@ -182,6 +184,7 @@ def capture_exception(exc: BaseException | None = None) -> types.SimpleNamespace
The returned snapshot is the same as what _interpreters.exec() returns.
"""
_Whence: TypeAlias = Literal[0, 1, 2, 3, 4, 5]
WHENCE_UNKNOWN: Final = 0
WHENCE_RUNTIME: Final = 1
WHENCE_LEGACY_CAPI: Final = 2

View file

@ -82,7 +82,7 @@ def encode_basestring_ascii(s: str, /) -> str:
Return an ASCII-only JSON representation of a Python string
"""
def scanstring(string: str, end: int, strict: bool = ...) -> tuple[str, int]:
def scanstring(string: str, end: int, strict: bool = True) -> tuple[str, int]:
"""scanstring(string, end, strict=True) -> (string, end)
Scan the string s for a JSON string. End is the index of the

View file

@ -11,7 +11,7 @@ import sys
from _typeshed import SupportsGetItem
from collections.abc import Callable, Container, Iterable, MutableMapping, MutableSequence, Sequence
from operator import attrgetter as attrgetter, itemgetter as itemgetter, methodcaller as methodcaller
from typing import Any, AnyStr, Protocol, SupportsAbs, SupportsIndex, TypeVar, overload
from typing import Any, AnyStr, Protocol, SupportsAbs, SupportsIndex, TypeVar, overload, type_check_only
from typing_extensions import ParamSpec, TypeAlias, TypeIs
_R = TypeVar("_R")
@ -25,12 +25,15 @@ _P = ParamSpec("_P")
# operators can be overloaded to return an arbitrary object. For example,
# the numpy.array comparison dunders return another numpy.array.
@type_check_only
class _SupportsDunderLT(Protocol):
def __lt__(self, other: Any, /) -> Any: ...
@type_check_only
class _SupportsDunderGT(Protocol):
def __gt__(self, other: Any, /) -> Any: ...
@type_check_only
class _SupportsDunderLE(Protocol):
def __le__(self, other: Any, /) -> Any: ...
@ -39,12 +42,15 @@ class _SupportsDunderGE(Protocol):
_SupportsComparison: TypeAlias = _SupportsDunderLE | _SupportsDunderGE | _SupportsDunderGT | _SupportsDunderLT
@type_check_only
class _SupportsInversion(Protocol[_T_co]):
def __invert__(self) -> _T_co: ...
@type_check_only
class _SupportsNeg(Protocol[_T_co]):
def __neg__(self) -> _T_co: ...
@type_check_only
class _SupportsPos(Protocol[_T_co]):
def __pos__(self) -> _T_co: ...

View file

@ -56,7 +56,8 @@ def _check_for_unavailable_sdk(_config_vars: dict[str, str]) -> dict[str, str]:
"""Remove references to any SDKs not available"""
def compiler_fixup(compiler_so: Iterable[str], cc_args: Sequence[str]) -> list[str]:
"""This function will strip '-isysroot PATH' and '-arch ARCH' from the
"""
This function will strip '-isysroot PATH' and '-arch ARCH' from the
compile flags if the user has specified one them in extra_compile_flags.
This is needed because '-arch ARCH' adds another architecture to the

View file

@ -16,8 +16,9 @@ from sqlite3 import (
ProgrammingError as ProgrammingError,
Row as Row,
Warning as Warning,
_IsolationLevel,
)
from typing import Any, Final, Literal, TypeVar, overload
from typing import Any, Final, TypeVar, overload
from typing_extensions import TypeAlias
if sys.version_info >= (3, 11):
@ -228,7 +229,7 @@ if sys.version_info >= (3, 12):
database: StrOrBytesPath,
timeout: float = 5.0,
detect_types: int = 0,
isolation_level: Literal["DEFERRED", "EXCLUSIVE", "IMMEDIATE"] | None = "DEFERRED",
isolation_level: _IsolationLevel = "DEFERRED",
check_same_thread: bool = True,
cached_statements: int = 128,
uri: bool = False,
@ -251,7 +252,7 @@ if sys.version_info >= (3, 12):
database: StrOrBytesPath,
timeout: float,
detect_types: int,
isolation_level: Literal["DEFERRED", "EXCLUSIVE", "IMMEDIATE"] | None,
isolation_level: _IsolationLevel,
check_same_thread: bool,
factory: type[_ConnectionT],
cached_statements: int = 128,
@ -264,7 +265,7 @@ if sys.version_info >= (3, 12):
database: StrOrBytesPath,
timeout: float = 5.0,
detect_types: int = 0,
isolation_level: Literal["DEFERRED", "EXCLUSIVE", "IMMEDIATE"] | None = "DEFERRED",
isolation_level: _IsolationLevel = "DEFERRED",
check_same_thread: bool = True,
*,
factory: type[_ConnectionT],
@ -279,7 +280,7 @@ else:
database: StrOrBytesPath,
timeout: float = 5.0,
detect_types: int = 0,
isolation_level: Literal["DEFERRED", "EXCLUSIVE", "IMMEDIATE"] | None = "DEFERRED",
isolation_level: _IsolationLevel = "DEFERRED",
check_same_thread: bool = True,
cached_statements: int = 128,
uri: bool = False,
@ -295,7 +296,7 @@ else:
database: StrOrBytesPath,
timeout: float,
detect_types: int,
isolation_level: Literal["DEFERRED", "EXCLUSIVE", "IMMEDIATE"] | None,
isolation_level: _IsolationLevel,
check_same_thread: bool,
factory: type[_ConnectionT],
cached_statements: int = 128,
@ -306,7 +307,7 @@ else:
database: StrOrBytesPath,
timeout: float = 5.0,
detect_types: int = 0,
isolation_level: Literal["DEFERRED", "EXCLUSIVE", "IMMEDIATE"] | None = "DEFERRED",
isolation_level: _IsolationLevel = "DEFERRED",
check_same_thread: bool = True,
*,
factory: type[_ConnectionT],

View file

@ -253,7 +253,7 @@ def start_new(function: Callable[[Unpack[_Ts]], object], args: tuple[Unpack[_Ts]
def start_new(function: Callable[..., object], args: tuple[Any, ...], kwargs: dict[str, Any], /) -> int: ...
if sys.version_info >= (3, 10):
def interrupt_main(signum: signal.Signals = ..., /) -> None:
def interrupt_main(signum: signal.Signals = signal.SIGINT, /) -> None:
"""Simulate the arrival of the given signal in the main thread,
where the corresponding signal handler will be executed.
If *signum* is omitted, SIGINT is assumed.

View file

@ -131,7 +131,9 @@ if sys.version_info >= (3, 13):
use: str | None = None,
/,
):
"""wantTk
"""
wantTk
if false, then Tk_Init() doesn't get called
sync
if true, then pass -sync to wish
@ -151,7 +153,9 @@ else:
use: str | None = None,
/,
):
"""wantTk
"""
wantTk
if false, then Tk_Init() doesn't get called
sync
if true, then pass -sync to wish

View file

@ -65,10 +65,10 @@ MaybeNone: TypeAlias = Any # stable
# In cases where the sentinel object is exported and can be used by user code,
# a construct like this is better:
#
# _SentinelType = NewType("_SentinelType", object)
# sentinel: _SentinelType
# _SentinelType = NewType("_SentinelType", object) # does not exist at runtime
# sentinel: Final[_SentinelType]
# def foo(x: int | None | _SentinelType = ...) -> None: ...
sentinel: Any
sentinel: Any # stable
# stable
class IdentityFunction(Protocol):

View file

@ -81,6 +81,7 @@ class abstractclassmethod(classmethod[_T, _P, _R_co]):
@abstractmethod
def my_abstract_classmethod(cls, ...):
...
"""
__isabstractmethod__: Literal[True]
@ -97,6 +98,7 @@ class abstractstaticmethod(staticmethod[_P, _R_co]):
@abstractmethod
def my_abstract_staticmethod(...):
...
"""
__isabstractmethod__: Literal[True]
@ -113,6 +115,7 @@ class abstractproperty(property):
@abstractmethod
def my_abstract_property(self):
...
"""
__isabstractmethod__: Literal[True]

View file

@ -39,6 +39,7 @@ if sys.version_info >= (3, 14):
* owner: The owning object (module, class, or function).
* is_argument: Does nothing, retained for compatibility.
* is_class: True if the forward reference was created in class scope.
"""
__forward_is_argument__: bool
@ -132,6 +133,7 @@ if sys.version_info >= (3, 14):
class, or function that the __annotate__ function derives from). With the
FORWARDREF format, it is used to provide better evaluation capabilities
on the generated ForwardRef objects.
"""
@overload
@ -231,6 +233,7 @@ if sys.version_info >= (3, 14):
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.
"""
def annotations_to_string(annotations: SupportsItems[str, object]) -> dict[str, str]:

View file

@ -65,7 +65,7 @@ import sys
from _typeshed import SupportsWrite, sentinel
from collections.abc import Callable, Generator, Iterable, Sequence
from re import Pattern
from typing import IO, Any, ClassVar, Final, Generic, NoReturn, Protocol, TypeVar, overload
from typing import IO, Any, ClassVar, Final, Generic, NoReturn, Protocol, TypeVar, overload, type_check_only
from typing_extensions import Self, TypeAlias, deprecated
__all__ = [
@ -168,7 +168,8 @@ class _ActionsContainer:
version: str = ...,
**kwargs: Any,
) -> Action:
"""add_argument(dest, ..., name=value, ...)
"""
add_argument(dest, ..., name=value, ...)
add_argument(option_string, option_string, ..., name=value, ...)
"""
@ -193,6 +194,7 @@ class _ActionsContainer:
def _handle_conflict_error(self, action: Action, conflicting_actions: Iterable[tuple[str, Action]]) -> NoReturn: ...
def _handle_conflict_resolve(self, action: Action, conflicting_actions: Iterable[tuple[str, Action]]) -> None: ...
@type_check_only
class _FormatterClass(Protocol):
def __call__(self, *, prog: str) -> HelpFormatter: ...
@ -401,7 +403,7 @@ class HelpFormatter:
if sys.version_info >= (3, 14):
def __init__(
self, prog: str, indent_increment: int = 2, max_help_position: int = 24, width: int | None = None, color: bool = False
self, prog: str, indent_increment: int = 2, max_help_position: int = 24, width: int | None = None, color: bool = True
) -> None: ...
else:
def __init__(

View file

@ -2170,7 +2170,8 @@ if sys.version_info >= (3, 13):
feature_version: None | int | tuple[int, int] = None,
optimize: Literal[-1, 0, 1, 2] = -1,
) -> Module:
"""Parse the source into an AST node.
"""
Parse the source into an AST node.
Equivalent to compile(source, filename, mode, PyCF_ONLY_AST).
Pass type_comments=True to get back type comments where the syntax allows.
"""
@ -2253,7 +2254,8 @@ else:
type_comments: bool = False,
feature_version: None | int | tuple[int, int] = None,
) -> Module:
"""Parse the source into an AST node.
"""
Parse the source into an AST node.
Equivalent to compile(source, filename, mode, PyCF_ONLY_AST).
Pass type_comments=True to get back type comments where the syntax allows.
"""
@ -2320,7 +2322,8 @@ else:
) -> mod: ...
def literal_eval(node_or_string: str | AST) -> Any:
"""Evaluate an expression node or a string containing only a Python
"""
Evaluate an expression node or a string containing only a Python
expression. The string or node provided may only consist of the following
Python literal structures: strings, bytes, numbers, tuples, lists, dicts,
sets, booleans, and None.
@ -2337,7 +2340,8 @@ if sys.version_info >= (3, 13):
indent: int | str | None = None,
show_empty: bool = False,
) -> str:
"""Return a formatted dump of the tree in node. This is mainly useful for
"""
Return a formatted dump of the tree in node. This is mainly useful for
debugging purposes. If annotate_fields is true (by default),
the returned string will show the names and the values for fields.
If annotate_fields is false, the result string will be more compact by
@ -2354,7 +2358,8 @@ else:
def dump(
node: AST, annotate_fields: bool = True, include_attributes: bool = False, *, indent: int | str | None = None
) -> str:
"""Return a formatted dump of the tree in node. This is mainly useful for
"""
Return a formatted dump of the tree in node. This is mainly useful for
debugging purposes. If annotate_fields is true (by default),
the returned string will show the names and the values for fields.
If annotate_fields is false, the result string will be more compact by
@ -2366,12 +2371,14 @@ else:
"""
def copy_location(new_node: _T, old_node: AST) -> _T:
"""Copy source location (`lineno`, `col_offset`, `end_lineno`, and `end_col_offset`
"""
Copy source location (`lineno`, `col_offset`, `end_lineno`, and `end_col_offset`
attributes) from *old_node* to *new_node* if possible, and return *new_node*.
"""
def fix_missing_locations(node: _T) -> _T:
"""When you compile a node tree with compile(), the compiler expects lineno and
"""
When you compile a node tree with compile(), the compiler expects lineno and
col_offset attributes for every node that supports them. This is rather
tedious to fill in for generated nodes, so this helper adds these attributes
recursively where not already set, by setting them to the values of the
@ -2379,23 +2386,27 @@ def fix_missing_locations(node: _T) -> _T:
"""
def increment_lineno(node: _T, n: int = 1) -> _T:
"""Increment the line number and end line number of each node in the tree
"""
Increment the line number and end line number of each node in the tree
starting at *node* by *n*. This is useful to "move code" to a different
location in a file.
"""
def iter_fields(node: AST) -> Iterator[tuple[str, Any]]:
"""Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``
"""
Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``
that is present on *node*.
"""
def iter_child_nodes(node: AST) -> Iterator[AST]:
"""Yield all direct child nodes of *node*, that is, all fields that are nodes
"""
Yield all direct child nodes of *node*, that is, all fields that are nodes
and all items of fields that are lists of nodes.
"""
def get_docstring(node: AsyncFunctionDef | FunctionDef | ClassDef | Module, clean: bool = True) -> str | None:
"""Return the docstring for the given node or None if no docstring can
"""
Return the docstring for the given node or None if no docstring can
be found. If the node provided does not have docstrings a TypeError
will be raised.
@ -2414,7 +2425,8 @@ def get_source_segment(source: str, node: AST, *, padded: bool = False) -> str |
"""
def walk(node: AST) -> Iterator[AST]:
"""Recursively yield all descendant nodes in the tree starting at *node*
"""
Recursively yield all descendant nodes in the tree starting at *node*
(including *node* itself), in no specified order. This is useful if you
only want to modify nodes in place and don't care about the context.
"""
@ -2431,7 +2443,8 @@ if sys.version_info >= (3, 14):
"""
class NodeVisitor:
"""A node visitor base class that walks the abstract syntax tree and calls a
"""
A node visitor base class that walks the abstract syntax tree and calls a
visitor function for every node found. This function may return a value
which is forwarded by the `visit` method.
@ -2595,7 +2608,8 @@ class NodeVisitor:
def visit_Ellipsis(self, node: Ellipsis) -> Any: ... # type: ignore[deprecated]
class NodeTransformer(NodeVisitor):
"""A :class:`NodeVisitor` subclass that walks the abstract syntax tree and
"""
A :class:`NodeVisitor` subclass that walks the abstract syntax tree and
allows modification of nodes.
The `NodeTransformer` will walk the AST and use the return value of the

View file

@ -43,14 +43,11 @@ if sys.platform == "win32":
"Server", # from base_events
"iscoroutinefunction", # from coroutines
"iscoroutine", # from coroutines
"_AbstractEventLoopPolicy", # from events
"AbstractEventLoop", # from events
"AbstractServer", # from events
"Handle", # from events
"TimerHandle", # from events
"_get_event_loop_policy", # from events
"get_event_loop_policy", # from events
"_set_event_loop_policy", # from events
"set_event_loop_policy", # from events
"get_event_loop", # from events
"set_event_loop", # from events
@ -519,14 +516,11 @@ else:
"Server", # from base_events
"iscoroutinefunction", # from coroutines
"iscoroutine", # from coroutines
"_AbstractEventLoopPolicy", # from events
"AbstractEventLoop", # from events
"AbstractServer", # from events
"Handle", # from events
"TimerHandle", # from events
"_get_event_loop_policy", # from events
"get_event_loop_policy", # from events
"_set_event_loop_policy", # from events
"set_event_loop_policy", # from events
"get_event_loop", # from events
"set_event_loop", # from events
@ -612,7 +606,6 @@ else:
"DatagramTransport", # from transports
"SubprocessTransport", # from transports
"SelectorEventLoop", # from unix_events
"_DefaultEventLoopPolicy", # from unix_events
"EventLoop", # from unix_events
)
elif sys.version_info >= (3, 13):

View file

@ -1,20 +1,25 @@
from _asyncio import Future
from collections.abc import Callable, Sequence
from contextvars import Context
from typing import Any, Final
from typing_extensions import TypeIs
from . import futures
__all__ = ()
# asyncio defines 'isfuture()' in base_futures.py and re-imports it in futures.py
# but it leads to circular import error in pytype tool.
# That's why the import order is reversed.
from .futures import isfuture as isfuture
_PENDING: Final = "PENDING" # undocumented
_CANCELLED: Final = "CANCELLED" # undocumented
_FINISHED: Final = "FINISHED" # undocumented
def isfuture(obj: object) -> TypeIs[Future[Any]]:
"""Check for a Future.
This returns True when obj is a Future instance or is advertising
itself as duck-type compatible by setting _asyncio_future_blocking.
See comment in Future for more details.
"""
def _format_callbacks(cb: Sequence[tuple[Callable[[futures.Future[Any]], None], Context]]) -> str: # undocumented
"""helper function for Future.__repr__"""

View file

@ -30,14 +30,11 @@ if sys.version_info < (3, 14):
# Keep asyncio.__all__ updated with any changes to __all__ here
if sys.version_info >= (3, 14):
__all__ = (
"_AbstractEventLoopPolicy",
"AbstractEventLoop",
"AbstractServer",
"Handle",
"TimerHandle",
"_get_event_loop_policy",
"get_event_loop_policy",
"_set_event_loop_policy",
"set_event_loop_policy",
"get_event_loop",
"set_event_loop",

View file

@ -43,7 +43,8 @@ class SendfileNotAvailableError(RuntimeError):
"""
class IncompleteReadError(EOFError):
"""Incomplete read error. Attributes:
"""
Incomplete read error. Attributes:
- partial: read bytes string before the end of stream was reached
- expected: total number of expected bytes (or None if unknown)

View file

@ -3,9 +3,9 @@
import sys
from _asyncio import Future as Future
from concurrent.futures._base import Future as _ConcurrentFuture
from typing import Any, TypeVar
from typing_extensions import TypeIs
from typing import TypeVar
from .base_futures import isfuture as isfuture
from .events import AbstractEventLoop
# Keep asyncio.__all__ updated with any changes to __all__ here
@ -18,16 +18,5 @@ else:
_T = TypeVar("_T")
# asyncio defines 'isfuture()' in base_futures.py and re-imports it in futures.py
# but it leads to circular import error in pytype tool.
# That's why the import order is reversed.
def isfuture(obj: object) -> TypeIs[Future[Any]]:
"""Check for a Future.
This returns True when obj is a Future instance or is advertising
itself as duck-type compatible by setting _asyncio_future_blocking.
See comment in Future for more details.
"""
def wrap_future(future: _ConcurrentFuture[_T] | Future[_T], *, loop: AbstractEventLoop | None = None) -> Future[_T]:
"""Wrap concurrent.futures.Future object."""

View file

@ -80,6 +80,7 @@ class Lock(_ContextManagerMixin, _LoopBoundMixin):
else:
# lock is acquired
...
"""
_waiters: deque[Future[Any]] | None

View file

@ -39,6 +39,7 @@ if sys.version_info >= (3, 11):
unittest runners, console tools, -- everywhere when async code
is called from existing sync framework and where the preferred single
asyncio.run() call doesn't work.
"""
def __init__(self, *, debug: bool | None = None, loop_factory: Callable[[], AbstractEventLoop] | None = None) -> None: ...

View file

@ -66,7 +66,8 @@ if sys.version_info < (3, 11):
_handshake_cb: Callable[[BaseException | None], None] | None
_shutdown_cb: Callable[[], None] | None
def __init__(self, context: ssl.SSLContext, server_side: bool, server_hostname: str | None = None) -> None:
"""The *context* argument specifies the ssl.SSLContext to use.
"""
The *context* argument specifies the ssl.SSLContext to use.
The *server_side* argument indicates whether this is a server side or
client side transport.
@ -95,7 +96,8 @@ if sys.version_info < (3, 11):
@property
def wrapped(self) -> bool:
"""Whether a security layer is currently in effect.
"""
Whether a security layer is currently in effect.
Return False during handshake.
"""

View file

@ -58,4 +58,5 @@ async def staggered_race(
``len(exceptions)`` is equal to the number of coroutines actually
started, and the order is the same as in ``coro_fns``. The winning
coroutine's entry is ``None``.
"""

View file

@ -40,7 +40,8 @@ class CycleFoundException(Exception):
def get_all_awaited_by(pid: SupportsIndex) -> list[_AwaitedInfo]: ...
def build_async_tree(result: Iterable[_AwaitedInfo], task_emoji: str = "(T)", cor_emoji: str = "") -> list[list[str]]:
"""Build a list of strings for pretty-print an async call tree.
"""
Build a list of strings for pretty-print an async call tree.
The call tree is produced by `get_all_async_stacks()`, prefixing tasks
with `task_emoji` and coroutine frames with `cor_emoji`.

View file

@ -18,7 +18,7 @@ _Ts = TypeVarTuple("_Ts")
# Keep asyncio.__all__ updated with any changes to __all__ here
if sys.platform != "win32":
if sys.version_info >= (3, 14):
__all__ = ("SelectorEventLoop", "_DefaultEventLoopPolicy", "EventLoop")
__all__ = ("SelectorEventLoop", "EventLoop")
elif sys.version_info >= (3, 13):
# Adds EventLoop
__all__ = (
@ -131,6 +131,7 @@ if sys.version_info < (3, 14):
Return True if the watcher is installed and ready to handle process exit
notifications.
"""
else:
@ -214,6 +215,7 @@ if sys.version_info < (3, 14):
Return True if the watcher is installed and ready to handle process exit
notifications.
"""
if sys.platform != "win32":

View file

@ -93,10 +93,13 @@ def urlsafe_b64decode(s: str | ReadableBuffer) -> bytes:
"""
def b32encode(s: ReadableBuffer) -> bytes:
"""Encode the bytes-like objects using base32 and return a bytes object."""
"""
Encode the bytes-like objects using base32 and return a bytes object.
"""
def b32decode(s: str | ReadableBuffer, casefold: bool = False, map01: str | ReadableBuffer | None = None) -> bytes:
"""Decode the base32 encoded bytes-like object or ASCII string s.
"""
Decode the base32 encoded bytes-like object or ASCII string s.
Optional casefold is a flag specifying whether a lowercase alphabet is
acceptable as input. For security purposes, the default is False.
@ -130,10 +133,13 @@ def b16decode(s: str | ReadableBuffer, casefold: bool = False) -> bytes:
if sys.version_info >= (3, 10):
def b32hexencode(s: ReadableBuffer) -> bytes:
"""Encode the bytes-like objects using base32hex and return a bytes object."""
"""
Encode the bytes-like objects using base32hex and return a bytes object.
"""
def b32hexdecode(s: str | ReadableBuffer, casefold: bool = False) -> bytes:
"""Decode the base32hex encoded bytes-like object or ASCII string s.
"""
Decode the base32hex encoded bytes-like object or ASCII string s.
Optional casefold is a flag specifying whether a lowercase alphabet is
acceptable as input. For security purposes, the default is False.

View file

@ -278,6 +278,7 @@ class Bdb:
return string contains the canonical filename, the function name
or '<lambda>', the input arguments, the return value, and the
line of code (if it exists).
"""
def run(self, cmd: str | CodeType, globals: dict[str, Any] | None = None, locals: Mapping[str, Any] | None = None) -> None:
@ -374,6 +375,7 @@ class Breakpoint:
The information includes the breakpoint number, temporary
status, file:line position, break condition, number of times to
ignore, and number of times hit.
"""
def checkfuncname(b: Breakpoint, frame: FrameType) -> bool:

View file

@ -881,9 +881,11 @@ class complex:
def from_number(cls, number: complex | SupportsComplex | SupportsFloat | SupportsIndex, /) -> Self:
"""Convert number to a complex floating-point number."""
@type_check_only
class _FormatMapMapping(Protocol):
def __getitem__(self, key: str, /) -> Any: ...
@type_check_only
class _TranslateTable(Protocol):
def __getitem__(self, key: int, /) -> str | int | None: ...
@ -3380,6 +3382,7 @@ if sys.version_info >= (3, 10):
def aiter(async_iterable: SupportsAiter[_SupportsAnextT_co], /) -> _SupportsAnextT_co:
"""Return an AsyncIterator for an AsyncIterable object."""
@type_check_only
class _SupportsSynchronousAnext(Protocol[_AwaitableT_co]):
def __anext__(self) -> _AwaitableT_co: ...
@ -3700,7 +3703,6 @@ def iter(object: Callable[[], _T | None], sentinel: None, /) -> Iterator[_T]: ..
@overload
def iter(object: Callable[[], _T], sentinel: object, /) -> Iterator[_T]: ...
# Keep this alias in sync with unittest.case._ClassInfo
if sys.version_info >= (3, 10):
_ClassInfo: TypeAlias = type | types.UnionType | tuple[_ClassInfo, ...]
else:

View file

@ -75,6 +75,7 @@ def open(
For text mode, a BZ2File object is created, and wrapped in an
io.TextIOWrapper instance with the specified encoding, error
handling behavior, and line ending(s).
"""
@overload

View file

@ -87,7 +87,8 @@ def monthrange(year: int, month: int) -> tuple[int, int]:
"""
class Calendar:
"""Base calendar class. This class doesn't do any formatting. It simply
"""
Base calendar class. This class doesn't do any formatting. It simply
provides data to subclasses.
"""
@ -96,137 +97,183 @@ class Calendar:
def getfirstweekday(self) -> int: ...
def setfirstweekday(self, firstweekday: int) -> None: ...
def iterweekdays(self) -> Iterable[int]:
"""Return an iterator for one week of weekday numbers starting with the
"""
Return an iterator for one week of weekday numbers starting with the
configured first one.
"""
def itermonthdates(self, year: int, month: int) -> Iterable[datetime.date]:
"""Return an iterator for one month. The iterator will yield datetime.date
"""
Return an iterator for one month. The iterator will yield datetime.date
values and will always iterate through complete weeks, so it will yield
dates outside the specified month.
"""
def itermonthdays2(self, year: int, month: int) -> Iterable[tuple[int, int]]:
"""Like itermonthdates(), but will yield (day number, weekday number)
"""
Like itermonthdates(), but will yield (day number, weekday number)
tuples. For days outside the specified month the day number is 0.
"""
def itermonthdays(self, year: int, month: int) -> Iterable[int]:
"""Like itermonthdates(), but will yield day numbers. For days outside
"""
Like itermonthdates(), but will yield day numbers. For days outside
the specified month the day number is 0.
"""
def monthdatescalendar(self, year: int, month: int) -> list[list[datetime.date]]:
"""Return a matrix (list of lists) representing a month's calendar.
"""
Return a matrix (list of lists) representing a month's calendar.
Each row represents a week; week entries are datetime.date values.
"""
def monthdays2calendar(self, year: int, month: int) -> list[list[tuple[int, int]]]:
"""Return a matrix representing a month's calendar.
"""
Return a matrix representing a month's calendar.
Each row represents a week; week entries are
(day number, weekday number) tuples. Day numbers outside this month
are zero.
"""
def monthdayscalendar(self, year: int, month: int) -> list[list[int]]:
"""Return a matrix representing a month's calendar.
"""
Return a matrix representing a month's calendar.
Each row represents a week; days outside this month are zero.
"""
def yeardatescalendar(self, year: int, width: int = 3) -> list[list[list[list[datetime.date]]]]:
"""Return the data for the specified year ready for formatting. The return
"""
Return the data for the specified year ready for formatting. The return
value is a list of month rows. Each month row contains up to width months.
Each month contains between 4 and 6 weeks and each week contains 1-7
days. Days are datetime.date objects.
"""
def yeardays2calendar(self, year: int, width: int = 3) -> list[list[list[list[tuple[int, int]]]]]:
"""Return the data for the specified year ready for formatting (similar to
"""
Return the data for the specified year ready for formatting (similar to
yeardatescalendar()). Entries in the week lists are
(day number, weekday number) tuples. Day numbers outside this month are
zero.
"""
def yeardayscalendar(self, year: int, width: int = 3) -> list[list[list[list[int]]]]:
"""Return the data for the specified year ready for formatting (similar to
"""
Return the data for the specified year ready for formatting (similar to
yeardatescalendar()). Entries in the week lists are day numbers.
Day numbers outside this month are zero.
"""
def itermonthdays3(self, year: int, month: int) -> Iterable[tuple[int, int, int]]:
"""Like itermonthdates(), but will yield (year, month, day) tuples. Can be
"""
Like itermonthdates(), but will yield (year, month, day) tuples. Can be
used for dates outside of datetime.date range.
"""
def itermonthdays4(self, year: int, month: int) -> Iterable[tuple[int, int, int, int]]:
"""Like itermonthdates(), but will yield (year, month, day, day_of_week) tuples.
"""
Like itermonthdates(), but will yield (year, month, day, day_of_week) tuples.
Can be used for dates outside of datetime.date range.
"""
class TextCalendar(Calendar):
"""Subclass of Calendar that outputs a calendar as a simple plain text
"""
Subclass of Calendar that outputs a calendar as a simple plain text
similar to the UNIX program cal.
"""
def prweek(self, theweek: int, width: int) -> None:
"""Print a single week (no newline)."""
"""
Print a single week (no newline).
"""
def formatday(self, day: int, weekday: int, width: int) -> str:
"""Returns a formatted day."""
"""
Returns a formatted day.
"""
def formatweek(self, theweek: int, width: int) -> str:
"""Returns a single week in a string (no newline)."""
"""
Returns a single week in a string (no newline).
"""
def formatweekday(self, day: int, width: int) -> str:
"""Returns a formatted week day name."""
"""
Returns a formatted week day name.
"""
def formatweekheader(self, width: int) -> str:
"""Return a header for a week."""
"""
Return a header for a week.
"""
def formatmonthname(self, theyear: int, themonth: int, width: int, withyear: bool = True) -> str:
"""Return a formatted month name."""
"""
Return a formatted month name.
"""
def prmonth(self, theyear: int, themonth: int, w: int = 0, l: int = 0) -> None:
"""Print a month's calendar."""
"""
Print a month's calendar.
"""
def formatmonth(self, theyear: int, themonth: int, w: int = 0, l: int = 0) -> str:
"""Return a month's calendar string (multi-line)."""
"""
Return a month's calendar string (multi-line).
"""
def formatyear(self, theyear: int, w: int = 2, l: int = 1, c: int = 6, m: int = 3) -> str:
"""Returns a year's calendar as a multi-line string."""
"""
Returns a year's calendar as a multi-line string.
"""
def pryear(self, theyear: int, w: int = 0, l: int = 0, c: int = 6, m: int = 3) -> None:
"""Print a year's calendar."""
def firstweekday() -> int: ...
def monthcalendar(year: int, month: int) -> list[list[int]]:
"""Return a matrix representing a month's calendar.
"""
Return a matrix representing a month's calendar.
Each row represents a week; days outside this month are zero.
"""
def prweek(theweek: int, width: int) -> None:
"""Print a single week (no newline)."""
"""
Print a single week (no newline).
"""
def week(theweek: int, width: int) -> str:
"""Returns a single week in a string (no newline)."""
"""
Returns a single week in a string (no newline).
"""
def weekheader(width: int) -> str:
"""Return a header for a week."""
"""
Return a header for a week.
"""
def prmonth(theyear: int, themonth: int, w: int = 0, l: int = 0) -> None:
"""Print a month's calendar."""
"""
Print a month's calendar.
"""
def month(theyear: int, themonth: int, w: int = 0, l: int = 0) -> str:
"""Return a month's calendar string (multi-line)."""
"""
Return a month's calendar string (multi-line).
"""
def calendar(theyear: int, w: int = 2, l: int = 1, c: int = 6, m: int = 3) -> str:
"""Returns a year's calendar as a multi-line string."""
"""
Returns a year's calendar as a multi-line string.
"""
def prcal(theyear: int, w: int = 0, l: int = 0, c: int = 6, m: int = 3) -> None:
"""Print a year's calendar."""
class HTMLCalendar(Calendar):
"""This calendar returns complete HTML pages."""
"""
This calendar returns complete HTML pages.
"""
cssclasses: ClassVar[list[str]]
cssclass_noday: ClassVar[str]
@ -236,30 +283,46 @@ class HTMLCalendar(Calendar):
cssclass_year: ClassVar[str]
cssclass_year_head: ClassVar[str]
def formatday(self, day: int, weekday: int) -> str:
"""Return a day as a table cell."""
"""
Return a day as a table cell.
"""
def formatweek(self, theweek: int) -> str:
"""Return a complete week as a table row."""
"""
Return a complete week as a table row.
"""
def formatweekday(self, day: int) -> str:
"""Return a weekday name as a table header."""
"""
Return a weekday name as a table header.
"""
def formatweekheader(self) -> str:
"""Return a header for a week as a table row."""
"""
Return a header for a week as a table row.
"""
def formatmonthname(self, theyear: int, themonth: int, withyear: bool = True) -> str:
"""Return a month name as a table row."""
"""
Return a month name as a table row.
"""
def formatmonth(self, theyear: int, themonth: int, withyear: bool = True) -> str:
"""Return a formatted month as a table."""
"""
Return a formatted month as a table.
"""
def formatyear(self, theyear: int, width: int = 3) -> str:
"""Return a formatted year as a table of tables."""
"""
Return a formatted year as a table of tables.
"""
def formatyearpage(
self, theyear: int, width: int = 3, css: str | None = "calendar.css", encoding: str | None = None
) -> bytes:
"""Return a formatted year as a complete HTML page."""
"""
Return a formatted year as a complete HTML page.
"""
class different_locale:
def __init__(self, locale: _LocaleType) -> None: ...
@ -267,14 +330,16 @@ class different_locale:
def __exit__(self, *args: Unused) -> None: ...
class LocaleTextCalendar(TextCalendar):
"""This class can be passed a locale name in the constructor and will return
"""
This class can be passed a locale name in the constructor and will return
month and weekday names in the specified locale.
"""
def __init__(self, firstweekday: int = 0, locale: _LocaleType | None = None) -> None: ...
class LocaleHTMLCalendar(HTMLCalendar):
"""This class can be passed a locale name in the constructor and will return
"""
This class can be passed a locale name in the constructor and will return
month and weekday names in the specified locale.
"""

View file

@ -14,7 +14,7 @@ from builtins import list as _list, type as _type
from collections.abc import Iterable, Iterator, Mapping
from email.message import Message
from types import TracebackType
from typing import IO, Any, Protocol
from typing import IO, Any, Protocol, type_check_only
from typing_extensions import Self
__all__ = [
@ -78,6 +78,7 @@ def parse_multipart(
is a list of strings.
"""
@type_check_only
class _Environ(Protocol):
def __getitem__(self, k: str, /) -> str: ...
def keys(self) -> Iterable[str]: ...
@ -86,6 +87,7 @@ def parse_header(line: str) -> tuple[str, dict[str, str]]:
"""Parse a Content-type like header.
Return the main content-type and a dictionary of options.
"""
def test(environ: _Environ = ...) -> None:
@ -93,6 +95,7 @@ def test(environ: _Environ = ...) -> None:
Write minimal HTTP headers and dump all information provided to
the script in HTML form.
"""
def print_environ(environ: _Environ = ...) -> None:
@ -164,6 +167,7 @@ class FieldStorage:
a file open for reading and writing. This makes it possible to
override the default choice of storing all files in a temporary
directory and unlinking them as soon as they have been opened.
"""
FieldStorageClass: _type | None
@ -243,6 +247,7 @@ class FieldStorage:
max_num_fields: int. If set, then __init__ throws a ValueError
if there are more than n fields read by parse_qsl().
"""
def __enter__(self) -> Self: ...
@ -294,6 +299,7 @@ class FieldStorage:
that is nevertheless automatically deleted when the script
terminates, try defining a __del__ method in a derived class
which unlinks the temporary files you have created.
"""
def print_exception(

View file

@ -61,6 +61,7 @@ class Cmd:
framework. There is no good reason to instantiate Cmd itself; rather,
it's useful as a superclass of an interpreter class you define yourself
in order to inherit Cmd's methods and encapsulate action methods.
"""
prompt: str
@ -87,17 +88,20 @@ class Cmd:
is done automatically. The optional arguments stdin and stdout
specify alternate input and output file objects; if not specified,
sys.stdin and sys.stdout are used.
"""
old_completer: Callable[[str, int], str | None] | None
def cmdloop(self, intro: Any | None = None) -> None:
"""Repeatedly issue a prompt, accept input, parse an initial prefix
off the received input, and dispatch to action methods, passing them
the remainder of the line as argument.
"""
def precmd(self, line: str) -> str:
"""Hook method executed just before the command line is
interpreted, but after the input prompt is generated and issued.
"""
def postcmd(self, stop: bool, line: str) -> bool:
@ -109,6 +113,7 @@ class Cmd:
def postloop(self) -> None:
"""Hook method executed once when the cmdloop() method is about to
return.
"""
def parseline(self, line: str) -> tuple[str | None, str | None, str]:
@ -125,6 +130,7 @@ class Cmd:
see the precmd() and postcmd() methods for useful execution hooks.
The return value is a flag indicating whether interpretation of
commands by the interpreter should stop.
"""
def emptyline(self) -> bool:
@ -132,6 +138,7 @@ class Cmd:
If this method is not overridden, it repeats the last nonempty
command entered.
"""
def default(self, line: str) -> None:
@ -139,6 +146,7 @@ class Cmd:
If this method is not overridden, it prints an error message and
returns.
"""
def completedefault(self, *ignored: Any) -> list[str]:
@ -146,6 +154,7 @@ class Cmd:
complete_*() method is available.
By default, it returns an empty list.
"""
def completenames(self, text: str, *ignored: Any) -> list[str]: ...

View file

@ -14,6 +14,7 @@ class InteractiveInterpreter:
This class deals with parsing and interpreter state (the user's
namespace); it doesn't deal with input buffering or prompting or
input file naming (the filename is always passed in explicitly).
"""
locals: dict[str, Any] # undocumented
@ -25,6 +26,7 @@ class InteractiveInterpreter:
namespace in which code will be executed; it defaults to a newly
created dictionary with key "__name__" set to "__console__" and
key "__doc__" set to None.
"""
def runsource(self, source: str, filename: str = "<input>", symbol: str = "single") -> bool:
@ -49,6 +51,7 @@ class InteractiveInterpreter:
an exception is raised). The return value can be used to
decide whether to use sys.ps1 or sys.ps2 to prompt the next
line.
"""
def runcode(self, code: CodeType) -> None:
@ -61,6 +64,7 @@ class InteractiveInterpreter:
A note about KeyboardInterrupt: this exception may occur
elsewhere in this code, and may not always be caught. The
caller should be prepared to deal with it.
"""
if sys.version_info >= (3, 13):
def showsyntaxerror(self, filename: str | None = None, *, source: str = "") -> None:
@ -73,6 +77,7 @@ class InteractiveInterpreter:
"<string>" when reading from a string).
The output is written by self.write(), below.
"""
else:
def showsyntaxerror(self, filename: str | None = None) -> None:
@ -85,6 +90,7 @@ class InteractiveInterpreter:
"<string>" when reading from a string).
The output is written by self.write(), below.
"""
def showtraceback(self) -> None:
@ -93,6 +99,7 @@ class InteractiveInterpreter:
We remove the first stack item because it is our own code.
The output is written by self.write(), below.
"""
def write(self, data: str) -> None:
@ -100,6 +107,7 @@ class InteractiveInterpreter:
The base implementation writes to sys.stderr; a subclass may
replace this with a different implementation.
"""
class InteractiveConsole(InteractiveInterpreter):
@ -107,6 +115,7 @@ class InteractiveConsole(InteractiveInterpreter):
This class builds on InteractiveInterpreter and adds prompting
using the familiar sys.ps1 and sys.ps2, and input buffering.
"""
buffer: list[str] # undocumented
@ -122,6 +131,7 @@ class InteractiveConsole(InteractiveInterpreter):
The optional filename argument should specify the (file)name
of the input stream; it will show up in tracebacks.
"""
def push(self, line: str, filename: str | None = None) -> bool:
@ -136,6 +146,7 @@ class InteractiveConsole(InteractiveInterpreter):
is left as it was after the line was appended. The return
value is 1 if more input is required, 0 if the line was dealt
with in some way (this is the same as runsource()).
"""
else:
def __init__(self, locals: dict[str, Any] | None = None, filename: str = "<console>") -> None:
@ -146,6 +157,7 @@ class InteractiveConsole(InteractiveInterpreter):
The optional filename argument should specify the (file)name
of the input stream; it will show up in tracebacks.
"""
def push(self, line: str) -> bool:
@ -160,6 +172,7 @@ class InteractiveConsole(InteractiveInterpreter):
is left as it was after the line was appended. The return
value is 1 if more input is required, 0 if the line was dealt
with in some way (this is the same as runsource()).
"""
def interact(self, banner: str | None = None, exitmsg: str | None = None) -> None:
@ -176,6 +189,7 @@ class InteractiveConsole(InteractiveInterpreter):
printed when exiting. Pass the empty string to suppress
printing an exit message. If exitmsg is not given or None,
a default message is printed.
"""
def resetbuffer(self) -> None:
@ -190,6 +204,7 @@ class InteractiveConsole(InteractiveInterpreter):
The base implementation uses the built-in function
input(); a subclass may replace this with a different
implementation.
"""
if sys.version_info >= (3, 13):
@ -213,6 +228,7 @@ if sys.version_info >= (3, 13):
local -- passed to InteractiveInterpreter.__init__()
exitmsg -- passed to InteractiveConsole.interact()
local_exit -- passed to InteractiveConsole.__init__()
"""
else:
@ -234,4 +250,5 @@ else:
readfunc -- if not None, replaces InteractiveConsole.raw_input()
local -- passed to InteractiveInterpreter.__init__()
exitmsg -- passed to InteractiveConsole.interact()
"""

View file

@ -156,6 +156,7 @@ def getencoder(encoding: str) -> _Encoder:
its encoder function.
Raises a LookupError in case the encoding cannot be found.
"""
def getdecoder(encoding: str) -> _Decoder:
@ -163,6 +164,7 @@ def getdecoder(encoding: str) -> _Decoder:
its decoder function.
Raises a LookupError in case the encoding cannot be found.
"""
def getincrementalencoder(encoding: str) -> _IncrementalEncoder:
@ -171,6 +173,7 @@ def getincrementalencoder(encoding: str) -> _IncrementalEncoder:
Raises a LookupError in case the encoding cannot be found
or the codecs doesn't provide an incremental encoder.
"""
@overload
@ -180,6 +183,7 @@ def getincrementaldecoder(encoding: _BufferedEncoding) -> _BufferedIncrementalDe
Raises a LookupError in case the encoding cannot be found
or the codecs doesn't provide an incremental decoder.
"""
@overload
@ -189,6 +193,7 @@ def getreader(encoding: str) -> _StreamReader:
its StreamReader class or factory function.
Raises a LookupError in case the encoding cannot be found.
"""
def getwriter(encoding: str) -> _StreamWriter:
@ -196,6 +201,7 @@ def getwriter(encoding: str) -> _StreamWriter:
its StreamWriter class or factory function.
Raises a LookupError in case the encoding cannot be found.
"""
def open(
@ -252,10 +258,12 @@ def EncodedFile(file: _Stream, data_encoding: str, file_encoding: str | None = N
.data_encoding and .file_encoding which reflect the given
parameters of the same name. The attributes can be used for
introspection by Python programs.
"""
def iterencode(iterator: Iterable[str], encoding: str, errors: str = "strict") -> Generator[bytes, None, None]:
"""Encoding iterator.
"""
Encoding iterator.
Encodes the input strings from the iterator using an IncrementalEncoder.
@ -264,7 +272,8 @@ def iterencode(iterator: Iterable[str], encoding: str, errors: str = "strict") -
"""
def iterdecode(iterator: Iterable[bytes], encoding: str, errors: str = "strict") -> Generator[str, None, None]:
"""Decoding iterator.
"""
Decoding iterator.
Decodes the input strings from the iterator using an IncrementalDecoder.
@ -322,6 +331,7 @@ class Codec:
(only for encoding).
The set of allowed values can be extended via register_error.
"""
# These are sort of @abstractmethod but sort of not.
@ -340,6 +350,7 @@ class Codec:
The encoder must be able to handle zero length input and
return an empty object of the output object type in this
situation.
"""
def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]:
@ -360,17 +371,20 @@ class Codec:
The decoder must be able to handle zero length input and
return an empty object of the output object type in this
situation.
"""
class IncrementalEncoder:
"""An IncrementalEncoder encodes an input in multiple steps. The input can
"""
An IncrementalEncoder encodes an input in multiple steps. The input can
be passed piece by piece to the encode() method. The IncrementalEncoder
remembers the state of the encoding process between calls to encode().
"""
errors: str
def __init__(self, errors: str = "strict") -> None:
"""Creates an IncrementalEncoder instance.
"""
Creates an IncrementalEncoder instance.
The IncrementalEncoder may use different error handling schemes by
providing the errors keyword argument. See the module docstring
@ -379,28 +393,37 @@ class IncrementalEncoder:
@abstractmethod
def encode(self, input: str, final: bool = False) -> bytes:
"""Encodes input and returns the resulting object."""
"""
Encodes input and returns the resulting object.
"""
def reset(self) -> None:
"""Resets the encoder to the initial state."""
"""
Resets the encoder to the initial state.
"""
# documentation says int but str is needed for the subclass.
def getstate(self) -> int | str:
"""Return the current state of the encoder."""
"""
Return the current state of the encoder.
"""
def setstate(self, state: int | str) -> None:
"""Set the current state of the encoder. state must have been
"""
Set the current state of the encoder. state must have been
returned by getstate().
"""
class IncrementalDecoder:
"""An IncrementalDecoder decodes an input in multiple steps. The input can
"""
An IncrementalDecoder decodes an input in multiple steps. The input can
be passed piece by piece to the decode() method. The IncrementalDecoder
remembers the state of the decoding process between calls to decode().
"""
errors: str
def __init__(self, errors: str = "strict") -> None:
"""Create an IncrementalDecoder instance.
"""
Create an IncrementalDecoder instance.
The IncrementalDecoder may use different error handling schemes by
providing the errors keyword argument. See the module docstring
@ -409,13 +432,18 @@ class IncrementalDecoder:
@abstractmethod
def decode(self, input: ReadableBuffer, final: bool = False) -> str:
"""Decode input and returns the resulting object."""
"""
Decode input and returns the resulting object.
"""
def reset(self) -> None:
"""Reset the decoder to the initial state."""
"""
Reset the decoder to the initial state.
"""
def getstate(self) -> tuple[bytes, int]:
"""Return the current state of the decoder.
"""
Return the current state of the decoder.
This must be a (buffered_input, additional_state_info) tuple.
buffered_input must be a bytes object containing bytes that
@ -427,7 +455,8 @@ class IncrementalDecoder:
"""
def setstate(self, state: tuple[bytes, int]) -> None:
"""Set the current state of the decoder.
"""
Set the current state of the decoder.
state must have been returned by getstate(). The effect of
setstate((b"", 0)) must be equivalent to reset().
@ -435,7 +464,8 @@ class IncrementalDecoder:
# These are not documented but used in encodings/*.py implementations.
class BufferedIncrementalEncoder(IncrementalEncoder):
"""This subclass of IncrementalEncoder can be used as the baseclass for an
"""
This subclass of IncrementalEncoder can be used as the baseclass for an
incremental encoder if the encoder must keep some of the output in a
buffer between calls to encode().
"""
@ -447,7 +477,8 @@ class BufferedIncrementalEncoder(IncrementalEncoder):
def encode(self, input: str, final: bool = False) -> bytes: ...
class BufferedIncrementalDecoder(IncrementalDecoder):
"""This subclass of IncrementalDecoder can be used as the baseclass for an
"""
This subclass of IncrementalDecoder can be used as the baseclass for an
incremental decoder if the decoder must be able to handle incomplete
byte sequences.
"""
@ -500,6 +531,7 @@ class StreamWriter(Codec):
output is put into a clean state, that allows appending
of new fresh data without having to rescan the whole
stream to recover state.
"""
def seek(self, offset: int, whence: int = 0) -> None: ...
@ -564,6 +596,7 @@ class StreamReader(Codec):
size, if given, is passed as size argument to the
read() method.
"""
def readlines(self, sizehint: int | None = None, keepends: bool = True) -> list[str]:
@ -574,7 +607,8 @@ class StreamReader(Codec):
method and are included in the list entries.
sizehint, if given, is ignored since there is no efficient
way to finding the true end-of-line.
way of finding the true end-of-line.
"""
def reset(self) -> None:
@ -583,6 +617,7 @@ class StreamReader(Codec):
Note that no stream repositioning should take place.
This method is primarily intended to be able to recover
from decoding errors.
"""
def seek(self, offset: int, whence: int = 0) -> None:
@ -609,6 +644,7 @@ class StreamReaderWriter(TextIO):
The design is such that one can use the factory functions
returned by the codec.lookup() function to construct the
instance.
"""
stream: _Stream
@ -622,6 +658,7 @@ class StreamReaderWriter(TextIO):
Error handling is done in the same way as defined for the
StreamWriter/Readers.
"""
def read(self, size: int = -1) -> str: ...
@ -664,6 +701,7 @@ class StreamRecoder(BinaryIO):
In the other direction, data is read from the underlying stream using
a Reader instance and then encoded and returned to the caller.
"""
data_encoding: str
@ -693,6 +731,7 @@ class StreamRecoder(BinaryIO):
Error handling is done in the same way as defined for the
StreamWriter/Readers.
"""
def read(self, size: int = -1) -> bytes: ...

View file

@ -77,6 +77,7 @@ def namedtuple(
Point(x=11, y=22)
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
Point(x=100, y=22)
"""
class UserDict(MutableMapping[_KT, _VT]):
@ -404,6 +405,7 @@ class Counter(dict[_T, int], Generic[_T]):
>>> c['b'] -= 2 # reduce the count of 'b' by two
>>> c.most_common() # 'b' is still in, but its count is zero
[('a', 3), ('c', 1), ('b', 0)]
"""
@overload
@ -416,6 +418,7 @@ class Counter(dict[_T, int], Generic[_T]):
>>> c = Counter('gallahad') # a new counter from an iterable
>>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping
>>> c = Counter(a=4, b=2) # a new counter from keyword args
"""
@overload
@ -443,6 +446,7 @@ class Counter(dict[_T, int], Generic[_T]):
Note, if an element's count has been set to zero or is a negative
number, elements() will ignore it.
"""
def most_common(self, n: int | None = None) -> list[tuple[_T, int]]:
@ -451,6 +455,7 @@ class Counter(dict[_T, int], Generic[_T]):
>>> Counter('abracadabra').most_common(3)
[('a', 5), ('b', 2), ('r', 2)]
"""
@classmethod
@ -470,6 +475,7 @@ class Counter(dict[_T, int], Generic[_T]):
0
>>> c['w'] # 1 in which, minus 1 in witch, minus 1 in watch
-1
"""
@overload
@ -494,6 +500,7 @@ class Counter(dict[_T, int], Generic[_T]):
>>> c.update(d) # add elements from another counter
>>> c['h'] # four 'h' in which, witch, and watch
4
"""
@overload
@ -517,6 +524,7 @@ class Counter(dict[_T, int], Generic[_T]):
>>> Counter('abbb') + Counter('bcc')
Counter({'b': 4, 'c': 2, 'a': 1})
"""
def __sub__(self, other: Counter[_T]) -> Counter[_T]:
@ -524,6 +532,7 @@ class Counter(dict[_T, int], Generic[_T]):
>>> Counter('abbbc') - Counter('bccd')
Counter({'b': 2, 'a': 1})
"""
def __and__(self, other: Counter[_T]) -> Counter[_T]:
@ -531,6 +540,7 @@ class Counter(dict[_T, int], Generic[_T]):
>>> Counter('abbb') & Counter('bcc')
Counter({'b': 1})
"""
def __or__(self, other: Counter[_S]) -> Counter[_T | _S]: # type: ignore[override]
@ -538,6 +548,7 @@ class Counter(dict[_T, int], Generic[_T]):
>>> Counter('abbb') | Counter('bcc')
Counter({'b': 3, 'c': 2, 'a': 1})
"""
def __pos__(self) -> Counter[_T]:
@ -546,6 +557,7 @@ class Counter(dict[_T, int], Generic[_T]):
def __neg__(self) -> Counter[_T]:
"""Subtracts from an empty counter. Strips positive and zero counts,
and flips the sign on negative counts.
"""
# several type: ignores because __iadd__ is supposedly incompatible with __add__, etc.
def __iadd__(self, other: SupportsItems[_T, int]) -> Self: # type: ignore[misc]
@ -555,6 +567,7 @@ class Counter(dict[_T, int], Generic[_T]):
>>> c += Counter('bcc')
>>> c
Counter({'b': 4, 'c': 2, 'a': 1})
"""
def __isub__(self, other: SupportsItems[_T, int]) -> Self:
@ -564,6 +577,7 @@ class Counter(dict[_T, int], Generic[_T]):
>>> c -= Counter('bccd')
>>> c
Counter({'b': 2, 'a': 1})
"""
def __iand__(self, other: SupportsItems[_T, int]) -> Self:
@ -573,6 +587,7 @@ class Counter(dict[_T, int], Generic[_T]):
>>> c &= Counter('bcc')
>>> c
Counter({'b': 1})
"""
def __ior__(self, other: SupportsItems[_T, int]) -> Self: # type: ignore[override,misc]
@ -582,6 +597,7 @@ class Counter(dict[_T, int], Generic[_T]):
>>> c |= Counter('bcc')
>>> c
Counter({'b': 3, 'c': 2, 'a': 1})
"""
if sys.version_info >= (3, 10):
def total(self) -> int:
@ -779,12 +795,14 @@ class ChainMap(MutableMapping[_KT, _VT]):
Lookups search the underlying mappings successively until a key is found.
In contrast, writes, updates, and deletions only operate on the first
mapping.
"""
maps: list[MutableMapping[_KT, _VT]]
def __init__(self, *maps: MutableMapping[_KT, _VT]) -> None:
"""Initialize a ChainMap by setting *maps* to the given mappings.
If no mappings are provided, a single empty dictionary is used.
"""
def new_child(self, m: MutableMapping[_KT, _VT] | None = None) -> Self:

View file

@ -14,10 +14,11 @@ See module py_compile for details of the actual byte-compilation.
import sys
from _typeshed import StrPath
from py_compile import PycInvalidationMode
from typing import Any, Protocol
from typing import Any, Protocol, type_check_only
__all__ = ["compile_dir", "compile_file", "compile_path"]
@type_check_only
class _SupportsSearch(Protocol):
def search(self, string: str, /) -> Any: ...

View file

@ -21,7 +21,7 @@ from .thread import ThreadPoolExecutor as ThreadPoolExecutor
if sys.version_info >= (3, 14):
from .interpreter import InterpreterPoolExecutor as InterpreterPoolExecutor
__all__ = (
__all__ = [
"FIRST_COMPLETED",
"FIRST_EXCEPTION",
"ALL_COMPLETED",
@ -36,7 +36,7 @@ if sys.version_info >= (3, 14):
"ProcessPoolExecutor",
"ThreadPoolExecutor",
"InterpreterPoolExecutor",
)
]
elif sys.version_info >= (3, 13):
__all__ = (

View file

@ -35,7 +35,9 @@ class InvalidStateError(Error):
"""The operation is not allowed in this state."""
class BrokenExecutor(RuntimeError):
"""Raised when a executor has become non-functional after a severe failure."""
"""
Raised when a executor has become non-functional after a severe failure.
"""
_T = TypeVar("_T")
_T_co = TypeVar("_T_co", covariant=True)

View file

@ -58,7 +58,9 @@ if sys.version_info >= (3, 14):
def run(self, task: _Task) -> None: ... # type: ignore[override]
class BrokenInterpreterPool(BrokenThreadPool):
"""Raised when a worker thread in an InterpreterPoolExecutor failed initializing."""
"""
Raised when a worker thread in an InterpreterPoolExecutor failed initializing.
"""
class InterpreterPoolExecutor(ThreadPoolExecutor):
BROKEN: type[BrokenInterpreterPool]

View file

@ -151,6 +151,7 @@ def _process_chunk(fn: Callable[..., _T], chunk: Iterable[tuple[Any, ...]]) -> l
iterable passed to map.
This function is run in a separate process.
"""
if sys.version_info >= (3, 11):
@ -247,13 +248,15 @@ _system_limited: bool | None
def _check_system_limits() -> None: ...
def _chain_from_iterable_of_lists(iterable: Iterable[MutableSequence[Any]]) -> Any:
"""Specialized implementation of itertools.chain.from_iterable.
"""
Specialized implementation of itertools.chain.from_iterable.
Each item in *iterable* should be a list. This function is
careful not to keep references to yielded objects.
"""
class BrokenProcessPool(BrokenExecutor):
"""Raised when a process in a ProcessPoolExecutor terminated abruptly
"""
Raised when a process in a ProcessPoolExecutor terminated abruptly
while a future was in the running state.
"""

View file

@ -89,7 +89,9 @@ else:
) -> None: ...
class BrokenThreadPool(BrokenExecutor):
"""Raised when a worker thread in a ThreadPoolExecutor failed initializing."""
"""
Raised when a worker thread in a ThreadPoolExecutor failed initializing.
"""
class ThreadPoolExecutor(Executor):
if sys.version_info >= (3, 14):

View file

@ -0,0 +1,142 @@
"""Subinterpreters High Level Module."""
import sys
import threading
import types
from collections.abc import Callable
from typing import Any, Literal, TypeVar
from typing_extensions import ParamSpec, Self
if sys.version_info >= (3, 13): # needed to satisfy pyright checks for Python <3.13
from _interpreters import (
InterpreterError as InterpreterError,
InterpreterNotFoundError as InterpreterNotFoundError,
NotShareableError as NotShareableError,
_SharedDict,
_Whence,
is_shareable as is_shareable,
)
from ._queues import Queue as Queue, QueueEmpty as QueueEmpty, QueueFull as QueueFull, create as create_queue
__all__ = [
"ExecutionFailed",
"Interpreter",
"InterpreterError",
"InterpreterNotFoundError",
"NotShareableError",
"Queue",
"QueueEmpty",
"QueueFull",
"create",
"create_queue",
"get_current",
"get_main",
"is_shareable",
"list_all",
]
_R = TypeVar("_R")
_P = ParamSpec("_P")
class ExecutionFailed(InterpreterError):
"""An unhandled exception happened during execution.
This is raised from Interpreter.exec() and Interpreter.call().
"""
excinfo: types.SimpleNamespace
def __init__(self, excinfo: types.SimpleNamespace) -> None: ...
def create() -> Interpreter:
"""Return a new (idle) Python interpreter."""
def list_all() -> list[Interpreter]:
"""Return all existing interpreters."""
def get_current() -> Interpreter:
"""Return the currently running interpreter."""
def get_main() -> Interpreter:
"""Return the main interpreter."""
class Interpreter:
"""A single Python interpreter.
Attributes:
"id" - the unique process-global ID number for the interpreter
"whence" - indicates where the interpreter was created
If the interpreter wasn't created by this module
then any method that modifies the interpreter will fail,
i.e. .close(), .prepare_main(), .exec(), and .call()
"""
def __new__(cls, id: int, /, _whence: _Whence | None = None, _ownsref: bool | None = None) -> Self: ...
def __reduce__(self) -> tuple[type[Self], int]: ...
def __hash__(self) -> int: ...
def __del__(self) -> None: ...
@property
def id(self) -> int: ...
@property
def whence(
self,
) -> Literal["unknown", "runtime init", "legacy C-API", "C-API", "cross-interpreter C-API", "_interpreters module"]: ...
def is_running(self) -> bool:
"""Return whether or not the identified interpreter is running."""
def close(self) -> None:
"""Finalize and destroy the interpreter.
Attempting to destroy the current interpreter results
in an InterpreterError.
"""
def prepare_main(
self, ns: _SharedDict | None = None, /, **kwargs: Any
) -> None: # kwargs has same value restrictions as _SharedDict
"""Bind the given values into the interpreter's __main__.
The values must be shareable.
"""
def exec(self, code: str | types.CodeType | Callable[[], object], /) -> None:
"""Run the given source code in the interpreter.
This is essentially the same as calling the builtin "exec"
with this interpreter, using the __dict__ of its __main__
module as both globals and locals.
There is no return value.
If the code raises an unhandled exception then an ExecutionFailed
exception is raised, which summarizes the unhandled exception.
The actual exception is discarded because objects cannot be
shared between interpreters.
This blocks the current Python thread until done. During
that time, the previous interpreter is allowed to run
in other threads.
"""
def call(self, callable: Callable[_P, _R], /, *args: _P.args, **kwargs: _P.kwargs) -> _R:
"""Call the object in the interpreter with given args/kwargs.
Nearly all callables, args, kwargs, and return values are
supported. All "shareable" objects are supported, as are
"stateless" functions (meaning non-closures that do not use
any globals). This method will fall back to pickle.
If the callable raises an exception then the error display
(including full traceback) is sent back between the interpreters
and an ExecutionFailed exception is raised, much like what
happens with Interpreter.exec().
"""
def call_in_thread(self, callable: Callable[_P, object], /, *args: _P.args, **kwargs: _P.kwargs) -> threading.Thread:
"""Return a new thread that calls the object in the interpreter.
The return value and any raised exception are discarded.
"""

View file

@ -0,0 +1,44 @@
"""Common code between queues and channels."""
import sys
from collections.abc import Callable
from typing import Final, NewType
from typing_extensions import Never, Self, TypeAlias
if sys.version_info >= (3, 13): # needed to satisfy pyright checks for Python <3.13
from _interpqueues import _UnboundOp
class ItemInterpreterDestroyed(Exception):
"""Raised when trying to get an item whose interpreter was destroyed."""
# Actually a descriptor that behaves similarly to classmethod but prevents
# access from instances.
classonly = classmethod
class UnboundItem:
"""Represents a cross-interpreter item no longer bound to an interpreter.
An item is unbound when the interpreter that added it to the
cross-interpreter container is destroyed.
"""
def __new__(cls) -> Never: ...
@classonly
def singleton(cls, kind: str, module: str, name: str = "UNBOUND") -> Self:
"""A non-data descriptor that makes a value only visible on the class.
This is like the "classmethod" builtin, but does not show up on
instances of the class. It may be used as a decorator.
"""
# Sentinel types and alias that don't exist at runtime.
_UnboundErrorType = NewType("_UnboundErrorType", object)
_UnboundRemoveType = NewType("_UnboundRemoveType", object)
_AnyUnbound: TypeAlias = _UnboundErrorType | _UnboundRemoveType | UnboundItem
UNBOUND_ERROR: Final[_UnboundErrorType]
UNBOUND_REMOVE: Final[_UnboundRemoveType]
UNBOUND: Final[UnboundItem] # analogous to UNBOUND_REPLACE in C
def serialize_unbound(unbound: _AnyUnbound) -> tuple[_UnboundOp]: ...
def resolve_unbound(flag: _UnboundOp, exctype_destroyed: Callable[[str], BaseException]) -> UnboundItem: ...

View file

@ -0,0 +1,134 @@
"""Cross-interpreter Queues High Level Module."""
import queue
import sys
from typing import Final, SupportsIndex
from typing_extensions import Self
if sys.version_info >= (3, 13): # needed to satisfy pyright checks for Python <3.13
from _interpqueues import QueueError as QueueError, QueueNotFoundError as QueueNotFoundError
from . import _crossinterp
from ._crossinterp import UNBOUND_ERROR as UNBOUND_ERROR, UNBOUND_REMOVE as UNBOUND_REMOVE, UnboundItem, _AnyUnbound
__all__ = [
"UNBOUND",
"UNBOUND_ERROR",
"UNBOUND_REMOVE",
"ItemInterpreterDestroyed",
"Queue",
"QueueEmpty",
"QueueError",
"QueueFull",
"QueueNotFoundError",
"create",
"list_all",
]
class QueueEmpty(QueueError, queue.Empty):
"""Raised from get_nowait() when the queue is empty.
It is also raised from get() if it times out.
"""
class QueueFull(QueueError, queue.Full):
"""Raised from put_nowait() when the queue is full.
It is also raised from put() if it times out.
"""
class ItemInterpreterDestroyed(QueueError, _crossinterp.ItemInterpreterDestroyed):
"""Raised from get() and get_nowait()."""
UNBOUND: Final[UnboundItem]
def create(maxsize: int = 0, *, unbounditems: _AnyUnbound = ...) -> Queue:
"""Return a new cross-interpreter queue.
The queue may be used to pass data safely between interpreters.
"unbounditems" sets the default for Queue.put(); see that method for
supported values. The default value is UNBOUND, which replaces
the unbound item.
"""
def list_all() -> list[Queue]:
"""Return a list of all open queues."""
class Queue:
"""A cross-interpreter queue."""
def __new__(cls, id: int, /) -> Self: ...
def __del__(self) -> None: ...
def __hash__(self) -> int: ...
def __reduce__(self) -> tuple[type[Self], int]: ...
@property
def id(self) -> int: ...
@property
def unbounditems(self) -> _AnyUnbound: ...
@property
def maxsize(self) -> int: ...
def empty(self) -> bool: ...
def full(self) -> bool: ...
def qsize(self) -> int: ...
def put(
self,
obj: object,
timeout: SupportsIndex | None = None,
*,
unbounditems: _AnyUnbound | None = None,
_delay: float = ...,
) -> None:
"""Add the object to the queue.
This blocks while the queue is full.
For most objects, the object received through Queue.get() will
be a new one, equivalent to the original and not sharing any
actual underlying data. The notable exceptions include
cross-interpreter types (like Queue) and memoryview, where the
underlying data is actually shared. Furthermore, some types
can be sent through a queue more efficiently than others. This
group includes various immutable types like int, str, bytes, and
tuple (if the items are likewise efficiently shareable). See interpreters.is_shareable().
"unbounditems" controls the behavior of Queue.get() for the given
object if the current interpreter (calling put()) is later
destroyed.
If "unbounditems" is None (the default) then it uses the
queue's default, set with create_queue(),
which is usually UNBOUND.
If "unbounditems" is UNBOUND_ERROR then get() will raise an
ItemInterpreterDestroyed exception if the original interpreter
has been destroyed. This does not otherwise affect the queue;
the next call to put() will work like normal, returning the next
item in the queue.
If "unbounditems" is UNBOUND_REMOVE then the item will be removed
from the queue as soon as the original interpreter is destroyed.
Be aware that this will introduce an imbalance between put()
and get() calls.
If "unbounditems" is UNBOUND then it is returned by get() in place
of the unbound item.
"""
def put_nowait(self, obj: object, *, unbounditems: _AnyUnbound | None = None) -> None: ...
def get(self, timeout: SupportsIndex | None = None, *, _delay: float = ...) -> object:
"""Return the next object from the queue.
This blocks while the queue is empty.
If the next item's original interpreter has been destroyed
then the "next object" is determined by the value of the
"unbounditems" argument to put().
"""
def get_nowait(self) -> object:
"""Return the next object from the channel.
If the queue is empty then raise QueueEmpty. Otherwise this
is the same as get().
"""

View file

@ -648,6 +648,7 @@ class SectionProxy(MutableMapping[str, str]):
Unless `fallback` is provided, `None` will be returned if the option
is not found.
"""
@overload
@ -664,17 +665,17 @@ class SectionProxy(MutableMapping[str, str]):
# These are partially-applied version of the methods with the same names in
# RawConfigParser; the stubs should be kept updated together
@overload
def getint(self, option: str, *, raw: bool = ..., vars: _Section | None = ...) -> int | None: ...
def getint(self, option: str, *, raw: bool = False, vars: _Section | None = None) -> int | None: ...
@overload
def getint(self, option: str, fallback: _T = ..., *, raw: bool = ..., vars: _Section | None = ...) -> int | _T: ...
def getint(self, option: str, fallback: _T = ..., *, raw: bool = False, vars: _Section | None = None) -> int | _T: ...
@overload
def getfloat(self, option: str, *, raw: bool = ..., vars: _Section | None = ...) -> float | None: ...
def getfloat(self, option: str, *, raw: bool = False, vars: _Section | None = None) -> float | None: ...
@overload
def getfloat(self, option: str, fallback: _T = ..., *, raw: bool = ..., vars: _Section | None = ...) -> float | _T: ...
def getfloat(self, option: str, fallback: _T = ..., *, raw: bool = False, vars: _Section | None = None) -> float | _T: ...
@overload
def getboolean(self, option: str, *, raw: bool = ..., vars: _Section | None = ...) -> bool | None: ...
def getboolean(self, option: str, *, raw: bool = False, vars: _Section | None = None) -> bool | None: ...
@overload
def getboolean(self, option: str, fallback: _T = ..., *, raw: bool = ..., vars: _Section | None = ...) -> bool | _T: ...
def getboolean(self, option: str, fallback: _T = ..., *, raw: bool = False, vars: _Section | None = None) -> bool | _T: ...
# SectionProxy can have arbitrary attributes when custom converters are used
def __getattr__(self, key: str) -> Callable[..., Any]: ...

View file

@ -6,7 +6,7 @@ from _typeshed import FileDescriptorOrPath, Unused
from abc import ABC, abstractmethod
from collections.abc import AsyncGenerator, AsyncIterator, Awaitable, Callable, Generator, Iterator
from types import TracebackType
from typing import IO, Any, Generic, Protocol, TypeVar, overload, runtime_checkable
from typing import IO, Any, Generic, Protocol, TypeVar, overload, runtime_checkable, type_check_only
from typing_extensions import ParamSpec, Self, TypeAlias
__all__ = [
@ -201,6 +201,7 @@ def asynccontextmanager(func: Callable[_P, AsyncIterator[_T_co]]) -> Callable[_P
<cleanup>
"""
@type_check_only
class _SupportsClose(Protocol):
def close(self) -> object: ...
@ -221,12 +222,14 @@ class closing(AbstractContextManager[_SupportsCloseT, None]):
<block>
finally:
f.close()
"""
def __init__(self, thing: _SupportsCloseT) -> None: ...
def __exit__(self, *exc_info: Unused) -> None: ...
if sys.version_info >= (3, 10):
@type_check_only
class _SupportsAclose(Protocol):
def aclose(self) -> Awaitable[object]: ...
@ -248,6 +251,7 @@ if sys.version_info >= (3, 10):
<block>
finally:
await agen.aclose()
"""
def __init__(self, thing: _SupportsAcloseT) -> None: ...

View file

@ -50,7 +50,7 @@ __getstate__() and __setstate__(). See the documentation for module
"""
import sys
from typing import Any, Protocol, TypeVar
from typing import Any, Protocol, TypeVar, type_check_only
from typing_extensions import Self
__all__ = ["Error", "copy", "deepcopy"]
@ -58,6 +58,7 @@ __all__ = ["Error", "copy", "deepcopy"]
_T = TypeVar("_T")
_SR = TypeVar("_SR", bound=_SupportsReplace)
@type_check_only
class _SupportsReplace(Protocol):
# In reality doesn't support args, but there's no other great way to express this.
def __replace__(self, *args: Any, **kwargs: Any) -> Self: ...

View file

@ -26,6 +26,7 @@ if sys.platform != "win32":
"""Generate a salt for the specified method.
If not specified, the strongest available method will be used.
"""
def crypt(word: str, salt: str | _Method | None = None) -> str:
@ -36,4 +37,5 @@ if sys.platform != "win32":
available method will be selected and a salt generated. Otherwise,
``salt`` may be one of the ``crypt.METHOD_*`` values, or a string as
returned by ``crypt.mksalt()``.
"""

View file

@ -128,6 +128,7 @@ class Dialect:
This must be subclassed (see csv.excel). Valid attributes are:
delimiter, quotechar, escapechar, doublequote, skipinitialspace,
lineterminator, quoting.
"""
delimiter: str
@ -234,12 +235,15 @@ class DictWriter(Generic[_T]):
"""
class Sniffer:
""" "Sniffs" the format of a CSV file (i.e. delimiter, quotechar)
"""
"Sniffs" the format of a CSV file (i.e. delimiter, quotechar)
Returns a Dialect object.
"""
preferred: list[str]
def sniff(self, sample: str, delimiters: str | None = None) -> type[Dialect]:
"""Returns a dialect (or None) corresponding to the sample"""
"""
Returns a dialect (or None) corresponding to the sample
"""
def has_header(self, sample: str) -> bool: ...

View file

@ -13,6 +13,7 @@ from _ctypes import (
_CData as _CData,
_CDataType as _CDataType,
_CField as _CField,
_CTypeBaseType,
_Pointer as _Pointer,
_PointerLike as _PointerLike,
_SimpleCData as _SimpleCData,
@ -231,7 +232,7 @@ def create_unicode_buffer(init: int | str, size: int | None = None) -> Array[c_w
"""
@deprecated("Deprecated in Python 3.13; removal scheduled for Python 3.15")
def SetPointerType(pointer: type[_Pointer[Any]], cls: Any) -> None: ...
def SetPointerType(pointer: type[_Pointer[Any]], cls: _CTypeBaseType) -> None: ...
def ARRAY(typ: _CT, len: int) -> Array[_CT]: ... # Soft Deprecated, no plans to remove
if sys.platform == "win32":

View file

@ -9,10 +9,13 @@ from ctypes.macholib.framework import framework_info as framework_info
__all__ = ["dyld_find", "framework_find", "framework_info", "dylib_info"]
def dyld_find(name: str, executable_path: str | None = None, env: Mapping[str, str] | None = None) -> str:
"""Find a library or framework using dyld semantics"""
"""
Find a library or framework using dyld semantics
"""
def framework_find(fn: str, executable_path: str | None = None, env: Mapping[str, str] | None = None) -> str:
"""Find a framework using dyld semantics in a very loose manner.
"""
Find a framework using dyld semantics in a very loose manner.
Will take input such as:
Python

View file

@ -16,7 +16,8 @@ class _DylibInfo(TypedDict):
suffix: str | None
def dylib_info(filename: str) -> _DylibInfo | None:
"""A dylib name can take one of the following four forms:
"""
A dylib name can take one of the following four forms:
Location/Name.SomeVersion_Suffix.dylib
Location/Name.SomeVersion.dylib
Location/Name_Suffix.dylib

View file

@ -16,7 +16,8 @@ class _FrameworkInfo(TypedDict):
suffix: str | None
def framework_info(filename: str) -> _FrameworkInfo | None:
"""A framework name can take one of the following four forms:
"""
A framework name can take one of the following four forms:
Location/Name.framework/Versions/SomeVersion/Name_Suffix
Location/Name.framework/Versions/SomeVersion/Name
Location/Name.framework/Name_Suffix

View file

@ -193,13 +193,13 @@ class time:
resolution: ClassVar[timedelta]
def __new__(
cls,
hour: SupportsIndex = ...,
minute: SupportsIndex = ...,
second: SupportsIndex = ...,
microsecond: SupportsIndex = ...,
tzinfo: _TzInfo | None = ...,
hour: SupportsIndex = 0,
minute: SupportsIndex = 0,
second: SupportsIndex = 0,
microsecond: SupportsIndex = 0,
tzinfo: _TzInfo | None = None,
*,
fold: int = ...,
fold: int = 0,
) -> Self: ...
@property
def hour(self) -> int: ...
@ -219,7 +219,7 @@ class time:
def __gt__(self, value: time, /) -> bool: ...
def __eq__(self, value: object, /) -> bool: ...
def __hash__(self) -> int: ...
def isoformat(self, timespec: str = ...) -> str:
def isoformat(self, timespec: str = "auto") -> str:
"""Return string in ISO 8601 format, [HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM].
The optional argument timespec specifies the number of additional terms
@ -298,13 +298,13 @@ class timedelta:
resolution: ClassVar[timedelta]
def __new__(
cls,
days: float = ...,
seconds: float = ...,
microseconds: float = ...,
milliseconds: float = ...,
minutes: float = ...,
hours: float = ...,
weeks: float = ...,
days: float = 0,
seconds: float = 0,
microseconds: float = 0,
milliseconds: float = 0,
minutes: float = 0,
hours: float = 0,
weeks: float = 0,
) -> Self: ...
@property
def days(self) -> int:
@ -390,13 +390,13 @@ class datetime(date):
year: SupportsIndex,
month: SupportsIndex,
day: SupportsIndex,
hour: SupportsIndex = ...,
minute: SupportsIndex = ...,
second: SupportsIndex = ...,
microsecond: SupportsIndex = ...,
tzinfo: _TzInfo | None = ...,
hour: SupportsIndex = 0,
minute: SupportsIndex = 0,
second: SupportsIndex = 0,
microsecond: SupportsIndex = 0,
tzinfo: _TzInfo | None = None,
*,
fold: int = ...,
fold: int = 0,
) -> Self: ...
@property
def hour(self) -> int: ...
@ -415,11 +415,11 @@ class datetime(date):
# meaning it is only *safe* to pass it as a keyword argument on 3.12+
if sys.version_info >= (3, 12):
@classmethod
def fromtimestamp(cls, timestamp: float, tz: _TzInfo | None = ...) -> Self:
def fromtimestamp(cls, timestamp: float, tz: _TzInfo | None = None) -> Self:
"""timestamp[, tz] -> tz's local time from POSIX timestamp."""
else:
@classmethod
def fromtimestamp(cls, timestamp: float, /, tz: _TzInfo | None = ...) -> Self:
def fromtimestamp(cls, timestamp: float, /, tz: _TzInfo | None = None) -> Self:
"""timestamp[, tz] -> tz's local time from POSIX timestamp."""
@classmethod
@ -492,10 +492,10 @@ class datetime(date):
) -> Self:
"""Return datetime with new specified fields."""
def astimezone(self, tz: _TzInfo | None = ...) -> Self:
def astimezone(self, tz: _TzInfo | None = None) -> Self:
"""tz -> convert to local time in new timezone tz"""
def isoformat(self, sep: str = ..., timespec: str = ...) -> str:
def isoformat(self, sep: str = "T", timespec: str = "auto") -> str:
"""[sep] -> string in ISO 8601 format, YYYY-MM-DDT[HH[:MM[:SS[.mmm[uuu]]]]][+HH:MM].
sep is used to separate the year from the time, and defaults to 'T'.
The optional argument timespec specifies the number of additional terms

View file

@ -66,6 +66,7 @@ if sys.version_info >= (3, 11):
The optional mode argument is the UNIX mode of the file, used only when
the database has to be created. It defaults to octal code 0o666 (and
will be modified by the prevailing umask).
"""
else:
@ -81,4 +82,5 @@ else:
The optional mode argument is the UNIX mode of the file, used only when
the database has to be created. It defaults to octal code 0o666 (and
will be modified by the prevailing umask).
"""

View file

@ -175,6 +175,7 @@ class Decimal:
or another Decimal object. If no value is given, return Decimal('0'). The
context does not affect the conversion and is only passed to determine if
the InvalidOperation trap is active.
"""
def __new__(cls, value: _DecimalNew = "0", context: Context | None = None) -> Self: ...
@ -189,6 +190,8 @@ class Decimal:
Decimal('0.1000000000000000055511151231257827021181583404541015625')
>>> Decimal.from_number(Decimal('3.14')) # another decimal instance
Decimal('3.14')
"""
@classmethod
@ -205,6 +208,8 @@ class Decimal:
Decimal('Infinity')
>>> Decimal.from_float(float('-inf'))
Decimal('-Infinity')
"""
def __bool__(self) -> bool:
@ -217,6 +222,7 @@ class Decimal:
a < b ==> Decimal('-1')
a == b ==> Decimal('0')
a > b ==> Decimal('1')
"""
def __hash__(self) -> int: ...
@ -229,6 +235,7 @@ class Decimal:
Return a pair of integers, whose ratio is exactly equal to the original
Decimal and with a positive denominator. The ratio is in lowest terms.
Raise OverflowError on infinities and a ValueError on NaNs.
"""
def to_eng_string(self, context: Context | None = None) -> str:
@ -238,6 +245,7 @@ class Decimal:
The value of context.capitals determines whether the exponent sign is lower
or upper case. Otherwise, the context does not affect the operation.
"""
def __abs__(self) -> Decimal:
@ -307,6 +315,7 @@ class Decimal:
if two integers are equally near then the even one is chosen.
If the result is zero then its sign will be the sign of self.
"""
def __float__(self) -> float:
@ -336,6 +345,8 @@ class Decimal:
>>> Decimal(2).fma(3, 5)
Decimal('11')
"""
def __rpow__(self, value: _Decimal, mod: Context | None = None, /) -> Decimal:
@ -347,6 +358,7 @@ class Decimal:
for producing canonical values for members of an equivalence class.
For example, Decimal('32.100') and Decimal('0.321000e+2') both normalize
to the equivalent value Decimal('32.1').
"""
def quantize(self, exp: _Decimal, rounding: str | None = None, context: Context | None = None) -> Decimal:
@ -368,6 +380,7 @@ class Decimal:
rounding may be necessary. In this case, the rounding mode is determined by the
rounding argument if given, else by the given context argument; if neither
argument is given, the rounding mode of the current thread's context is used.
"""
def same_quantum(self, other: _Decimal, context: Context | None = None) -> bool:
@ -376,6 +389,7 @@ class Decimal:
This operation is unaffected by context and is quiet: no flags are changed
and no rounding is performed. As an exception, the C version may raise
InvalidOperation if the second operand cannot be converted exactly.
"""
def to_integral_exact(self, rounding: str | None = None, context: Context | None = None) -> Decimal:
@ -383,6 +397,7 @@ class Decimal:
rounding occurs. The rounding mode is determined by the rounding parameter
if given, else by the given context. If neither parameter is given, then the
rounding mode of the current default context is used.
"""
def to_integral_value(self, rounding: str | None = None, context: Context | None = None) -> Decimal:
@ -390,26 +405,31 @@ class Decimal:
rounding mode is determined by the rounding parameter if given, else by
the given context. If neither parameter is given, then the rounding mode
of the current default context is used.
"""
def to_integral(self, rounding: str | None = None, context: Context | None = None) -> Decimal:
"""Identical to the to_integral_value() method. The to_integral() name has been
kept for compatibility with older versions.
"""
def sqrt(self, context: Context | None = None) -> Decimal:
"""Return the square root of the argument to full precision. The result is
correctly rounded using the ROUND_HALF_EVEN rounding mode.
"""
def max(self, other: _Decimal, context: Context | None = None) -> Decimal:
"""Maximum of self and other. If one operand is a quiet NaN and the other is
numeric, the numeric operand is returned.
"""
def min(self, other: _Decimal, context: Context | None = None) -> Decimal:
"""Minimum of self and other. If one operand is a quiet NaN and the other is
numeric, the numeric operand is returned.
"""
def adjusted(self) -> int:
@ -419,6 +439,7 @@ class Decimal:
"""Return the canonical encoding of the argument. Currently, the encoding
of a Decimal instance is always canonical, so this operation returns its
argument unchanged.
"""
def compare_signal(self, other: _Decimal, context: Context | None = None) -> Decimal:
@ -443,6 +464,7 @@ class Decimal:
This operation is unaffected by context and is quiet: no flags are changed
and no rounding is performed. As an exception, the C version may raise
InvalidOperation if the second operand cannot be converted exactly.
"""
def compare_total_mag(self, other: _Decimal, context: Context | None = None) -> Decimal:
@ -454,16 +476,19 @@ class Decimal:
This operation is unaffected by context and is quiet: no flags are changed
and no rounding is performed. As an exception, the C version may raise
InvalidOperation if the second operand cannot be converted exactly.
"""
def copy_abs(self) -> Decimal:
"""Return the absolute value of the argument. This operation is unaffected by
context and is quiet: no flags are changed and no rounding is performed.
"""
def copy_negate(self) -> Decimal:
"""Return the negation of the argument. This operation is unaffected by context
and is quiet: no flags are changed and no rounding is performed.
"""
def copy_sign(self, other: _Decimal, context: Context | None = None) -> Decimal:
@ -476,39 +501,46 @@ class Decimal:
This operation is unaffected by context and is quiet: no flags are changed
and no rounding is performed. As an exception, the C version may raise
InvalidOperation if the second operand cannot be converted exactly.
"""
def exp(self, context: Context | None = None) -> Decimal:
"""Return the value of the (natural) exponential function e**x at the given
number. The function always uses the ROUND_HALF_EVEN mode and the result
is correctly rounded.
"""
def is_canonical(self) -> bool:
"""Return True if the argument is canonical and False otherwise. Currently,
a Decimal instance is always canonical, so this operation always returns
True.
"""
def is_finite(self) -> bool:
"""Return True if the argument is a finite number, and False if the argument
is infinite or a NaN.
"""
def is_infinite(self) -> bool:
"""Return True if the argument is either positive or negative infinity and
False otherwise.
"""
def is_nan(self) -> bool:
"""Return True if the argument is a (quiet or signaling) NaN and False
otherwise.
"""
def is_normal(self, context: Context | None = None) -> bool:
"""Return True if the argument is a normal finite non-zero number with an
adjusted exponent greater than or equal to Emin. Return False if the
argument is zero, subnormal, infinite or a NaN.
"""
def is_qnan(self) -> bool:
@ -517,6 +549,7 @@ class Decimal:
def is_signed(self) -> bool:
"""Return True if the argument has a negative sign and False otherwise.
Note that both zeros and NaNs can carry signs.
"""
def is_snan(self) -> bool:
@ -526,21 +559,25 @@ class Decimal:
"""Return True if the argument is subnormal, and False otherwise. A number is
subnormal if it is non-zero, finite, and has an adjusted exponent less
than Emin.
"""
def is_zero(self) -> bool:
"""Return True if the argument is a (positive or negative) zero and False
otherwise.
"""
def ln(self, context: Context | None = None) -> Decimal:
"""Return the natural (base e) logarithm of the operand. The function always
uses the ROUND_HALF_EVEN mode and the result is correctly rounded.
"""
def log10(self, context: Context | None = None) -> Decimal:
"""Return the base ten logarithm of the operand. The function always uses the
ROUND_HALF_EVEN mode and the result is correctly rounded.
"""
def logb(self, context: Context | None = None) -> Decimal:
@ -548,6 +585,7 @@ class Decimal:
Decimal instance. If the operand is a zero, then Decimal('-Infinity') is
returned and the DivisionByZero condition is raised. If the operand is
an infinity then Decimal('Infinity') is returned.
"""
def logical_and(self, other: _Decimal, context: Context | None = None) -> Decimal:
@ -565,23 +603,27 @@ class Decimal:
def max_mag(self, other: _Decimal, context: Context | None = None) -> Decimal:
"""Similar to the max() method, but the comparison is done using the absolute
values of the operands.
"""
def min_mag(self, other: _Decimal, context: Context | None = None) -> Decimal:
"""Similar to the min() method, but the comparison is done using the absolute
values of the operands.
"""
def next_minus(self, context: Context | None = None) -> Decimal:
"""Return the largest number representable in the given context (or in the
current default context if no context is given) that is smaller than the
given operand.
"""
def next_plus(self, context: Context | None = None) -> Decimal:
"""Return the smallest number representable in the given context (or in the
current default context if no context is given) that is larger than the
given operand.
"""
def next_toward(self, other: _Decimal, context: Context | None = None) -> Decimal:
@ -589,6 +631,7 @@ class Decimal:
operand in the direction of the second operand. If both operands are
numerically equal, return a copy of the first operand with the sign set
to be the same as the sign of the second operand.
"""
def number_class(self, context: Context | None = None) -> str:
@ -605,11 +648,14 @@ class Decimal:
* '+Infinity', indicating that the operand is positive infinity.
* 'NaN', indicating that the operand is a quiet NaN (Not a Number).
* 'sNaN', indicating that the operand is a signaling NaN.
"""
def radix(self) -> Decimal:
"""Return Decimal(10), the radix (base) in which the Decimal class does
all its arithmetic. Included for compatibility with the specification.
"""
def rotate(self, other: _Decimal, context: Context | None = None) -> Decimal:
@ -621,12 +667,14 @@ class Decimal:
The coefficient of the first operand is padded on the left with zeros to
length precision if necessary. The sign and exponent of the first operand are
unchanged.
"""
def scaleb(self, other: _Decimal, context: Context | None = None) -> Decimal:
"""Return the first operand with the exponent adjusted the second. Equivalently,
return the first operand multiplied by 10**other. The second operand must be
an integer.
"""
def shift(self, other: _Decimal, context: Context | None = None) -> Decimal:
@ -637,6 +685,7 @@ class Decimal:
positive, then the shift is to the left; otherwise the shift is to the
right. Digits shifted into the coefficient are zeros. The sign and exponent
of the first operand are unchanged.
"""
def __reduce__(self) -> tuple[type[Self], tuple[str]]: ...
@ -654,6 +703,8 @@ class Context:
... traps=[InvalidOperation, DivisionByZero, Overflow],
... flags=[])
>>>
"""
# TODO: Context doesn't allow you to delete *any* attributes from instances of the class at runtime,
@ -696,22 +747,26 @@ class Context:
def Etiny(self) -> int:
"""Return a value equal to Emin - prec + 1, which is the minimum exponent value
for subnormal results. When underflow occurs, the exponent is set to Etiny.
"""
def Etop(self) -> int:
"""Return a value equal to Emax - prec + 1. This is the maximum exponent
if the _clamp field of the context is set to 1 (IEEE clamp mode). Etop()
must not be negative.
"""
def create_decimal(self, num: _DecimalNew = "0", /) -> Decimal:
"""Create a new Decimal instance from num, using self as the context. Unlike the
Decimal constructor, this function observes the context limits.
"""
def create_decimal_from_float(self, f: float, /) -> Decimal:
"""Create a new Decimal instance from float f. Unlike the Decimal.from_float()
class method, this function observes the context limits.
"""
def abs(self, x: _Decimal, /) -> Decimal:
@ -828,6 +883,7 @@ class Context:
def minus(self, x: _Decimal, /) -> Decimal:
"""Minus corresponds to the unary prefix minus operator in Python, but applies
the context to the result.
"""
def multiply(self, x: _Decimal, y: _Decimal, /) -> Decimal:
@ -851,6 +907,7 @@ class Context:
def plus(self, x: _Decimal, /) -> Decimal:
"""Plus corresponds to the unary prefix plus operator in Python, but applies
the context to the result.
"""
def power(self, a: _Decimal, b: _Decimal, modulo: _Decimal | None = None) -> Decimal:
@ -867,6 +924,8 @@ class Context:
* 'b' must be nonnegative
* at least one of 'a' or 'b' must be nonzero
* modulo must be nonzero and less than 10**prec in absolute value
"""
def quantize(self, x: _Decimal, y: _Decimal, /) -> Decimal:
@ -878,11 +937,13 @@ class Context:
def remainder(self, x: _Decimal, y: _Decimal, /) -> Decimal:
"""Return the remainder from integer division. The sign of the result,
if non-zero, is the same as that of the original dividend.
"""
def remainder_near(self, x: _Decimal, y: _Decimal, /) -> Decimal:
"""Return x - y * n, where n is the integer nearest the exact value of x / y
(if the result is 0 then its sign will be the sign of x).
"""
def rotate(self, x: _Decimal, y: _Decimal, /) -> Decimal:

View file

@ -26,6 +26,8 @@ Class HtmlDiff:
For producing HTML side by side comparison with change highlights.
"""
import re
import sys
from collections.abc import Callable, Iterable, Iterator, Sequence
from types import GenericAlias
from typing import Any, AnyStr, Generic, Literal, NamedTuple, TypeVar, overload
@ -55,7 +57,8 @@ class Match(NamedTuple):
size: int
class SequenceMatcher(Generic[_T]):
"""SequenceMatcher is a flexible class for comparing pairs of sequences of
"""
SequenceMatcher is a flexible class for comparing pairs of sequences of
any type, so long as the sequence elements are hashable. The basic
algorithm predates, and is a little fancier than, an algorithm
published in the late 1980's by Ratcliff and Obershelp under the
@ -411,7 +414,8 @@ def get_close_matches(
) -> list[Sequence[_T]]: ...
class Differ:
"""Differ is a class for comparing sequences of lines of text, and
"""
Differ is a class for comparing sequences of lines of text, and
producing human-readable differences or deltas. Differ uses
SequenceMatcher both to compare sequences of lines, and to compare
sequences of characters within similar (near-matching) lines.
@ -496,7 +500,8 @@ class Differ:
"""
def __init__(self, linejunk: Callable[[str], bool] | None = None, charjunk: Callable[[str], bool] | None = None) -> None:
"""Construct a text differencer, with optional filters.
"""
Construct a text differencer, with optional filters.
The two optional keyword parameters are for filter functions:
@ -515,7 +520,8 @@ class Differ:
"""
def compare(self, a: Sequence[str], b: Sequence[str]) -> Iterator[str]:
"""Compare two sequences of lines; generate the resulting delta.
"""
Compare two sequences of lines; generate the resulting delta.
Each sequence must contain individual single-line strings ending with
newlines. Such sequences can be obtained from the `readlines()` method
@ -539,8 +545,25 @@ class Differ:
+ emu
"""
def IS_LINE_JUNK(line: str, pat: Any = ...) -> bool: # pat is undocumented
"""Return True for ignorable line: if `line` is blank or contains a single '#'.
if sys.version_info >= (3, 14):
def IS_LINE_JUNK(line: str, pat: Callable[[str], re.Match[str] | None] | None = None) -> bool:
"""
Return True for ignorable line: if `line` is blank or contains a single '#'.
Examples:
>>> IS_LINE_JUNK('\\n')
True
>>> IS_LINE_JUNK(' # \\n')
True
>>> IS_LINE_JUNK('hello\\n')
False
"""
else:
def IS_LINE_JUNK(line: str, pat: Callable[[str], re.Match[str] | None] = ...) -> bool:
"""
Return True for ignorable line: iff `line` is blank or contains a single '#'.
Examples:
@ -553,7 +576,8 @@ def IS_LINE_JUNK(line: str, pat: Any = ...) -> bool: # pat is undocumented
"""
def IS_CHARACTER_JUNK(ch: str, ws: str = " \t") -> bool: # ws is undocumented
"""Return True for ignorable character: iff `ch` is a space or tab.
"""
Return True for ignorable character: iff `ch` is a space or tab.
Examples:
@ -577,7 +601,8 @@ def unified_diff(
n: int = 3,
lineterm: str = "\n",
) -> Iterator[str]:
"""Compare two sequences of lines; generate the delta as a unified diff.
"""
Compare two sequences of lines; generate the delta as a unified diff.
Unified diffs are a compact way of showing line changes and a few
lines of context. The number of context lines is set by 'n' which
@ -625,7 +650,8 @@ def context_diff(
n: int = 3,
lineterm: str = "\n",
) -> Iterator[str]:
"""Compare two sequences of lines; generate the delta as a context diff.
"""
Compare two sequences of lines; generate the delta as a context diff.
Context diffs are a compact way of showing line changes and a few
lines of context. The number of context lines is set by 'n' which
@ -672,7 +698,8 @@ def ndiff(
linejunk: Callable[[str], bool] | None = None,
charjunk: Callable[[str], bool] | None = ...,
) -> Iterator[str]:
"""Compare `a` and `b` (lists of strings); return a `Differ`-style delta.
"""
Compare `a` and `b` (lists of strings); return a `Differ`-style delta.
Optional keyword parameters `linejunk` and `charjunk` are for filter
functions, or can be None:
@ -794,7 +821,8 @@ class HtmlDiff:
"""
def restore(delta: Iterable[str], which: int) -> Iterator[str]:
"""Generate one of the two sequences that generated a delta.
"""
Generate one of the two sequences that generated a delta.
Given a `delta` produced by `Differ.compare()` or `ndiff()`, extract
lines originating from file 1 or 2 (parameter `which`), stripping off line
@ -826,7 +854,8 @@ def diff_bytes(
n: int = 3,
lineterm: bytes | bytearray = b"\n",
) -> Iterator[bytes]:
"""Compare `a` and `b`, two sequences of lines represented as bytes rather
"""
Compare `a` and `b`, two sequences of lines represented as bytes rather
than str. This is a wrapper for `dfunc`, which is typically either
unified_diff() or context_diff(). Inputs are losslessly converted to
strings so that `dfunc` only has to worry about strings, and encoded

View file

@ -255,6 +255,7 @@ def findlabels(code: _HaveCodeType) -> list[int]:
"""Detect all offsets in a byte code which are jump targets.
Return the list of offsets.
"""
def findlinestarts(code: _HaveCodeType) -> Iterator[tuple[int, int]]:

View file

@ -52,6 +52,7 @@ class register(PyPIRCCommand):
1. use existing login,
2. register as a new user, or
3. set the password to a random string and email the user.
"""
def build_post_data(self, action): ...

View file

@ -101,7 +101,8 @@ class FileList:
) -> bool: ...
def findall(dir: str = ".") -> list[str]:
"""Find all files under 'dir' and return the list of full filenames.
"""
Find all files under 'dir' and return the list of full filenames.
Unless dir is '.', return full filenames with dir prepended.
"""

View file

@ -29,6 +29,7 @@ def get_host_platform() -> str:
win32 (all others - specifically, sys.platform is returned)
For other non-POSIX platforms, currently just returns 'sys.platform'.
"""
def get_platform() -> str: ...

View file

@ -123,7 +123,8 @@ BLANKLINE_MARKER: str
ELLIPSIS_MARKER: str
class Example:
"""A single doctest example, consisting of source code and expected
"""
A single doctest example, consisting of source code and expected
output. `Example` defines the following attributes:
- source: A single Python statement, always ending with a newline.
@ -176,7 +177,8 @@ class Example:
def __eq__(self, other: object) -> bool: ...
class DocTest:
"""A collection of doctest examples that should be run in a single
"""
A collection of doctest examples that should be run in a single
namespace. Each `DocTest` defines the following attributes:
- examples: the list of examples.
@ -214,7 +216,8 @@ class DocTest:
lineno: int | None,
docstring: str | None,
) -> None:
"""Create a new DocTest containing the given examples. The
"""
Create a new DocTest containing the given examples. The
DocTest's globals are initialized with a copy of `globs`.
"""
@ -223,10 +226,13 @@ class DocTest:
def __eq__(self, other: object) -> bool: ...
class DocTestParser:
"""A class used to parse strings containing doctest examples."""
"""
A class used to parse strings containing doctest examples.
"""
def parse(self, string: str, name: str = "<string>") -> list[str | Example]:
"""Divide the given string into examples and intervening text,
"""
Divide the given string into examples and intervening text,
and return them as a list of alternating Examples and strings.
Line numbers for the Examples are 0-based. The optional
argument `name` is a name identifying this string, and is only
@ -234,7 +240,8 @@ class DocTestParser:
"""
def get_doctest(self, string: str, globs: dict[str, Any], name: str, filename: str | None, lineno: int | None) -> DocTest:
"""Extract all doctest examples from the given string, and
"""
Extract all doctest examples from the given string, and
collect them into a `DocTest` object.
`globs`, `name`, `filename`, and `lineno` are attributes for
@ -243,7 +250,8 @@ class DocTestParser:
"""
def get_examples(self, string: str, name: str = "<string>") -> list[Example]:
"""Extract all doctest examples from the given string, and return
"""
Extract all doctest examples from the given string, and return
them as a list of `Example` objects. Line numbers are
0-based, because it's most common in doctests that nothing
interesting appears on the same line as opening triple-quote,
@ -254,7 +262,8 @@ class DocTestParser:
"""
class DocTestFinder:
"""A class used to extract the DocTests that are relevant to a given
"""
A class used to extract the DocTests that are relevant to a given
object, from its docstring and the docstrings of its contained
objects. Doctests can currently be extracted from the following
object types: modules, functions, classes, methods, staticmethods,
@ -264,7 +273,8 @@ class DocTestFinder:
def __init__(
self, verbose: bool = False, parser: DocTestParser = ..., recurse: bool = True, exclude_empty: bool = True
) -> None:
"""Create a new doctest finder.
"""
Create a new doctest finder.
The optional argument `parser` specifies a class or
function that should be used to create new DocTest objects (or
@ -287,7 +297,8 @@ class DocTestFinder:
globs: dict[str, Any] | None = None,
extraglobs: dict[str, Any] | None = None,
) -> list[DocTest]:
"""Return a list of the DocTests that are defined by the given
"""
Return a list of the DocTests that are defined by the given
object's docstring, or by any of its contained objects'
docstrings.
@ -318,12 +329,14 @@ class DocTestFinder:
defaults to the module's `__dict__`, if specified, or {}
otherwise. If `extraglobs` is not specified, then it defaults
to {}.
"""
_Out: TypeAlias = Callable[[str], object]
class DocTestRunner:
"""A class used to run DocTest test cases, and accumulate statistics.
"""
A class used to run DocTest test cases, and accumulate statistics.
The `run` method is used to process a single DocTest case. It
returns a TestResults instance.
@ -393,7 +406,8 @@ class DocTestRunner:
skips: int
test: DocTest
def __init__(self, checker: OutputChecker | None = None, verbose: bool | None = None, optionflags: int = 0) -> None:
"""Create a new test runner.
"""
Create a new test runner.
Optional keyword arg `checker` is the `OutputChecker` that
should be used to compare the expected outputs and actual
@ -410,25 +424,32 @@ class DocTestRunner:
"""
def report_start(self, out: _Out, test: DocTest, example: Example) -> None:
"""Report that the test runner is about to process the given
"""
Report that the test runner is about to process the given
example. (Only displays a message if verbose=True)
"""
def report_success(self, out: _Out, test: DocTest, example: Example, got: str) -> None:
"""Report that the given example ran successfully. (Only
"""
Report that the given example ran successfully. (Only
displays a message if verbose=True)
"""
def report_failure(self, out: _Out, test: DocTest, example: Example, got: str) -> None:
"""Report that the given example failed."""
"""
Report that the given example failed.
"""
def report_unexpected_exception(self, out: _Out, test: DocTest, example: Example, exc_info: ExcInfo) -> None:
"""Report that the given example raised an unexpected exception."""
"""
Report that the given example raised an unexpected exception.
"""
def run(
self, test: DocTest, compileflags: int | None = None, out: _Out | None = None, clear_globs: bool = True
) -> TestResults:
"""Run the examples in `test`, and display the results using the
"""
Run the examples in `test`, and display the results using the
writer function `out`.
The examples are run in the namespace `test.globs`. If
@ -448,7 +469,8 @@ class DocTestRunner:
"""
def summarize(self, verbose: bool | None = None) -> TestResults:
"""Print a summary of all the test cases that have been run by
"""
Print a summary of all the test cases that have been run by
this DocTestRunner, and return a TestResults instance.
The optional `verbose` argument controls how detailed the
@ -459,7 +481,8 @@ class DocTestRunner:
def merge(self, other: DocTestRunner) -> None: ...
class OutputChecker:
"""A class used to check whether the actual output from a doctest
"""
A class used to check whether the actual output from a doctest
example matches the expected output. `OutputChecker` defines two
methods: `check_output`, which compares a given pair of outputs,
and returns true if they match; and `output_difference`, which
@ -467,7 +490,8 @@ class OutputChecker:
"""
def check_output(self, want: str, got: str, optionflags: int) -> bool:
"""Return True iff the actual output from an example (`got`)
"""
Return True iff the actual output from an example (`got`)
matches the expected output (`want`). These strings are
always considered to match if they are identical; but
depending on what option flags the test runner is using,
@ -477,7 +501,8 @@ class OutputChecker:
"""
def output_difference(self, example: Example, got: str, optionflags: int) -> str:
"""Return a string describing the differences between the
"""
Return a string describing the differences between the
expected output for a given example (`example`) and the actual
output (`got`). `optionflags` is the set of option flags used
to compare `want` and `got`.
@ -605,6 +630,7 @@ class DebugRunner(DocTestRunner):
>>> test.globs
{}
"""
master: DocTestRunner | None
@ -628,8 +654,8 @@ def testmod(
from module m (or the current module if m is not supplied), starting
with m.__doc__.
Also test examples reachable from dict m.__test__ if it exists and is
not None. m.__test__ maps names to functions, classes and strings;
Also test examples reachable from dict m.__test__ if it exists.
m.__test__ maps names to functions, classes and strings;
function and class docstrings are tested even if the name is private;
strings are tested directly, as if they were docstrings.
@ -698,7 +724,8 @@ def testfile(
parser: DocTestParser = ...,
encoding: str | None = None,
) -> TestResults:
"""Test examples in the given file. Return (#failures, #tests).
"""
Test examples in the given file. Return (#failures, #tests).
Optional keyword arg "module_relative" specifies how filenames
should be interpreted:
@ -782,7 +809,8 @@ def run_docstring_examples(
compileflags: int | None = None,
optionflags: int = 0,
) -> None:
"""Test examples in the given object's docstring (`f`), using `globs`
"""
Test examples in the given object's docstring (`f`), using `globs`
as globals. Optional argument `name` is used in failure messages.
If the optional argument `verbose` is true, then generate output
even if there are no failures.
@ -852,7 +880,8 @@ def DocTestSuite(
test_finder: DocTestFinder | None = None,
**options: Any,
) -> _DocTestSuite:
"""Convert doctest tests for a module to a unittest test suite.
"""
Convert doctest tests for a module to a unittest test suite.
This converts each documentation string in a module that
contains doctest tests to a unittest test case. If any of the

View file

@ -427,6 +427,7 @@ def get_fws(value: str) -> tuple[WhiteSpaceTerminal, str]:
This isn't the RFC definition. We're using fws to represent tokens where
folding can be done, but when we are parsing the *un*folding has already
been done so we don't need to watch out for CRLF.
"""
def get_encoded_word(value: str, terminal_type: str = "vtext") -> tuple[EncodedWord, str]:
@ -449,6 +450,7 @@ def get_unstructured(value: str) -> UnstructuredTokenList:
Because an 'unstructured' value must by definition constitute the entire
value, this 'get' routine does not return a remaining value, only the
parsed TokenList.
"""
def get_qp_ctext(value: str) -> tuple[WhiteSpaceTerminal, str]:
@ -461,6 +463,7 @@ def get_qp_ctext(value: str) -> tuple[WhiteSpaceTerminal, str]:
quoted pairs are converted to their unquoted values, what is returned is
a 'ptext' token. In this case it is a WhiteSpaceTerminal, so it's value
is ' '.
"""
def get_qcontent(value: str) -> tuple[ValueTerminal, str]:
@ -471,6 +474,7 @@ def get_qcontent(value: str) -> tuple[ValueTerminal, str]:
added to the token's defects list. Any quoted pairs are converted to their
unquoted values, so what is returned is a 'ptext' token. In this case it
is a ValueTerminal.
"""
def get_atext(value: str) -> tuple[ValueTerminal, str]:
@ -536,6 +540,7 @@ def get_word(value: str) -> tuple[Any, str]:
This means the 'word' level of the formal grammar is not represented in the
parse tree; this is because having that extra layer when manipulating the
parse tree is more confusing than it is helpful.
"""
def get_phrase(value: str) -> tuple[Phrase, str]:
@ -548,6 +553,7 @@ def get_phrase(value: str) -> tuple[Phrase, str]:
list. We also accept a phrase that starts with CFWS followed by a dot;
this is registered as an InvalidHeaderDefect, since it is not supported by
even the obsolete grammar.
"""
def get_local_part(value: str) -> tuple[LocalPart, str]:
@ -566,6 +572,7 @@ def get_dtext(value: str) -> tuple[ValueTerminal, str]:
unquoted values, so what is returned is a ptext token, in this case a
ValueTerminal. If there were quoted-printables, an ObsoleteHeaderDefect is
added to the returned token's defect list.
"""
def get_domain_literal(value: str) -> tuple[DomainLiteral, str]:
@ -574,6 +581,7 @@ def get_domain_literal(value: str) -> tuple[DomainLiteral, str]:
def get_domain(value: str) -> tuple[Domain, str]:
"""domain = dot-atom / domain-literal / obs-domain
obs-domain = atom *("." atom))
"""
def get_addr_spec(value: str) -> tuple[AddrSpec, str]:
@ -590,6 +598,7 @@ def get_obs_route(value: str) -> tuple[ObsRoute, str]:
def get_angle_addr(value: str) -> tuple[AngleAddr, str]:
"""angle-addr = [CFWS] "<" addr-spec ">" [CFWS] / obs-angle-addr
obs-angle-addr = [CFWS] "<" obs-route addr-spec ">" [CFWS]
"""
def get_display_name(value: str) -> tuple[DisplayName, str]:
@ -598,6 +607,7 @@ def get_display_name(value: str) -> tuple[DisplayName, str]:
Because this is simply a name-rule, we don't return a display-name
token containing a phrase, but rather a display-name token with
the content of the phrase.
"""
def get_name_addr(value: str) -> tuple[NameAddr, str]:
@ -611,6 +621,7 @@ def get_invalid_mailbox(value: str, endchars: str) -> tuple[InvalidMailbox, str]
This is outside the formal grammar. The InvalidMailbox TokenList that is
returned acts like a Mailbox, but the data attributes are None.
"""
def get_mailbox_list(value: str) -> tuple[MailboxList, str]:
@ -623,11 +634,13 @@ def get_mailbox_list(value: str) -> tuple[MailboxList, str]:
invalid mailboxes into InvalidMailbox tokens and continue parsing any
remaining valid mailboxes. We also allow all mailbox entries to be null,
and this condition is handled appropriately at a higher level.
"""
def get_group_list(value: str) -> tuple[GroupList, str]:
"""group-list = mailbox-list / CFWS / obs-group-list
obs-group-list = 1*([CFWS] ",") [CFWS]
"""
def get_group(value: str) -> tuple[Group, str]:
@ -641,6 +654,7 @@ def get_address(value: str) -> tuple[Address, str]:
a 'mailboxes' attribute which treats a single address as a list of length
one. When you need to differentiate between to two cases, extract the single
element, which is either a mailbox or a group token.
"""
def get_address_list(value: str) -> tuple[AddressList, str]:
@ -651,6 +665,7 @@ def get_address_list(value: str) -> tuple[AddressList, str]:
of the input, assuming the input to be entirely composed of an
address-list. This is always true in email parsing, and allows us
to skip invalid addresses to parse additional valid ones.
"""
def get_no_fold_literal(value: str) -> tuple[NoFoldLiteral, str]:
@ -674,6 +689,7 @@ def get_invalid_parameter(value: str) -> tuple[InvalidParameter, str]:
This is outside the formal grammar. The InvalidParameter TokenList that is
returned acts like a Parameter, but the data attributes are None.
"""
def get_ttext(value: str) -> tuple[ValueTerminal, str]:
@ -683,6 +699,7 @@ def get_ttext(value: str) -> tuple[ValueTerminal, str]:
defects list if we find non-ttext characters. We also register defects for
*any* non-printables even though the RFC doesn't exclude all of them,
because we follow the spirit of RFC 5322.
"""
def get_token(value: str) -> tuple[Token, str]:
@ -692,6 +709,7 @@ def get_token(value: str) -> tuple[Token, str]:
tspecials. We also exclude tabs even though the RFC doesn't.
The RFC implies the CFWS but is not explicit about it in the BNF.
"""
def get_attrtext(value: str) -> tuple[ValueTerminal, str]:
@ -701,6 +719,7 @@ def get_attrtext(value: str) -> tuple[ValueTerminal, str]:
token's defects list if we find non-attrtext characters. We also register
defects for *any* non-printables even though the RFC doesn't exclude all of
them, because we follow the spirit of RFC 5322.
"""
def get_attribute(value: str) -> tuple[Attribute, str]:
@ -710,6 +729,7 @@ def get_attribute(value: str) -> tuple[Attribute, str]:
value terminal for the actual run of characters. The RFC equivalent of
attrtext is the token characters, with the subtraction of '*', "'", and '%'.
We include tab in the excluded set just as we do for token.
"""
def get_extended_attrtext(value: str) -> tuple[ValueTerminal, str]:
@ -718,6 +738,7 @@ def get_extended_attrtext(value: str) -> tuple[ValueTerminal, str]:
This is a special parsing routine so that we get a value that
includes % escapes as a single string (which we decode as a single
string later).
"""
def get_extended_attribute(value: str) -> tuple[Attribute, str]:
@ -725,6 +746,7 @@ def get_extended_attribute(value: str) -> tuple[Attribute, str]:
This is like the non-extended version except we allow % characters, so that
we can pick up an encoded value as a single string.
"""
def get_section(value: str) -> tuple[Section, str]:
@ -734,6 +756,7 @@ def get_section(value: str) -> tuple[Section, str]:
check for that and add a defect. We also assume no CFWS is allowed between
the '*' and the digits, though the RFC is not crystal clear on that.
The caller should already have dealt with leading CFWS.
"""
def get_value(value: str) -> tuple[Value, str]:
@ -759,6 +782,7 @@ def parse_mime_parameters(value: str) -> MimeParameters:
This is 'parse' routine because it consumes the remaining value, but it
would never be called to parse a full header. Instead it is called to
parse everything after the non-parameter value of a specific MIME header.
"""
def parse_content_type_header(value: str) -> ContentType:

View file

@ -41,6 +41,7 @@ class _PolicyBase(Generic[_MessageT_co]):
The repr of an instance can be used to reconstruct the object
if and only if the repr of the values can be used to reconstruct
those values.
"""
max_line_length: int | None
@ -67,6 +68,7 @@ class _PolicyBase(Generic[_MessageT_co]):
"""Create new Policy, possibly overriding some defaults.
See class docstring for a list of overridable attributes.
"""
def clone(
@ -85,12 +87,14 @@ class _PolicyBase(Generic[_MessageT_co]):
The new instance has the same attribute values as the current object,
except for the changes passed in as keyword arguments.
"""
def __add__(self, other: Policy) -> Self:
"""Non-default values from right operand override those from left.
The object returned is a new instance of the subclass.
"""
class Policy(_PolicyBase[_MessageT_co], metaclass=ABCMeta):
@ -164,6 +168,7 @@ class Policy(_PolicyBase[_MessageT_co], metaclass=ABCMeta):
This method is intended to be called by parsers that discover defects.
The email package parsers always call it with Defect instances.
"""
def register_defect(self, obj: Message[Any, Any], defect: MessageDefect) -> None:
@ -175,6 +180,7 @@ class Policy(_PolicyBase[_MessageT_co], metaclass=ABCMeta):
the defects attribute of obj. The objects used by the email package by
default that get passed to this method will always have a defects
attribute with an append method.
"""
def header_max_count(self, name: str) -> int | None:
@ -217,6 +223,7 @@ class Policy(_PolicyBase[_MessageT_co], metaclass=ABCMeta):
header. The value passed in by the email package may contain
surrogateescaped binary data if the lines were parsed by a BytesParser.
The returned value should not contain any surrogateescaped data.
"""
@abstractmethod
@ -227,6 +234,7 @@ class Policy(_PolicyBase[_MessageT_co], metaclass=ABCMeta):
package may contain surrogateescaped binary data if the lines were
parsed by a BytesParser. The returned value should not contain any
surrogateescaped data.
"""
@abstractmethod
@ -235,6 +243,7 @@ class Policy(_PolicyBase[_MessageT_co], metaclass=ABCMeta):
data containing linesep characters that implement the folding of the
header according to the policy controls. The value passed in by the
email package may contain surrogateescaped binary data.
"""
class Compat32(Policy[_MessageT_co]):
@ -305,6 +314,7 @@ class Compat32(Policy[_MessageT_co]):
The value is determined by stripping leading whitespace off the
remainder of the first line joined with all subsequent lines, and
stripping any trailing carriage return or linefeed characters.
"""
def header_store_parse(self, name: str, value: str) -> tuple[str, str]:
@ -336,6 +346,7 @@ class Compat32(Policy[_MessageT_co]):
existing line breaks in the value, and wraps each resulting line to the
max_line_length. Non-ASCII binary data are CTE encoded using the
unknown-8bit charset.
"""
def fold_binary(self, name: str, value: str) -> bytes:
@ -349,6 +360,7 @@ class Compat32(Policy[_MessageT_co]):
max_line_length. If cte_type is 7bit, non-ascii binary data is CTE
encoded using the unknown-8bit charset. Otherwise the original source
header is used, with its existing line breaks and/or binary data.
"""
compat32: Compat32[Message[str, str]]

View file

@ -33,6 +33,7 @@ class FeedParser(Generic[_MessageT]):
The policy keyword specifies a policy object that controls a number of
aspects of the parser's operation. The default policy maintains
backward compatibility.
"""
@overload
@ -53,6 +54,7 @@ class BytesFeedParser(FeedParser[_MessageT]):
The policy keyword specifies a policy object that controls a number of
aspects of the parser's operation. The default policy maintains
backward compatibility.
"""
@overload

View file

@ -49,6 +49,7 @@ class Generator(Generic[_MessageT]):
aspects of the generator's operation. If no policy is specified,
the policy associated with the Message object passed to the
flatten method is used.
"""
@overload
@ -76,6 +77,7 @@ class Generator(Generic[_MessageT]):
the output. The default value is determined by the policy specified
when the Generator instance was created or, if none was specified,
from the policy associated with the msg.
"""
def clone(self, fp: SupportsWrite[str]) -> Self:
@ -123,6 +125,7 @@ class BytesGenerator(Generator[_MessageT]):
aspects of the generator's operation. If no policy is specified,
the policy associated with the Message object passed to the
flatten method is used.
"""
@overload

View file

@ -52,6 +52,7 @@ class BaseHeader(str):
The subclass should also make sure that a 'max_count' attribute is defined
that is either None or 1. XXX: need to better define this API.
"""
# max_count is actually more of an abstract ClassVar (not defined on the base class, but expected to be defined in subclasses)
@ -76,6 +77,7 @@ class BaseHeader(str):
The returned value is an ASCII-only string possibly containing linesep
characters, and ending with a linesep character. The string includes
the header name and the ': ' separator.
"""
class UnstructuredHeader:
@ -98,6 +100,7 @@ class UnstructuredHeader:
Because an 'unstructured' value must by definition constitute the entire
value, this 'get' routine does not return a remaining value, only the
parsed TokenList.
"""
@classmethod
@ -138,6 +141,7 @@ class DateHeader:
Because an 'unstructured' value must by definition constitute the entire
value, this 'get' routine does not return a remaining value, only the
parsed TokenList.
"""
@classmethod
@ -268,6 +272,7 @@ class HeaderRegistry:
use_default_map controls whether or not the default mapping of names to
specialized classes is copied in to the registry when the factory is
created. The default is True.
"""
def map_to_type(self, name: str, cls: type[BaseHeader]) -> None:
@ -282,6 +287,7 @@ class HeaderRegistry:
base_class with a specialized class from the registry or the
default_class, and passing the name and value to the constructed
class's constructor.
"""
class Address:
@ -313,6 +319,7 @@ class Address:
attributes, all of which are read-only. The addr_spec and the string
value of the object are both quoted according to RFC5322 rules, but
without any Content Transfer Encoding.
"""
__hash__: ClassVar[None] # type: ignore[assignment]
def __eq__(self, other: object) -> bool: ...
@ -335,6 +342,7 @@ class Group:
string representation of a Group whose display_name is None is the same
as the Address object, if there is one and only one Address object in
the addresses list.
"""
__hash__: ClassVar[None] # type: ignore[assignment]
def __eq__(self, other: object) -> bool: ...

View file

@ -332,6 +332,7 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]):
rawparam = msg.get_param('foo')
param = email.utils.collapse_rfc2231_value(rawparam)
"""
@overload

View file

@ -32,6 +32,7 @@ class Parser(Generic[_MessageT]):
The policy keyword specifies a policy object that controls a number of
aspects of the parser's operation. The default policy maintains
backward compatibility.
"""
@overload

View file

@ -119,6 +119,7 @@ class EmailPolicy(Policy[_MessageT]):
it as additional arguments. The default
content_manager is
:data:`~email.contentmanager.raw_data_manager`.
"""
utf8: bool
@ -170,6 +171,7 @@ class EmailPolicy(Policy[_MessageT]):
remainder of the first line joined with all subsequent lines, and
stripping any trailing carriage return or linefeed characters. (This
is the same as Compat32).
"""
def header_store_parse(self, name: str, value: Any) -> tuple[str, Any]:
@ -181,6 +183,7 @@ class EmailPolicy(Policy[_MessageT]):
method, and the resulting custom header object is returned as the
value. In this case a ValueError is raised if the input value contains
CR or LF characters.
"""
def header_fetch_parse(self, name: str, value: str) -> Any:
@ -195,6 +198,7 @@ class EmailPolicy(Policy[_MessageT]):
are passed to the header_factory method, and the resulting custom
header object is returned. Any surrogateescaped bytes get turned
into the unicode unknown-character glyph.
"""
def fold(self, name: str, value: str) -> Any:
@ -220,6 +224,7 @@ class EmailPolicy(Policy[_MessageT]):
binary data. In that case the value is refolded regardless of the
refold_source setting, which causes the binary data to be CTE encoded
using the unknown-8bit charset.
"""
def fold_binary(self, name: str, value: str) -> bytes:
@ -238,6 +243,7 @@ class EmailPolicy(Policy[_MessageT]):
If utf8 is true, headers are encoded to utf8, otherwise to ascii with
non-ASCII unicode rendered as encoded words.
"""
def clone(
@ -260,6 +266,7 @@ class EmailPolicy(Policy[_MessageT]):
The new instance has the same attribute values as the current object,
except for the changes passed in as keyword arguments.
"""
default: EmailPolicy[EmailMessage]

View file

@ -94,6 +94,7 @@ def body_encode(body: str, maxlinelen: int = 76, eol: str = "\n") -> str:
The minimum maxlinelen is 4 to have room for a quoted character ("=XX")
followed by a soft line break. Smaller values will generate a
ValueError.
"""
def decode(encoded: str, eol: str = "\n") -> str:

View file

@ -42,7 +42,8 @@ def unquote(str: str) -> str:
# `strict` parameter added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5
def parseaddr(addr: str | list[str], *, strict: bool = True) -> tuple[str, str]:
"""Parse addr into its constituent realname and email address parts.
"""
Parse addr into its constituent realname and email address parts.
Return a tuple of realname and email address, unless the parse fails, in
which case return a 2-tuple of ('', '').
@ -135,6 +136,7 @@ if sys.version_info >= (3, 14):
argument should be a datetime instance, and it is converted to the
local time zone according to the system time zone database. If *dt* is
naive (that is, dt.tzinfo is None), it is assumed to be in local time.
"""
elif sys.version_info >= (3, 12):
@ -147,6 +149,7 @@ elif sys.version_info >= (3, 12):
local time zone according to the system time zone database. If *dt* is
naive (that is, dt.tzinfo is None), it is assumed to be in local time.
The isdst parameter is ignored.
"""
@overload
@ -166,6 +169,7 @@ else:
is or is not (respectively) in effect for the specified time. A
negative value for *isdst* causes the localtime() function to attempt
to divine whether summer time is in effect for the specified time.
"""
def make_msgid(idstring: str | None = None, domain: str | None = None) -> str:

View file

@ -41,6 +41,7 @@ def normalize_encoding(encoding: str | bytes) -> str:
becomes '_'. Leading and trailing underscores are removed.
Note that encoding names should be ASCII only.
"""
def search_function(encoding: str) -> CodecInfo | None: ...

View file

@ -1,7 +1,9 @@
__all__ = ["version", "bootstrap"]
def version() -> str:
"""Returns a string specifying the bundled version of pip."""
"""
Returns a string specifying the bundled version of pip.
"""
def bootstrap(
*,
@ -12,7 +14,8 @@ def bootstrap(
default_pip: bool = False,
verbosity: int = 0,
) -> None:
"""Bootstrap pip into the current Python installation (or the given root
"""
Bootstrap pip into the current Python installation (or the given root
directory).
Note that calling this function will alter both sys.path and os.environ.

View file

@ -57,19 +57,24 @@ _Signature: TypeAlias = Any # TODO: Unable to import Signature from inspect mod
if sys.version_info >= (3, 11):
class nonmember(Generic[_EnumMemberT]):
"""Protects item from becoming an Enum member during class creation."""
"""
Protects item from becoming an Enum member during class creation.
"""
value: _EnumMemberT
def __init__(self, value: _EnumMemberT) -> None: ...
class member(Generic[_EnumMemberT]):
"""Forces item to become an Enum member during class creation."""
"""
Forces item to become an Enum member during class creation.
"""
value: _EnumMemberT
def __init__(self, value: _EnumMemberT) -> None: ...
class _EnumDict(dict[str, Any]):
"""Track enum member order and ensure member names are not reused.
"""
Track enum member order and ensure member names are not reused.
EnumType will use the names found in self._member_names as the
enumeration member names.
@ -81,7 +86,8 @@ class _EnumDict(dict[str, Any]):
def __init__(self) -> None: ...
def __setitem__(self, key: str, value: Any) -> None:
"""Changes anything not dundered or not a descriptor.
"""
Changes anything not dundered or not a descriptor.
If an enum member name is used twice, an error is raised; duplicate
values are not checked for.
@ -107,7 +113,9 @@ if sys.version_info >= (3, 13):
# Structurally: Iterable[T], Reversible[T], Container[T] where T is the enum itself
class EnumMeta(type):
"""Metaclass for Enum"""
"""
Metaclass for Enum
"""
if sys.version_info >= (3, 11):
def __new__(
@ -128,10 +136,14 @@ class EnumMeta(type):
@classmethod
def __prepare__(metacls, cls: str, bases: tuple[type, ...], **kwds: Any) -> _EnumDict: ... # type: ignore[override]
def __iter__(self: type[_EnumMemberT]) -> Iterator[_EnumMemberT]:
"""Return members in definition order."""
"""
Return members in definition order.
"""
def __reversed__(self: type[_EnumMemberT]) -> Iterator[_EnumMemberT]:
"""Return members in reverse definition order."""
"""
Return members in reverse definition order.
"""
if sys.version_info >= (3, 12):
def __contains__(self: type[Any], value: object) -> bool:
"""Return True if `value` is in `cls`.
@ -143,7 +155,8 @@ class EnumMeta(type):
"""
elif sys.version_info >= (3, 11):
def __contains__(self: type[Any], member: object) -> bool:
"""Return True if member is a member of this enum
"""
Return True if member is a member of this enum
raises TypeError if member is not an enum member
note: in 3.12 TypeError will no longer be raised, and True will also be
@ -155,28 +168,36 @@ class EnumMeta(type):
def __contains__(self: type[Any], member: object) -> bool: ...
def __getitem__(self: type[_EnumMemberT], name: str) -> _EnumMemberT:
"""Return the member matching `name`."""
"""
Return the member matching `name`.
"""
@_builtins_property
def __members__(self: type[_EnumMemberT]) -> types.MappingProxyType[str, _EnumMemberT]:
"""Returns a mapping of member name->value.
"""
Returns a mapping of member name->value.
This mapping lists all enum members, including aliases. Note that this
is a read-only view of the internal mapping.
"""
def __len__(self) -> int:
"""Return the number of members (no aliases)"""
"""
Return the number of members (no aliases)
"""
def __bool__(self) -> Literal[True]:
"""classes/types should always be True."""
"""
classes/types should always be True.
"""
def __dir__(self) -> list[str]: ...
# Overload 1: Value lookup on an already existing enum class (simple case)
@overload
def __call__(cls: type[_EnumMemberT], value: Any, names: None = None) -> _EnumMemberT:
"""Either returns an existing member, or creates a new enum class.
"""
Either returns an existing member, or creates a new enum class.
This method is used both when an enum class is given a value to match
to an enumeration member (i.e. Color(3)) and for the functional API
@ -215,7 +236,8 @@ class EnumMeta(type):
start: int = 1,
boundary: FlagBoundary | None = None,
) -> type[Enum]:
"""Either returns an existing member, or creates a new enum class.
"""
Either returns an existing member, or creates a new enum class.
This method is used both when an enum class is given a value to match
to an enumeration member (i.e. Color(3)) and for the functional API
@ -252,7 +274,8 @@ class EnumMeta(type):
type: type | None = None,
start: int = 1,
) -> type[Enum]:
"""Either returns an existing member, or creates a new enum class.
"""
Either returns an existing member, or creates a new enum class.
This method is used both when an enum class is given a value to match
to an enumeration member (i.e. Color(3)) and for the functional API
@ -285,7 +308,8 @@ class EnumMeta(type):
if sys.version_info >= (3, 12):
@overload
def __call__(cls: type[_EnumMemberT], value: Any, *values: Any) -> _EnumMemberT:
"""Either returns an existing member, or creates a new enum class.
"""
Either returns an existing member, or creates a new enum class.
This method is used both when an enum class is given a value to match
to an enumeration member (i.e. Color(3)) and for the functional API
@ -323,7 +347,8 @@ if sys.version_info >= (3, 11):
EnumType = EnumMeta
class property(types.DynamicClassAttribute):
"""This is a descriptor, used to define attributes that act differently
"""
This is a descriptor, used to define attributes that act differently
when accessed through an enum member and through an enum class.
Instance access is the same as property(), but access to an attribute
through the enum class will instead look in the class' _member_map_ for
@ -340,7 +365,8 @@ else:
_magic_enum_attr = types.DynamicClassAttribute
class Enum(metaclass=EnumMeta):
"""Create a collection of name/value pairs.
"""
Create a collection of name/value pairs.
Example enumeration:
@ -394,7 +420,8 @@ class Enum(metaclass=EnumMeta):
def _missing_(cls, value: object) -> Any: ...
@staticmethod
def _generate_next_value_(name: str, start: int, count: int, last_values: list[Any]) -> Any:
"""Generate the next value when not given.
"""
Generate the next value when not given.
name: the name of the member
start: the initial start value or None
@ -408,11 +435,15 @@ class Enum(metaclass=EnumMeta):
# and in practice using `object` here has the same effect as using `Any`.
def __new__(cls, value: object) -> Self: ...
def __dir__(self) -> list[str]:
"""Returns public methods and other interesting attributes."""
"""
Returns public methods and other interesting attributes.
"""
def __hash__(self) -> int: ...
def __format__(self, format_spec: str) -> str:
"""Returns format using actual value type unless __str__ has been overridden."""
"""
Returns format using actual value type unless __str__ has been overridden.
"""
def __reduce_ex__(self, proto: Unused) -> tuple[Any, ...]: ...
if sys.version_info >= (3, 11):
@ -429,7 +460,9 @@ class Enum(metaclass=EnumMeta):
if sys.version_info >= (3, 11):
class ReprEnum(Enum):
"""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):
_IntEnumBase = ReprEnum
@ -437,7 +470,9 @@ else:
_IntEnumBase = Enum
class IntEnum(int, _IntEnumBase):
"""Enum where members are also (and must be) ints"""
"""
Enum where members are also (and must be) ints
"""
_value_: int
@_magic_enum_attr
@ -447,12 +482,16 @@ class IntEnum(int, _IntEnumBase):
def __new__(cls, value: int) -> Self: ...
def unique(enumeration: _EnumerationT) -> _EnumerationT:
"""Class decorator for enumerations ensuring unique member values."""
"""
Class decorator for enumerations ensuring unique member values.
"""
_auto_null: Any
class Flag(Enum):
"""Support for flags"""
"""
Support for flags
"""
_name_: str | None # type: ignore[assignment]
_value_: int
@ -465,7 +504,9 @@ class Flag(Enum):
"""The value of the Enum member."""
def __contains__(self, other: Self) -> bool:
"""Returns True if self has at least the same flags set as other."""
"""
Returns True if self has at least the same flags set as other.
"""
def __bool__(self) -> bool: ...
def __or__(self, other: Self) -> Self: ...
@ -474,7 +515,9 @@ class Flag(Enum):
def __invert__(self) -> Self: ...
if sys.version_info >= (3, 11):
def __iter__(self) -> Iterator[Self]:
"""Returns flags in definition order."""
"""
Returns flags in definition order.
"""
def __len__(self) -> int: ...
__ror__ = __or__
@ -483,7 +526,9 @@ class Flag(Enum):
if sys.version_info >= (3, 11):
class StrEnum(str, ReprEnum):
"""Enum where members are also (and must be) strings"""
"""
Enum where members are also (and must be) strings
"""
def __new__(cls, value: str) -> Self: ...
_value_: str
@ -493,10 +538,14 @@ if sys.version_info >= (3, 11):
@staticmethod
def _generate_next_value_(name: str, start: int, count: int, last_values: list[str]) -> str:
"""Return the lower-cased version of the member name."""
"""
Return the lower-cased version of the member name.
"""
class EnumCheck(StrEnum):
"""various conditions to check an enumeration for"""
"""
various conditions to check an enumeration for
"""
CONTINUOUS = "no skipped integer values"
NAMED_FLAGS = "multi-flag aliases may not contain unnamed flags"
@ -507,13 +556,16 @@ if sys.version_info >= (3, 11):
UNIQUE = EnumCheck.UNIQUE
class verify:
"""Check an enumeration for various constraints. (see EnumCheck)"""
"""
Check an enumeration for various constraints. (see EnumCheck)
"""
def __init__(self, *checks: EnumCheck) -> None: ...
def __call__(self, enumeration: _EnumerationT) -> _EnumerationT: ...
class FlagBoundary(StrEnum):
"""control how out of range values are handled
"""
control how out of range values are handled
"strict" -> error is raised [default for Flag]
"conform" -> extra bits are discarded
"eject" -> lose flag status
@ -531,22 +583,27 @@ if sys.version_info >= (3, 11):
KEEP = FlagBoundary.KEEP
def global_str(self: Enum) -> str:
"""use enum_name instead of class.enum_name"""
"""
use enum_name instead of class.enum_name
"""
def global_enum(cls: _EnumerationT, update_str: bool = False) -> _EnumerationT:
"""decorator that makes the repr() of an enum member reference its module
"""
decorator that makes the repr() of an enum member reference its module
instead of its class; also exports all members to the enum's module's
global namespace
"""
def global_enum_repr(self: Enum) -> str:
"""use module.enum_name instead of class.enum_name
"""
use module.enum_name instead of class.enum_name
the module is the last module in case of a multi-module name
"""
def global_flag_repr(self: Flag) -> str:
"""use module.flag_name instead of class.flag_name
"""
use module.flag_name instead of class.flag_name
the module is the last module in case of a multi-module name
"""
@ -554,7 +611,9 @@ if sys.version_info >= (3, 11):
if sys.version_info >= (3, 11):
# 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
"""Support for integer-based Flags"""
"""
Support for integer-based Flags
"""
def __new__(cls, value: int) -> Self: ...
def __or__(self, other: int) -> Self: ...
@ -567,7 +626,9 @@ if sys.version_info >= (3, 11):
else:
class IntFlag(int, Flag): # type: ignore[misc] # complaints about incompatible bases
"""Support for integer-based Flags"""
"""
Support for integer-based Flags
"""
def __new__(cls, value: int) -> Self: ...
def __or__(self, other: int) -> Self: ...
@ -579,17 +640,13 @@ else:
__rxor__ = __xor__
class auto:
"""Instances are replaced with an appropriate value in Enum class suites."""
"""
Instances are replaced with an appropriate value in Enum class suites.
"""
_value_: Any
@_magic_enum_attr
def value(self) -> Any:
"""The base class of the class hierarchy.
When called, it accepts no arguments and returns a new featureless
instance that has no instance attributes and cannot be given any.
"""
def value(self) -> Any: ...
def __new__(cls) -> Self: ...
# These don't exist, but auto is basically immediately replaced with

View file

@ -41,6 +41,7 @@ def cmp(f1: StrOrBytesPath, f2: StrOrBytesPath, shallow: bool | Literal[0, 1] =
This function uses a cache for past comparisons and the results,
with cache entries invalidated if their stat information
changes. The cache may be cleared by calling clear_cache().
"""
def cmpfiles(
@ -56,6 +57,7 @@ def cmpfiles(
files that compare equal
files that are different
filenames that aren't regular files.
"""
class dircmp(Generic[AnyStr]):

View file

@ -69,7 +69,7 @@ import sys
from _typeshed import AnyStr_co, StrOrBytesPath
from collections.abc import Callable, Iterable
from types import GenericAlias, TracebackType
from typing import IO, Any, AnyStr, Generic, Literal, Protocol, overload
from typing import IO, Any, AnyStr, Generic, Literal, Protocol, overload, type_check_only
from typing_extensions import Self, TypeAlias
__all__ = [
@ -92,6 +92,7 @@ if sys.version_info >= (3, 11):
else:
_TextMode: TypeAlias = Literal["r", "rU", "U"]
@type_check_only
class _HasReadlineAndFileno(Protocol[AnyStr_co]):
def readline(self) -> AnyStr_co: ...
def fileno(self) -> int: ...
@ -180,7 +181,8 @@ def close() -> None:
"""Close the sequence."""
def nextfile() -> None:
"""Close the current file so that the next iteration will read the first
"""
Close the current file so that the next iteration will read the first
line from the next file (if any); lines not read from the file will
not count towards the cumulative line count. The filename is not
changed until after the first line of the next file has been read.
@ -190,34 +192,40 @@ def nextfile() -> None:
"""
def filename() -> str:
"""Return the name of the file currently being read.
"""
Return the name of the file currently being read.
Before the first line has been read, returns None.
"""
def lineno() -> int:
"""Return the cumulative line number of the line that has just been read.
"""
Return the cumulative line number of the line that has just been read.
Before the first line has been read, returns 0. After the last line
of the last file has been read, returns the line number of that line.
"""
def filelineno() -> int:
"""Return the line number in the current file. Before the first line
"""
Return the line number in the current file. Before the first line
has been read, returns 0. After the last line of the last file has
been read, returns the line number of that line within the file.
"""
def fileno() -> int:
"""Return the file number of the current file. When no file is currently
"""
Return the file number of the current file. When no file is currently
opened, returns -1.
"""
def isfirstline() -> bool:
"""Returns true the line just read is the first line of its file,
"""
Returns true the line just read is the first line of its file,
otherwise returns false.
"""
def isstdin() -> bool:
"""Returns true if the last line was read from sys.stdin,
"""
Returns true if the last line was read from sys.stdin,
otherwise returns false.
"""

View file

@ -34,6 +34,7 @@ class NullFormatter:
Implementations should inherit from this class if implementing a writer
interface but don't need to inherit any implementation.
"""
writer: NullWriter | None
@ -62,6 +63,7 @@ class AbstractFormatter:
This implementation has demonstrated wide applicability to many writers,
and may be used directly in most circumstances. It has been used to
implement a full-featured World Wide Web browser.
"""
writer: NullWriter
@ -105,6 +107,7 @@ class NullWriter:
A writer which only provides the interface definition; no actions are
taken on any methods. This should be the base class for all writers
which do not need to inherit any implementation methods.
"""
def flush(self) -> None: ...
@ -125,6 +128,7 @@ class AbstractWriter(NullWriter):
Each method simply announces itself by printing its name and
arguments on standard output.
"""
class DumbWriter(NullWriter):
@ -133,6 +137,7 @@ class DumbWriter(NullWriter):
output is simply word-wrapped to the number of columns specified by
the maxcol parameter. This class is suitable for reflowing a sequence
of paragraphs.
"""
file: IO[str]

View file

@ -4,13 +4,14 @@ import sys
from collections.abc import Callable
from decimal import Decimal
from numbers import Rational, Real
from typing import Any, Literal, Protocol, SupportsIndex, overload
from typing import Any, Literal, Protocol, SupportsIndex, overload, type_check_only
from typing_extensions import Self, TypeAlias
_ComparableNum: TypeAlias = int | float | Decimal | Real
__all__ = ["Fraction"]
@type_check_only
class _ConvertibleToIntegerRatio(Protocol):
def as_integer_ratio(self) -> tuple[int | Rational, int | Rational]: ...
@ -32,6 +33,7 @@ class Fraction(Rational):
- float and Decimal instances
- other Rational instances (including integers)
"""
@overload
@ -64,6 +66,7 @@ class Fraction(Rational):
Fraction(9, 4)
>>> Fraction(Decimal('1.47'))
Fraction(147, 100)
"""
@overload
@ -100,6 +103,7 @@ class Fraction(Rational):
Fraction(9, 4)
>>> Fraction(Decimal('1.47'))
Fraction(147, 100)
"""
@classmethod
@ -107,6 +111,7 @@ class Fraction(Rational):
"""Converts a finite float to a rational number, exactly.
Beware that Fraction.from_float(0.3) != Fraction(3, 10).
"""
@classmethod
@ -122,6 +127,7 @@ class Fraction(Rational):
Fraction(311, 99)
>>> Fraction(4321, 8765).limit_denominator(10000)
Fraction(4321, 8765)
"""
def as_integer_ratio(self) -> tuple[int, int]:
@ -245,6 +251,7 @@ class Fraction(Rational):
If b is not an integer, the result will be a float or complex
since roots are generally irrational. If b is an integer, the
result will be rational.
"""
@overload
@ -259,6 +266,7 @@ class Fraction(Rational):
If b is not an integer, the result will be a float or complex
since roots are generally irrational. If b is an integer, the
result will be rational.
"""
@overload
@ -351,4 +359,5 @@ class Fraction(Rational):
"""Converts a finite real number to a rational number, exactly.
Beware that Fraction.from_number(0.3) != Fraction(3, 10).
"""

View file

@ -135,6 +135,7 @@ def lru_cache(maxsize: int | None = 128, typed: bool = False) -> Callable[[Calla
Access the underlying function with f.__wrapped__.
See: https://en.wikipedia.org/wiki/Cache_replacement_policies#Least_recently_used_(LRU)
"""
@overload
@ -434,6 +435,7 @@ def _make_key(
If there is only a single argument and its data type is known to cache
its hash value, then that argument is returned without a wrapper. This
saves space and improves lookup speed.
"""
if sys.version_info >= (3, 14):

View file

@ -56,6 +56,7 @@ def getopt(
string if the option has no argument. The options occur in the
list in the same order in which they were found, thus allowing
multiple occurrences. Long and short options may be mixed.
"""
def gnu_getopt(
@ -72,6 +73,7 @@ def gnu_getopt(
If the first character of the option string is '+', or if the
environment variable POSIXLY_CORRECT is set, then option
processing stops as soon as a non-option argument is encountered.
"""
class GetoptError(Exception):

View file

@ -14,7 +14,7 @@ import io
import sys
from _typeshed import StrPath
from collections.abc import Callable, Container, Iterable, Sequence
from typing import Any, Final, Literal, Protocol, TypeVar, overload
from typing import Any, Final, Literal, Protocol, TypeVar, overload, type_check_only
__all__ = [
"NullTranslations",
@ -38,6 +38,7 @@ __all__ = [
if sys.version_info < (3, 11):
__all__ += ["bind_textdomain_codeset", "ldgettext", "ldngettext", "lgettext", "lngettext"]
@type_check_only
class _TranslationsReader(Protocol):
def read(self) -> bytes: ...
# optional:

View file

@ -42,6 +42,7 @@ class TopologicalSorter(Generic[_T]):
therefore no more nodes can be added using "add".
Raise ValueError if nodes have already been passed out of the sorter.
"""
def is_active(self) -> bool:

View file

@ -8,7 +8,7 @@ import sys
import zlib
from _typeshed import ReadableBuffer, SizedBuffer, StrOrBytesPath, WriteableBuffer
from io import FileIO, TextIOWrapper
from typing import Final, Literal, Protocol, overload
from typing import Final, Literal, Protocol, overload, type_check_only
from typing_extensions import TypeAlias
if sys.version_info >= (3, 14):
@ -31,6 +31,7 @@ FEXTRA: Final[int] # actually Literal[4] # undocumented
FNAME: Final[int] # actually Literal[8] # undocumented
FCOMMENT: Final[int] # actually Literal[16] # undocumented
@type_check_only
class _ReadableFileobj(Protocol):
def read(self, n: int, /) -> bytes: ...
def seek(self, n: int, /) -> object: ...
@ -39,6 +40,7 @@ class _ReadableFileobj(Protocol):
# mode: str
# def fileno() -> int: ...
@type_check_only
class _WritableFileobj(Protocol):
def write(self, b: bytes, /) -> object: ...
def flush(self) -> object: ...
@ -72,6 +74,7 @@ def open(
For text mode, a GzipFile object is created, and wrapped in an
io.TextIOWrapper instance with the specified encoding, error handling
behavior, and line ending(s).
"""
@overload
@ -124,6 +127,7 @@ class GzipFile(BaseStream):
This class only supports opening files in binary mode. If you need to open a
compressed file in text mode, use the gzip.open() function.
"""
myfileobj: FileIO | None
@ -171,6 +175,7 @@ class GzipFile(BaseStream):
is in Unix format, i.e., seconds since 00:00:00 UTC, January 1, 1970.
If mtime is omitted or None, the current time is used. Use mtime = 0
to generate a compressed stream that does not depend on creation time.
"""
@overload

View file

@ -58,6 +58,7 @@ def merge(
>>> list(merge(['dog', 'horse'], ['cat', 'fish', 'kangaroo'], key=len))
['dog', 'cat', 'fish', 'horse', 'kangaroo']
"""
def nlargest(n: int, iterable: Iterable[_S], key: Callable[[_S], SupportsRichComparison] | None = None) -> list[_S]:

View file

@ -7,14 +7,16 @@ from typing import AnyStr
__all__ = ["escape", "unescape"]
def escape(s: AnyStr, quote: bool = True) -> AnyStr:
"""Replace special characters "&", "<" and ">" to HTML-safe sequences.
"""
Replace special characters "&", "<" and ">" to HTML-safe sequences.
If the optional flag quote is true (the default), the quotation mark
characters, both double quote (") and single quote (') characters are also
translated.
"""
def unescape(s: AnyStr) -> AnyStr:
"""Convert all named and numeric character references (e.g. &gt;, &#62;,
"""
Convert all named and numeric character references (e.g. &gt;, &#62;,
&x3e;) in the string s to the corresponding unicode characters.
This function uses the rules defined by the HTML 5 standard
for both valid and invalid character references, and the list of

View file

@ -1,7 +1,9 @@
"""A parser for HTML and XHTML."""
import sys
from _markupbase import ParserBase
from re import Pattern
from typing import Final
__all__ = ["HTMLParser"]
@ -27,6 +29,10 @@ class HTMLParser(ParserBase):
argument.
"""
CDATA_CONTENT_ELEMENTS: Final[tuple[str, ...]]
if sys.version_info >= (3, 14):
RCDATA_CONTENT_ELEMENTS: Final[tuple[str, ...]]
def __init__(self, *, convert_charrefs: bool = True) -> None:
"""Initialize and reset this instance.
@ -56,7 +62,6 @@ class HTMLParser(ParserBase):
def handle_comment(self, data: str) -> None: ...
def handle_decl(self, decl: str) -> None: ...
def handle_pi(self, data: str) -> None: ...
CDATA_CONTENT_ELEMENTS: tuple[str, ...]
def check_for_whole_start_tag(self, i: int) -> int: ... # undocumented
def clear_cdata_mode(self) -> None: ... # undocumented
def goahead(self, end: bool) -> None: ... # undocumented
@ -65,6 +70,9 @@ class HTMLParser(ParserBase):
def parse_html_declaration(self, i: int) -> int: ... # undocumented
def parse_pi(self, i: int) -> int: ... # undocumented
def parse_starttag(self, i: int) -> int: ... # undocumented
if sys.version_info >= (3, 14):
def set_cdata_mode(self, elem: str, *, escapable: bool = False) -> None: ... # undocumented
else:
def set_cdata_mode(self, elem: str) -> None: ... # undocumented
rawdata: str # undocumented
cdata_elem: str | None # undocumented

View file

@ -197,6 +197,7 @@ class HTTPMessage(email.message.Message[str, str]):
returned, without interpretation. If the header does not occur, an
empty list is returned. If the header occurs multiple times, all
occurrences are returned. Case is not important in the header name.
"""
@overload
@ -250,6 +251,7 @@ class HTTPResponse(io.BufferedIOBase, BinaryIO): # type: ignore[misc] # incomp
the *default* is not specified.
If the headers are unknown, raises http.client.ResponseNotReady.
"""
@overload
@ -284,6 +286,7 @@ class HTTPResponse(io.BufferedIOBase, BinaryIO): # type: ignore[misc] # incomp
Content-Length giving file size, and a Content-Type
containing a guess at the file's type. See also the
description of the mimetools module.
"""
def geturl(self) -> str:
@ -294,11 +297,13 @@ class HTTPResponse(io.BufferedIOBase, BinaryIO): # type: ignore[misc] # incomp
some cases the caller needs to know which URL the client was
redirected to. The geturl() method can be used to get at this
redirected URL.
"""
def getcode(self) -> int:
"""Return the HTTP status code that was sent with the response,
or None if the URL is not an HTTP URL.
"""
def begin(self) -> None: ...
@ -348,7 +353,8 @@ class HTTPConnection:
def set_debuglevel(self, level: int) -> None: ...
if sys.version_info >= (3, 12):
def get_proxy_response_headers(self) -> HTTPMessage | None:
"""Returns a dictionary with the headers of the response
"""
Returns a dictionary with the headers of the response
received from the proxy server to the CONNECT request
sent to set the tunnel.

View file

@ -66,6 +66,7 @@ class CookieJar:
"""Add correct Cookie: header to request (urllib.request.Request object).
The Cookie2 header is also added unless policy.hide_cookie2 is true.
"""
def extract_cookies(self, response: HTTPResponse, request: Request) -> None:
@ -91,6 +92,7 @@ class CookieJar:
the cookie with the specified name, path and domain is removed.
Raises KeyError if no matching cookie exists.
"""
def clear_session_cookies(self) -> None:
@ -98,6 +100,7 @@ class CookieJar:
Note that the .save() method won't save session cookies anyway, unless
you ask otherwise by passing a true ignore_discard argument.
"""
def clear_expired_cookies(self) -> None: # undocumented
@ -108,6 +111,7 @@ class CookieJar:
this method is called by CookieJar itself every so often, and the
.save() method won't save expired cookies anyway (unless you ask
otherwise by passing a true ignore_expires argument).
"""
def __iter__(self) -> Iterator[Cookie]: ...
@ -120,8 +124,10 @@ class FileCookieJar(CookieJar):
filename: str | None
delayload: bool
def __init__(self, filename: StrPath | None = None, delayload: bool = False, policy: CookiePolicy | None = None) -> None:
"""Cookies are NOT loaded from the named file until either the .load() or
"""
Cookies are NOT loaded from the named file until either the .load() or
.revert() method is called.
"""
def save(self, filename: str | None = None, ignore_discard: bool = False, ignore_expires: bool = False) -> None:
@ -135,10 +141,13 @@ class FileCookieJar(CookieJar):
Raises LoadError (or OSError) if reversion is not successful; the
object's state will not be altered if this happens.
"""
class MozillaCookieJar(FileCookieJar):
"""WARNING: you may want to backup your browser's cookies file if you use
"""
WARNING: you may want to backup your browser's cookies file if you use
this class to save cookies. I *think* it works, but there have been
bugs in the past!
@ -164,13 +173,15 @@ class MozillaCookieJar(FileCookieJar):
Note that though Mozilla and Netscape use the same format, they use
slightly different headers. The class saves cookies using the Netscape
header by default (Mozilla can cope with that).
"""
if sys.version_info < (3, 10):
header: ClassVar[str] # undocumented
class LWPCookieJar(FileCookieJar):
"""The LWPCookieJar saves a sequence of "Set-Cookie3" lines.
"""
The LWPCookieJar saves a sequence of "Set-Cookie3" lines.
"Set-Cookie3" is the format used by the libwww-perl library, not known
to be compatible with any browser, but which is easy to read and
doesn't lose information about RFC 2965 cookies.
@ -178,12 +189,14 @@ class LWPCookieJar(FileCookieJar):
Additional methods
as_lwp_str(ignore_discard=True, ignore_expired=True)
"""
def as_lwp_str(self, ignore_discard: bool = True, ignore_expires: bool = True) -> str: # undocumented
"""Return cookies as a string of "\\n"-separated "Set-Cookie3" headers.
ignore_discard and ignore_expires: see docstring for FileCookieJar.save
"""
class CookiePolicy:
@ -193,6 +206,7 @@ class CookiePolicy:
The subclass DefaultCookiePolicy defines the standard rules for Netscape
and RFC 2965 cookies -- override that if you want a customized policy.
"""
netscape: bool
@ -203,6 +217,7 @@ class CookiePolicy:
Currently, pre-expired cookies never get this far -- the CookieJar
class deletes such cookies itself.
"""
def return_ok(self, cookie: Cookie, request: Request) -> bool:
@ -289,6 +304,7 @@ class Cookie:
Note that the port may be present in the headers, but unspecified ("Port"
rather than"Port=80", for example); if this is the case, port is None.
"""
version: int | None

View file

@ -188,7 +188,8 @@ class BaseCookie(dict[str, Morsel[_T]], Generic[_T]):
"""Dictionary style assignment."""
class SimpleCookie(BaseCookie[str]):
"""SimpleCookie supports strings as cookie values. When setting
"""
SimpleCookie supports strings as cookie values. When setting
the value using the dictionary assignment notation, SimpleCookie
calls the builtin str() to convert the value to a string. Values
received from HTTP are kept as strings.

View file

@ -196,6 +196,7 @@ class BaseHTTPRequestHandler(socketserver.StreamRequestHandler):
where <type> and <subtype> should be registered MIME types,
e.g. "text/html" or "text/plain".
"""
client_address: tuple[str, int]
@ -221,6 +222,7 @@ class BaseHTTPRequestHandler(socketserver.StreamRequestHandler):
You normally don't need to override this method; see the class
__doc__ string for information on how to handle specific HTTP
commands such as GET and POST.
"""
def handle_expect_100(self) -> bool:
@ -235,6 +237,7 @@ class BaseHTTPRequestHandler(socketserver.StreamRequestHandler):
This method should either return True (possibly after sending
a 100 Continue response) or send an error response and return
False.
"""
def send_error(self, code: int, message: str | None = None, explain: str | None = None) -> None:
@ -252,6 +255,7 @@ class BaseHTTPRequestHandler(socketserver.StreamRequestHandler):
This sends an error response (so it must be called before any
output has been generated), logs the error, and finally sends
a piece of HTML explaining the error to the user.
"""
def send_response(self, code: int, message: str | None = None) -> None:
@ -260,6 +264,7 @@ class BaseHTTPRequestHandler(socketserver.StreamRequestHandler):
Also send two standard headers with the server software
version and the current date.
"""
def send_header(self, keyword: str, value: str) -> None:
@ -276,6 +281,7 @@ class BaseHTTPRequestHandler(socketserver.StreamRequestHandler):
"""Log an accepted request.
This is called by send_response().
"""
def log_error(self, format: str, *args: Any) -> None:
@ -287,6 +293,7 @@ class BaseHTTPRequestHandler(socketserver.StreamRequestHandler):
Arguments are the same as for log_message().
XXX This should go to the separate error log.
"""
def log_message(self, format: str, *args: Any) -> None:
@ -306,6 +313,7 @@ class BaseHTTPRequestHandler(socketserver.StreamRequestHandler):
Unicode control characters are replaced with escaped hex
before writing the output to stderr.
"""
def version_string(self) -> str:
@ -329,6 +337,7 @@ class BaseHTTPRequestHandler(socketserver.StreamRequestHandler):
Return True for success, False for failure; on failure, any relevant
error response has already been sent back.
"""
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
@ -340,6 +349,7 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
The GET and HEAD requests are identical except that the HEAD
request omits the actual contents of the file.
"""
extensions_map: dict[str, str]
@ -369,6 +379,7 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
to the outputfile by the caller unless the command was HEAD,
and must be closed by the caller under all circumstances), or
None, in which case the caller has nothing further to do.
"""
def list_directory(self, path: StrPath) -> io.BytesIO | None: # undocumented
@ -377,6 +388,7 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
Return value is either a file object, or None (indicating an
error). In either case, the headers are sent, making the
interface the same as for send_head().
"""
def translate_path(self, path: str) -> str: # undocumented
@ -385,6 +397,7 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
Components that mean special things to the local file system
(e.g. drive or directory names) are ignored. (XXX They should
probably be diagnosed.)
"""
def copyfile(self, source: SupportsRead[AnyStr], outputfile: SupportsWrite[AnyStr]) -> None: # undocumented
@ -399,6 +412,7 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
the block size or perhaps to replace newlines by CRLF
-- note however that this the default server uses this
to copy binary data as well.
"""
def guess_type(self, path: StrPath) -> str: # undocumented
@ -413,6 +427,7 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
up in the table self.extensions_map, using application/octet-stream
as a default; however it would be permissible (if
slow) to look inside the data to make a better guess.
"""
def executable(path: StrPath) -> bool: # undocumented
@ -425,6 +440,7 @@ class CGIHTTPRequestHandler(SimpleHTTPRequestHandler):
GET and HEAD also support running CGI scripts.
The POST command is *only* implemented for CGI scripts.
"""
cgi_directories: list[str]
@ -433,6 +449,7 @@ class CGIHTTPRequestHandler(SimpleHTTPRequestHandler):
"""Serve a POST request.
This is only implemented for CGI scripts.
"""
def is_cgi(self) -> bool: # undocumented
@ -448,6 +465,7 @@ class CGIHTTPRequestHandler(SimpleHTTPRequestHandler):
The default implementation tests whether the normalized url
path begins with one of the strings in self.cgi_directories
(and the next character is a '/' or the end of the string).
"""
def is_executable(self, path: StrPath) -> bool: # undocumented

View file

@ -2,10 +2,11 @@
from _typeshed import StrPath
from collections.abc import Callable
from typing import Any, BinaryIO, Protocol, overload
from typing import Any, BinaryIO, Protocol, overload, type_check_only
__all__ = ["what"]
@type_check_only
class _ReadableBinary(Protocol):
def tell(self) -> int: ...
def read(self, size: int, /) -> bytes: ...

View file

@ -40,6 +40,7 @@ def new_module(name: str) -> types.ModuleType:
Create a new module.
The module is not entered into sys.modules.
"""
def get_magic() -> bytes:
@ -63,6 +64,7 @@ def cache_from_source(path: StrPath, debug_override: bool | None = None) -> str:
place of sys.flags.optimize.
If sys.implementation.cache_tag is None then NotImplementedError is raised.
"""
def source_from_cache(path: StrPath) -> str:
@ -74,6 +76,7 @@ def source_from_cache(path: StrPath) -> str:
the .py file calculated to correspond to the .pyc file. If path does
not conform to PEP 3147 format, ValueError will be raised. If
sys.implementation.cache_tag is None then NotImplementedError is raised.
"""
def get_suffixes() -> list[tuple[str, str, int]]:
@ -83,6 +86,7 @@ class NullImporter:
"""**DEPRECATED**
Null import object.
"""
def __init__(self, path: StrPath) -> None: ...
@ -113,6 +117,7 @@ def load_module(name: str, file: _FileLike | None, filename: str, details: tuple
Load a module, given information returned by find_module().
The module name must include the full package name, if any.
"""
# IO[Any] is a TextIOWrapper if name is a .py file, and a FileIO otherwise.
@ -127,6 +132,7 @@ def find_module(
module and continue search in sys.path. The module name cannot
contain '.'; to search for a submodule of a package, pass the
submodule name and the package's __path__.
"""
def reload(module: types.ModuleType) -> types.ModuleType:
@ -135,6 +141,7 @@ def reload(module: types.ModuleType) -> types.ModuleType:
Reload the module and return it.
The module must have been successfully imported before.
"""
def init_builtin(name: str) -> types.ModuleType | None:

Some files were not shown because too many files have changed in this diff Show more