Skip to content

Allow pickling Cancelled #3250

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Apr 21, 2025
1 change: 1 addition & 0 deletions newsfragments/3248.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Allow pickling `trio.Cancelled`, as they can show up when you want to pickle something else. This does not rule out pickling other ``NoPublicConstructor`` objects -- create an issue if necessary.
10 changes: 10 additions & 0 deletions src/trio/_core/_exceptions.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
from __future__ import annotations

from typing import TYPE_CHECKING

from trio._util import NoPublicConstructor, final

if TYPE_CHECKING:
from collections.abc import Callable


class TrioInternalError(Exception):
"""Raised by :func:`run` if we encounter a bug in Trio, or (possibly) a
Expand Down Expand Up @@ -63,6 +70,9 @@ class Cancelled(BaseException, metaclass=NoPublicConstructor):
def __str__(self) -> str:
return "Cancelled"

def __reduce__(self) -> tuple[Callable[[], Cancelled], tuple[()]]:
return (Cancelled._create, ())


class BusyResourceError(Exception):
"""Raised when a task attempts to use a resource that some other task is
Expand Down
8 changes: 8 additions & 0 deletions src/trio/_core/_tests/test_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import contextvars
import functools
import gc
import pickle
import sys
import threading
import time
Expand Down Expand Up @@ -2235,6 +2236,13 @@ def test_Cancelled_subclass() -> None:
type("Subclass", (_core.Cancelled,), {})


# https://github.com/python-trio/trio/issues/3248
def test_Cancelled_pickle() -> None:
cancelled = _core.Cancelled._create()
cancelled = pickle.loads(pickle.dumps(cancelled))
assert isinstance(cancelled, _core.Cancelled)


def test_CancelScope_subclass() -> None:
with pytest.raises(TypeError):
type("Subclass", (_core.CancelScope,), {})
Expand Down