Debian Codegraph @

src/trio/_util.py

raw
1 # Little utilities we use internally
2 from __future__ import annotations
3
4 import collections.abc
5 import inspect
6 import signal
7 from abc import ABCMeta
8 from collections.abc import Awaitable, Callable, Sequence
9 from typing import (
10 TYPE_CHECKING,
11 Any,
12 NoReturn,
13 TypeVar,
14 final as std_final,
15 )
16
17 from sniffio import thread_local as sniffio_loop
18
19 import trio
20
21 # Explicit "Any" is not allowed
22 CallT = TypeVar("CallT", bound=Callable[..., Any]) # type: ignore[explicit-any]
23 T = TypeVar("T")
24 RetT = TypeVar("RetT")
25
26 if TYPE_CHECKING:
27 import sys
28 from types import AsyncGeneratorType, TracebackType
29
30 from typing_extensions import TypeVarTuple, Unpack
31
32 if sys.version_info < (3, 11):
33 from exceptiongroup import BaseExceptionGroup
34
35 PosArgsT = TypeVarTuple("PosArgsT")
36
37
38 # See: #461 as to why this is needed.
39 # The gist is that threading.main_thread() has the capability to lie to us
40 # if somebody else edits the threading ident cache to replace the main
41 # thread; causing threading.current_thread() to return a _DummyThread,
42 # causing the C-c check to fail, and so on.
43 # Trying to use signal out of the main thread will fail, so we can then
44 # reliably check if this is the main thread without relying on a
45 # potentially modified threading.
46 def is_main_thread() -> bool:
47 """Attempt to reliably check if we are in the main thread."""
48 try:
49 signal.signal(signal.SIGINT, signal.getsignal(signal.SIGINT))
50 return True
51 except (TypeError, ValueError):
52 return False
53
54
55 ######
56 # Call the function and get the coroutine object, while giving helpful
57 # errors for common mistakes. Returns coroutine object.
58 ######
59 def coroutine_or_error(
60 async_fn: Callable[[Unpack[PosArgsT]], Awaitable[RetT]],
61 *args: Unpack[PosArgsT],
62 ) -> collections.abc.Coroutine[object, NoReturn, RetT]:
63 def _return_value_looks_like_wrong_library(value: object) -> bool:
64 # Returned by legacy @asyncio.coroutine functions, which includes
65 # a surprising proportion of asyncio builtins.
66 if isinstance(value, collections.abc.Generator):
67 return True
68 # The protocol for detecting an asyncio Future-like object
69 if getattr(value, "_asyncio_future_blocking", None) is not None:
70 return True
71 # This janky check catches tornado Futures and twisted Deferreds.
72 # By the time we're calling this function, we already know
73 # something has gone wrong, so a heuristic is pretty safe.
74 return value.__class__.__name__ in ("Future", "Deferred")
75
76 # Make sure a sync-fn-that-returns-coroutine still sees itself as being
77 # in trio context
78 prev_loop, sniffio_loop.name = sniffio_loop.name, "trio"
79
80 try:
81 coro = async_fn(*args)
82
83 except TypeError:
84 # Give good error for: nursery.start_soon(trio.sleep(1))
85 if isinstance(async_fn, collections.abc.Coroutine):
86 # explicitly close coroutine to avoid RuntimeWarning
87 async_fn.close()
88
89 raise TypeError(
90 "Trio was expecting an async function, but instead it got "
91 f"a coroutine object {async_fn!r}\n"
92 "\n"
93 "Probably you did something like:\n"
94 "\n"
95 f" trio.run({async_fn.__name__}(...)) # incorrect!\n"
96 f" nursery.start_soon({async_fn.__name__}(...)) # incorrect!\n"
97 "\n"
98 "Instead, you want (notice the parentheses!):\n"
99 "\n"
100 f" trio.run({async_fn.__name__}, ...) # correct!\n"
101 f" nursery.start_soon({async_fn.__name__}, ...) # correct!",
102 ) from None
103
104 # Give good error for: nursery.start_soon(future)
105 if _return_value_looks_like_wrong_library(async_fn):
106 raise TypeError(
107 "Trio was expecting an async function, but instead it got "
108 f"{async_fn!r} – are you trying to use a library written for "
109 "asyncio/twisted/tornado or similar? That won't work "
110 "without some sort of compatibility shim.",
111 ) from None
112
113 raise
114
115 finally:
116 sniffio_loop.name = prev_loop
117
118 # We can't check iscoroutinefunction(async_fn), because that will fail
119 # for things like functools.partial objects wrapping an async
120 # function. So we have to just call it and then check whether the
121 # return value is a coroutine object.
122 # Note: will not be necessary on python>=3.8, see https://bugs.python.org/issue34890
123 # TODO: python3.7 support is now dropped, so the above can be addressed.
124 if not isinstance(coro, collections.abc.Coroutine):
125 # Give good error for: nursery.start_soon(func_returning_future)
126 if _return_value_looks_like_wrong_library(coro):
127 raise TypeError(
128 f"Trio got unexpected {coro!r} – are you trying to use a "
129 "library written for asyncio/twisted/tornado or similar? "
130 "That won't work without some sort of compatibility shim.",
131 )
132
133 if inspect.isasyncgen(coro):
134 raise TypeError(
135 "start_soon expected an async function but got an async "
136 f"generator {coro!r}",
137 )
138
139 # Give good error for: nursery.start_soon(some_sync_fn)
140 raise TypeError(
141 "Trio expected an async function, but {!r} appears to be "
142 "synchronous".format(getattr(async_fn, "__qualname__", async_fn)),
143 )
144
145 return coro
146
147
148 class ConflictDetector:
149 """Detect when two tasks are about to perform operations that would
150 conflict.
151
152 Use as a synchronous context manager; if two tasks enter it at the same
153 time then the second one raises an error. You can use it when there are
154 two pieces of code that *would* collide and need a lock if they ever were
155 called at the same time, but that should never happen.
156
157 We use this in particular for things like, making sure that two different
158 tasks don't call sendall simultaneously on the same stream.
159
160 """
161
162 def __init__(self, msg: str) -> None:
163 self._msg = msg
164 self._held = False
165
166 def __enter__(self) -> None:
167 if self._held:
168 raise trio.BusyResourceError(self._msg)
169 else:
170 self._held = True
171
172 def __exit__(
173 self,
174 exc_type: type[BaseException] | None,
175 exc_value: BaseException | None,
176 traceback: TracebackType | None,
177 ) -> None:
178 self._held = False
179
180
181 def async_wraps( # type: ignore[explicit-any]
182 cls: type[object],
183 wrapped_cls: type[object],
184 attr_name: str,
185 ) -> Callable[[CallT], CallT]:
186 """Similar to wraps, but for async wrappers of non-async functions."""
187
188 def decorator(func: CallT) -> CallT: # type: ignore[explicit-any]
189 func.__name__ = attr_name
190 func.__qualname__ = f"{cls.__qualname__}.{attr_name}"
191
192 func.__doc__ = f"Like :meth:`~{wrapped_cls.__module__}.{wrapped_cls.__qualname__}.{attr_name}`, but async."
193
194 return func
195
196 return decorator
197
198
199 def fixup_module_metadata(
200 module_name: str,
201 namespace: collections.abc.Mapping[str, object],
202 ) -> None:
203 seen_ids: set[int] = set()
204
205 def fix_one(qualname: str, name: str, obj: object) -> None:
206 # avoid infinite recursion (relevant when using
207 # typing.Generic, for example)
208 if id(obj) in seen_ids:
209 return
210 seen_ids.add(id(obj))
211
212 mod = getattr(obj, "__module__", None)
213 if mod is not None and mod.startswith("trio."):
214 obj.__module__ = module_name
215 # Modules, unlike everything else in Python, put fully-qualified
216 # names into their __name__ attribute. We check for "." to avoid
217 # rewriting these.
218 if hasattr(obj, "__name__") and "." not in obj.__name__:
219 obj.__name__ = name
220 if hasattr(obj, "__qualname__"):
221 obj.__qualname__ = qualname
222 if isinstance(obj, type):
223 for attr_name, attr_value in obj.__dict__.items():
224 fix_one(objname + "." + attr_name, attr_name, attr_value)
225
226 for objname, obj in namespace.items():
227 if not objname.startswith("_"): # ignore private attributes
228 fix_one(objname, objname, obj)
229
230
231 def _init_final_cls(cls: type[object]) -> NoReturn:
232 """Raises an exception when a final class is subclassed."""
233 raise TypeError(f"{cls.__module__}.{cls.__qualname__} does not support subclassing")
234
235
236 def _final_impl(decorated: type[T]) -> type[T]:
237 """Decorator that enforces a class to be final (i.e., subclass not allowed).
238
239 If a class uses this metaclass like this::
240
241 @final
242 class SomeClass:
243 pass
244
245 The metaclass will ensure that no subclass can be created.
246
247 Raises
248 ------
249 - TypeError if a subclass is created
250 """
251 # Override the method blindly. We're always going to raise, so it doesn't
252 # matter what the original did (if anything).
253 decorated.__init_subclass__ = classmethod(_init_final_cls) # type: ignore[assignment]
254 # Apply the typing decorator, in 3.11+ it adds a __final__ marker attribute.
255 return std_final(decorated)
256
257
258 if TYPE_CHECKING:
259 from typing import final
260 else:
261 final = _final_impl
262
263
264 @final # No subclassing of NoPublicConstructor itself.
265 class NoPublicConstructor(ABCMeta):
266 """Metaclass that ensures a private constructor.
267
268 If a class uses this metaclass like this::
269
270 @final
271 class SomeClass(metaclass=NoPublicConstructor):
272 pass
273
274 The metaclass will ensure that no instance can be initialized. This should always be
275 used with @final.
276
277 If you try to instantiate your class (SomeClass()), a TypeError will be thrown. Use
278 _create() instead in the class's implementation.
279
280 Raises
281 ------
282 - TypeError if an instance is created.
283 """
284
285 def __call__(cls, *args: object, **kwargs: object) -> None:
286 raise TypeError(
287 f"{cls.__module__}.{cls.__qualname__} has no public constructor",
288 )
289
290 def _create(cls: type[T], *args: object, **kwargs: object) -> T:
291 return super().__call__(*args, **kwargs) # type: ignore
292
293
294 def name_asyncgen(agen: AsyncGeneratorType[object, NoReturn]) -> str:
295 """Return the fully-qualified name of the async generator function
296 that produced the async generator iterator *agen*.
297 """
298 if not hasattr(agen, "ag_code"): # pragma: no cover
299 return repr(agen)
300 try:
301 # `agen.ag_frame` can be None, but we catch AttributeError.
302 module = agen.ag_frame.f_globals["__name__"] # type: ignore[union-attr]
303 except (AttributeError, KeyError):
304 module = f"<{agen.ag_code.co_filename}>"
305 try:
306 qualname = agen.__qualname__
307 except AttributeError:
308 qualname = agen.ag_code.co_name
309 return f"{module}.{qualname}"
310
311
312 # work around a pyright error
313 if TYPE_CHECKING:
314 Fn = TypeVar("Fn", bound=Callable[..., object]) # type: ignore[explicit-any]
315
316 def wraps( # type: ignore[explicit-any]
317 wrapped: Callable[..., object],
318 assigned: Sequence[str] = ...,
319 updated: Sequence[str] = ...,
320 ) -> Callable[[Fn], Fn]: ...
321
322 else:
323 from functools import wraps # noqa: F401 # this is re-exported
324
325
326 def raise_saving_context(exc: BaseException) -> NoReturn:
327 """This helper allows re-raising an exception without __context__ being set."""
328 # cause does not need special handling, we simply avoid using `raise .. from ..`
329 # __suppress_context__ also does not need handling, it's only set if modifying cause
330 __tracebackhide__ = True
331 context = exc.__context__
332 try:
333 raise exc
334 finally:
335 exc.__context__ = context
336 del exc, context
337
338
339 class MultipleExceptionError(Exception):
340 """Raised by raise_single_exception_from_group if encountering multiple
341 non-cancelled exceptions."""
342
343
344 def raise_single_exception_from_group(
345 eg: BaseExceptionGroup[BaseException],
346 ) -> NoReturn:
347 """This function takes an exception group that is assumed to have at most
348 one non-cancelled exception, which it reraises as a standalone exception.
349
350 This exception may be an exceptiongroup itself, in which case it will not be unwrapped.
351
352 If a :exc:`KeyboardInterrupt` is encountered, a new KeyboardInterrupt is immediately
353 raised with the entire group as cause.
354
355 If the group only contains :exc:`Cancelled` it reraises the first one encountered.
356
357 It will retain context and cause of the contained exception, and entirely discard
358 the cause/context of the group(s).
359
360 If multiple non-cancelled exceptions are encountered, it raises
361 :exc:`AssertionError`.
362 """
363 # immediately bail out if there's any KI or SystemExit
364 for e in eg.exceptions:
365 if isinstance(e, (KeyboardInterrupt, SystemExit)):
366 raise type(e)(*e.args) from eg
367
368 cancelled_exception: trio.Cancelled | None = None
369 noncancelled_exception: BaseException | None = None
370
371 for e in eg.exceptions:
372 if isinstance(e, trio.Cancelled):
373 if cancelled_exception is None:
374 cancelled_exception = e
375 elif noncancelled_exception is None:
376 noncancelled_exception = e
377 else:
378 raise MultipleExceptionError(
379 "Attempted to unwrap exceptiongroup with multiple non-cancelled exceptions. This is often caused by a bug in the caller."
380 ) from eg
381
382 if noncancelled_exception is not None:
383 raise_saving_context(noncancelled_exception)
384
385 assert cancelled_exception is not None, "group can't be empty"
386 raise_saving_context(cancelled_exception)