|
| 1 | +import sys |
| 2 | +from collections.abc import Callable, Iterator, Mapping |
| 3 | +from typing import Any, ClassVar, Generic, TypeVar, final, overload |
| 4 | +from typing_extensions import ParamSpec |
| 5 | + |
| 6 | +if sys.version_info >= (3, 9): |
| 7 | + from types import GenericAlias |
| 8 | + |
| 9 | +_T = TypeVar("_T") |
| 10 | +_D = TypeVar("_D") |
| 11 | +_P = ParamSpec("_P") |
| 12 | + |
| 13 | +@final |
| 14 | +class ContextVar(Generic[_T]): |
| 15 | + @overload |
| 16 | + def __init__(self, name: str) -> None: ... |
| 17 | + @overload |
| 18 | + def __init__(self, name: str, *, default: _T) -> None: ... |
| 19 | + def __hash__(self) -> int: ... |
| 20 | + @property |
| 21 | + def name(self) -> str: ... |
| 22 | + @overload |
| 23 | + def get(self) -> _T: ... |
| 24 | + @overload |
| 25 | + def get(self, default: _T, /) -> _T: ... |
| 26 | + @overload |
| 27 | + def get(self, default: _D, /) -> _D | _T: ... |
| 28 | + def set(self, value: _T, /) -> Token[_T]: ... |
| 29 | + def reset(self, token: Token[_T], /) -> None: ... |
| 30 | + if sys.version_info >= (3, 9): |
| 31 | + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... |
| 32 | + |
| 33 | +@final |
| 34 | +class Token(Generic[_T]): |
| 35 | + @property |
| 36 | + def var(self) -> ContextVar[_T]: ... |
| 37 | + @property |
| 38 | + def old_value(self) -> Any: ... # returns either _T or MISSING, but that's hard to express |
| 39 | + MISSING: ClassVar[object] |
| 40 | + if sys.version_info >= (3, 9): |
| 41 | + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... |
| 42 | + |
| 43 | +def copy_context() -> Context: ... |
| 44 | + |
| 45 | +# It doesn't make sense to make this generic, because for most Contexts each ContextVar will have |
| 46 | +# a different value. |
| 47 | +@final |
| 48 | +class Context(Mapping[ContextVar[Any], Any]): |
| 49 | + def __init__(self) -> None: ... |
| 50 | + @overload |
| 51 | + def get(self, key: ContextVar[_T], default: None = None, /) -> _T | None: ... |
| 52 | + @overload |
| 53 | + def get(self, key: ContextVar[_T], default: _T, /) -> _T: ... |
| 54 | + @overload |
| 55 | + def get(self, key: ContextVar[_T], default: _D, /) -> _T | _D: ... |
| 56 | + def run(self, callable: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs) -> _T: ... |
| 57 | + def copy(self) -> Context: ... |
| 58 | + def __getitem__(self, key: ContextVar[_T], /) -> _T: ... |
| 59 | + def __iter__(self) -> Iterator[ContextVar[Any]]: ... |
| 60 | + def __len__(self) -> int: ... |
| 61 | + def __eq__(self, value: object, /) -> bool: ... |
0 commit comments