| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from functools import partial |
| 4 |
from typing import TYPE_CHECKING, Literal, TypeAlias |
| 5 |
|
| 6 |
import attrs |
| 7 |
|
| 8 |
from trio._util import NoPublicConstructor, final |
| 9 |
|
| 10 |
if TYPE_CHECKING: |
| 11 |
from collections.abc import Callable |
| 12 |
|
| 13 |
from typing_extensions import Self |
| 14 |
|
| 15 |
CancelReasonLiteral: TypeAlias = Literal[ |
| 16 |
"KeyboardInterrupt", |
| 17 |
"deadline", |
| 18 |
"explicit", |
| 19 |
"nursery", |
| 20 |
"shutdown", |
| 21 |
"unknown", |
| 22 |
] |
| 23 |
|
| 24 |
|
| 25 |
class TrioInternalError(Exception): |
| 26 |
"""Raised by :func:`run` if we encounter a bug in Trio, or (possibly) a |
| 27 |
misuse of one of the low-level :mod:`trio.lowlevel` APIs. |
| 28 |
|
| 29 |
This should never happen! If you get this error, please file a bug. |
| 30 |
|
| 31 |
Unfortunately, if you get this error it also means that all bets are off – |
| 32 |
Trio doesn't know what is going on and its normal invariants may be void. |
| 33 |
(For example, we might have "lost track" of a task. Or lost track of all |
| 34 |
tasks.) Again, though, this shouldn't happen. |
| 35 |
|
| 36 |
""" |
| 37 |
|
| 38 |
|
| 39 |
class RunFinishedError(RuntimeError): |
| 40 |
"""Raised by `trio.from_thread.run` and similar functions if the |
| 41 |
corresponding call to :func:`trio.run` has already finished. |
| 42 |
|
| 43 |
""" |
| 44 |
|
| 45 |
|
| 46 |
class WouldBlock(Exception): |
| 47 |
"""Raised by ``X_nowait`` functions if ``X`` would block.""" |
| 48 |
|
| 49 |
|
| 50 |
@final |
| 51 |
@attrs.define(eq=False, kw_only=True) |
| 52 |
class Cancelled(BaseException, metaclass=NoPublicConstructor): |
| 53 |
"""Raised by blocking calls if the surrounding scope has been cancelled. |
| 54 |
|
| 55 |
You should let this exception propagate, to be caught by the relevant |
| 56 |
cancel scope. To remind you of this, it inherits from :exc:`BaseException` |
| 57 |
instead of :exc:`Exception`, just like :exc:`KeyboardInterrupt` and |
| 58 |
:exc:`SystemExit` do. This means that if you write something like:: |
| 59 |
|
| 60 |
try: |
| 61 |
... |
| 62 |
except Exception: |
| 63 |
... |
| 64 |
|
| 65 |
then this *won't* catch a :exc:`Cancelled` exception. |
| 66 |
|
| 67 |
You cannot raise :exc:`Cancelled` yourself. Attempting to do so |
| 68 |
will produce a :exc:`TypeError`. Use :meth:`cancel_scope.cancel() |
| 69 |
<trio.CancelScope.cancel>` instead. |
| 70 |
|
| 71 |
.. note:: |
| 72 |
|
| 73 |
In the US it's also common to see this word spelled "canceled", with |
| 74 |
only one "l". This is a `recent |
| 75 |
<https://books.google.com/ngrams/graph?content=canceled%2Ccancelled&year_start=1800&year_end=2000&corpus=5&smoothing=3&direct_url=t1%3B%2Ccanceled%3B%2Cc0%3B.t1%3B%2Ccancelled%3B%2Cc0>`__ |
| 76 |
and `US-specific |
| 77 |
<https://books.google.com/ngrams/graph?content=canceled%2Ccancelled&year_start=1800&year_end=2000&corpus=18&smoothing=3&share=&direct_url=t1%3B%2Ccanceled%3B%2Cc0%3B.t1%3B%2Ccancelled%3B%2Cc0>`__ |
| 78 |
innovation, and even in the US both forms are still commonly used. So |
| 79 |
for consistency with the rest of the world and with "cancellation" |
| 80 |
(which always has two "l"s), Trio uses the two "l" spelling |
| 81 |
everywhere. |
| 82 |
|
| 83 |
""" |
| 84 |
|
| 85 |
source: CancelReasonLiteral = "unknown" |
| 86 |
# repr(Task), so as to avoid gc troubles from holding a reference |
| 87 |
source_task: str | None = None |
| 88 |
reason: str | None = None |
| 89 |
|
| 90 |
def __str__(self) -> str: |
| 91 |
return ( |
| 92 |
f"cancelled due to {self.source}" |
| 93 |
+ ("" if self.reason is None else f" with reason {self.reason!r}") |
| 94 |
+ ("" if self.source_task is None else f" from task {self.source_task}") |
| 95 |
) |
| 96 |
|
| 97 |
def __reduce__(self) -> tuple[Callable[[], Cancelled], tuple[()]]: |
| 98 |
# The `__reduce__` tuple does not support directly passing kwargs, and the |
| 99 |
# kwargs are required so we can't use the third item for adding to __dict__, |
| 100 |
# so we use partial. |
| 101 |
return ( |
| 102 |
partial( |
| 103 |
Cancelled._create, |
| 104 |
source=self.source, |
| 105 |
source_task=self.source_task, |
| 106 |
reason=self.reason, |
| 107 |
), |
| 108 |
(), |
| 109 |
) |
| 110 |
|
| 111 |
if TYPE_CHECKING: |
| 112 |
# for type checking on internal code |
| 113 |
@classmethod |
| 114 |
def _create( |
| 115 |
cls, |
| 116 |
*, |
| 117 |
source: CancelReasonLiteral = "unknown", |
| 118 |
source_task: str | None = None, |
| 119 |
reason: str | None = None, |
| 120 |
) -> Self: ... |
| 121 |
|
| 122 |
|
| 123 |
class BusyResourceError(Exception): |
| 124 |
"""Raised when a task attempts to use a resource that some other task is |
| 125 |
already using, and this would lead to bugs and nonsense. |
| 126 |
|
| 127 |
For example, if two tasks try to send data through the same socket at the |
| 128 |
same time, Trio will raise :class:`BusyResourceError` instead of letting |
| 129 |
the data get scrambled. |
| 130 |
|
| 131 |
""" |
| 132 |
|
| 133 |
|
| 134 |
class ClosedResourceError(Exception): |
| 135 |
"""Raised when attempting to use a resource after it has been closed. |
| 136 |
|
| 137 |
Note that "closed" here means that *your* code closed the resource, |
| 138 |
generally by calling a method with a name like ``close`` or ``aclose``, or |
| 139 |
by exiting a context manager. If a problem arises elsewhere – for example, |
| 140 |
because of a network failure, or because a remote peer closed their end of |
| 141 |
a connection – then that should be indicated by a different exception |
| 142 |
class, like :exc:`BrokenResourceError` or an :exc:`OSError` subclass. |
| 143 |
|
| 144 |
""" |
| 145 |
|
| 146 |
|
| 147 |
class BrokenResourceError(Exception): |
| 148 |
"""Raised when an attempt to use a resource fails due to external |
| 149 |
circumstances. |
| 150 |
|
| 151 |
For example, you might get this if you try to send data on a stream where |
| 152 |
the remote side has already closed the connection. |
| 153 |
|
| 154 |
You *don't* get this error if *you* closed the resource – in that case you |
| 155 |
get :class:`ClosedResourceError`. |
| 156 |
|
| 157 |
This exception's ``__cause__`` attribute will often contain more |
| 158 |
information about the underlying error. |
| 159 |
|
| 160 |
""" |
| 161 |
|
| 162 |
|
| 163 |
class EndOfChannel(Exception): |
| 164 |
"""Raised when trying to receive from a :class:`trio.abc.ReceiveChannel` |
| 165 |
that has no more data to receive. |
| 166 |
|
| 167 |
This is analogous to an "end-of-file" condition, but for channels. |
| 168 |
|
| 169 |
""" |