Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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