Debian Codegraph @

jedi/third_party/typeshed/stdlib/contextlib.pyi

raw symbols SCIP
1 import abc
2 import sys
3 from _typeshed import FileDescriptorOrPath, Unused
4 from abc import ABC, abstractmethod
5 from collections.abc import AsyncGenerator, AsyncIterator, Awaitable, Callable, Generator, Iterator
6 from types import TracebackType
7 from typing import Any, Generic, Protocol, TypeVar, overload, runtime_checkable, type_check_only
8 from typing_extensions import ParamSpec, Self, TypeAlias, deprecated
9
10 __all__ = [
11 "contextmanager",
12 "closing",
13 "AbstractContextManager",
14 "ContextDecorator",
15 "ExitStack",
16 "redirect_stdout",
17 "redirect_stderr",
18 "suppress",
19 "AbstractAsyncContextManager",
20 "AsyncExitStack",
21 "asynccontextmanager",
22 "nullcontext",
23 ]
24
25 if sys.version_info >= (3, 10):
26 __all__ += ["aclosing"]
27
28 if sys.version_info >= (3, 11):
29 __all__ += ["chdir"]
30
31 _T = TypeVar("_T")
32 _T_co = TypeVar("_T_co", covariant=True)
33 _ExitT_co = TypeVar("_ExitT_co", covariant=True, bound=bool | None, default=bool | None)
34 _F = TypeVar("_F", bound=Callable[..., Any])
35 _G_co = TypeVar("_G_co", bound=Generator[Any, Any, Any] | AsyncGenerator[Any, Any], covariant=True)
36 _P = ParamSpec("_P")
37
38 _SendT_contra = TypeVar("_SendT_contra", contravariant=True, default=None)
39 _ReturnT_co = TypeVar("_ReturnT_co", covariant=True, default=None)
40
41 _ExitFunc: TypeAlias = Callable[[type[BaseException] | None, BaseException | None, TracebackType | None], bool | None]
42 _CM_EF = TypeVar("_CM_EF", bound=AbstractContextManager[Any, Any] | _ExitFunc)
43
44 # mypy and pyright object to this being both ABC and Protocol.
45 # At runtime it inherits from ABC and is not a Protocol, but it is on the
46 # allowlist for use as a Protocol.
47 @runtime_checkable
48 class AbstractContextManager(ABC, Protocol[_T_co, _ExitT_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues]
49 __slots__ = ()
50 def __enter__(self) -> _T_co: ...
51 @abstractmethod
52 def __exit__(
53 self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, /
54 ) -> _ExitT_co: ...
55
56 # mypy and pyright object to this being both ABC and Protocol.
57 # At runtime it inherits from ABC and is not a Protocol, but it is on the
58 # allowlist for use as a Protocol.
59 @runtime_checkable
60 class AbstractAsyncContextManager(ABC, Protocol[_T_co, _ExitT_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues]
61 __slots__ = ()
62 async def __aenter__(self) -> _T_co: ...
63 @abstractmethod
64 async def __aexit__(
65 self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, /
66 ) -> _ExitT_co: ...
67
68 class ContextDecorator:
69 def _recreate_cm(self) -> Self: ...
70 def __call__(self, func: _F) -> _F: ...
71
72 class _GeneratorContextManagerBase(Generic[_G_co]):
73 # Ideally this would use ParamSpec, but that requires (*args, **kwargs), which this isn't. see #6676
74 def __init__(self, func: Callable[..., _G_co], args: tuple[Any, ...], kwds: dict[str, Any]) -> None: ...
75 gen: _G_co
76 func: Callable[..., _G_co]
77 args: tuple[Any, ...]
78 kwds: dict[str, Any]
79
80 class _GeneratorContextManager(
81 _GeneratorContextManagerBase[Generator[_T_co, _SendT_contra, _ReturnT_co]],
82 AbstractContextManager[_T_co, bool | None],
83 ContextDecorator,
84 ):
85 def __exit__(
86 self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None
87 ) -> bool | None: ...
88
89 @overload
90 def contextmanager(func: Callable[_P, Generator[_T_co, None, object]]) -> Callable[_P, _GeneratorContextManager[_T_co]]: ...
91 @overload
92 @deprecated(
93 "Annotating the return type as `-> Iterator[Foo]` with `@contextmanager` is deprecated. Use `-> Generator[Foo]` instead."
94 )
95 def contextmanager(func: Callable[_P, Iterator[_T_co]]) -> Callable[_P, _GeneratorContextManager[_T_co]]: ...
96
97 if sys.version_info >= (3, 10):
98 _AF = TypeVar("_AF", bound=Callable[..., Awaitable[Any]])
99
100 class AsyncContextDecorator:
101 def _recreate_cm(self) -> Self: ...
102 def __call__(self, func: _AF) -> _AF: ...
103
104 class _AsyncGeneratorContextManager(
105 _GeneratorContextManagerBase[AsyncGenerator[_T_co, _SendT_contra]],
106 AbstractAsyncContextManager[_T_co, bool | None],
107 AsyncContextDecorator,
108 ):
109 async def __aexit__(
110 self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None
111 ) -> bool | None: ...
112
113 else:
114 class _AsyncGeneratorContextManager(
115 _GeneratorContextManagerBase[AsyncGenerator[_T_co, _SendT_contra]], AbstractAsyncContextManager[_T_co, bool | None]
116 ):
117 async def __aexit__(
118 self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None
119 ) -> bool | None: ...
120
121 @overload
122 def asynccontextmanager(func: Callable[_P, AsyncGenerator[_T_co]]) -> Callable[_P, _AsyncGeneratorContextManager[_T_co]]: ...
123 @overload
124 @deprecated(
125 "Annotating the return type as `-> AsyncIterator[Foo]` with `@asynccontextmanager` is deprecated. "
126 "Use `-> AsyncGenerator[Foo]` instead."
127 )
128 def asynccontextmanager(func: Callable[_P, AsyncIterator[_T_co]]) -> Callable[_P, _AsyncGeneratorContextManager[_T_co]]: ...
129 @type_check_only
130 class _SupportsClose(Protocol):
131 def close(self) -> object: ...
132
133 _SupportsCloseT = TypeVar("_SupportsCloseT", bound=_SupportsClose)
134
135 class closing(AbstractContextManager[_SupportsCloseT, None]):
136 def __init__(self, thing: _SupportsCloseT) -> None: ...
137 def __exit__(self, *exc_info: Unused) -> None: ...
138
139 if sys.version_info >= (3, 10):
140 @type_check_only
141 class _SupportsAclose(Protocol):
142 def aclose(self) -> Awaitable[object]: ...
143
144 _SupportsAcloseT = TypeVar("_SupportsAcloseT", bound=_SupportsAclose)
145
146 class aclosing(AbstractAsyncContextManager[_SupportsAcloseT, None]):
147 def __init__(self, thing: _SupportsAcloseT) -> None: ...
148 async def __aexit__(self, *exc_info: Unused) -> None: ...
149
150 class suppress(AbstractContextManager[None, bool]):
151 def __init__(self, *exceptions: type[BaseException]) -> None: ...
152 def __exit__(
153 self, exctype: type[BaseException] | None, excinst: BaseException | None, exctb: TracebackType | None
154 ) -> bool: ...
155
156 # This is trying to describe what is needed for (most?) uses
157 # of `redirect_stdout` and `redirect_stderr`.
158 # https://github.com/python/typeshed/issues/14903
159 @type_check_only
160 class _SupportsRedirect(Protocol):
161 def write(self, s: str, /) -> int: ...
162 def flush(self) -> None: ...
163
164 _SupportsRedirectT = TypeVar("_SupportsRedirectT", bound=_SupportsRedirect | None)
165
166 class _RedirectStream(AbstractContextManager[_SupportsRedirectT, None]):
167 def __init__(self, new_target: _SupportsRedirectT) -> None: ...
168 def __exit__(
169 self, exctype: type[BaseException] | None, excinst: BaseException | None, exctb: TracebackType | None
170 ) -> None: ...
171
172 class redirect_stdout(_RedirectStream[_SupportsRedirectT]): ...
173 class redirect_stderr(_RedirectStream[_SupportsRedirectT]): ...
174
175 class _BaseExitStack(Generic[_ExitT_co]):
176 def enter_context(self, cm: AbstractContextManager[_T, _ExitT_co]) -> _T: ...
177 def push(self, exit: _CM_EF) -> _CM_EF: ...
178 def callback(self, callback: Callable[_P, _T], /, *args: _P.args, **kwds: _P.kwargs) -> Callable[_P, _T]: ...
179 def pop_all(self) -> Self: ...
180
181 # this class is to avoid putting `metaclass=abc.ABCMeta` on the implementations directly, as this would make them
182 # appear explicitly abstract to some tools. this is due to the implementations not subclassing `AbstractContextManager`
183 # see note on the subclasses
184 @type_check_only
185 class _BaseExitStackAbstract(_BaseExitStack[_ExitT_co], metaclass=abc.ABCMeta): ...
186
187 # In reality this is a subclass of `AbstractContextManager`, but we can't provide `Self` as the argument for `__enter__`
188 # https://discuss.python.org/t/self-as-typevar-default/90939
189 class ExitStack(_BaseExitStackAbstract[_ExitT_co]):
190 def close(self) -> None: ...
191 def __enter__(self) -> Self: ...
192 def __exit__(
193 self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, /
194 ) -> _ExitT_co: ...
195
196 _ExitCoroFunc: TypeAlias = Callable[
197 [type[BaseException] | None, BaseException | None, TracebackType | None], Awaitable[bool | None]
198 ]
199 _ACM_EF = TypeVar("_ACM_EF", bound=AbstractAsyncContextManager[Any, Any] | _ExitCoroFunc)
200
201 # In reality this is a subclass of `AbstractContextManager`, but we can't provide `Self` as the argument for `__enter__`
202 # https://discuss.python.org/t/self-as-typevar-default/90939
203 class AsyncExitStack(_BaseExitStackAbstract[_ExitT_co]):
204 async def enter_async_context(self, cm: AbstractAsyncContextManager[_T, _ExitT_co]) -> _T: ...
205 def push_async_exit(self, exit: _ACM_EF) -> _ACM_EF: ...
206 def push_async_callback(
207 self, callback: Callable[_P, Awaitable[_T]], /, *args: _P.args, **kwds: _P.kwargs
208 ) -> Callable[_P, Awaitable[_T]]: ...
209 async def aclose(self) -> None: ...
210 async def __aenter__(self) -> Self: ...
211 async def __aexit__(
212 self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, /
213 ) -> _ExitT_co: ...
214
215 if sys.version_info >= (3, 10):
216 class nullcontext(AbstractContextManager[_T, None], AbstractAsyncContextManager[_T, None]):
217 enter_result: _T
218 @overload
219 def __init__(self: nullcontext[None]) -> None: ...
220 @overload
221 def __init__(self: nullcontext[_T], enter_result: _T) -> None: ... # pyright: ignore[reportInvalidTypeVarUse] #11780
222 def __enter__(self) -> _T: ...
223 def __exit__(self, *exctype: Unused) -> None: ...
224 async def __aenter__(self) -> _T: ...
225 async def __aexit__(self, *exctype: Unused) -> None: ...
226
227 else:
228 class nullcontext(AbstractContextManager[_T, None]):
229 enter_result: _T
230 @overload
231 def __init__(self: nullcontext[None]) -> None: ...
232 @overload
233 def __init__(self: nullcontext[_T], enter_result: _T) -> None: ... # pyright: ignore[reportInvalidTypeVarUse] #11780
234 def __enter__(self) -> _T: ...
235 def __exit__(self, *exctype: Unused) -> None: ...
236
237 if sys.version_info >= (3, 11):
238 _T_fd_or_any_path = TypeVar("_T_fd_or_any_path", bound=FileDescriptorOrPath)
239
240 class chdir(AbstractContextManager[None, None], Generic[_T_fd_or_any_path]):
241 path: _T_fd_or_any_path
242 def __init__(self, path: _T_fd_or_any_path) -> None: ...
243 def __enter__(self) -> None: ...
244 def __exit__(self, *excinfo: Unused) -> None: ...