Skip to content
Open
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
5 changes: 5 additions & 0 deletions docs/versionhistory.rst
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,11 @@ This library adheres to `Semantic Versioning 2.0 <http://semver.org/>`_.
task.

(`#1197 <https://github.com/agronholm/anyio/issues/1197>`_; PR by @tapetersen)
- Fixed ``CancelScope`` on the asyncio backend allowing a scope to be entered again
after it had been exited, instead of raising ``RuntimeError`` like the Trio backend
does. Reusing a cancelled scope silently cancelled the body of the second ``with``
block (`#1296 <https://github.com/agronholm/anyio/pull/1296>`_;
PR by @jaideeppyne)

**4.14.2**

Expand Down
5 changes: 4 additions & 1 deletion src/anyio/_backends/_asyncio.py
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,7 @@ class CancelScope(BaseCancelScope):
"_cancelled_caught",
"_child_scopes",
"_deadline",
"_has_been_entered",
"_host_task",
"_parent_scope",
"_pending_uncancellations",
Expand All @@ -410,6 +411,7 @@ def __init__(self, deadline: float = math.inf, shield: bool = False):
self._cancel_reason: str | None = None
self._cancelled_caught = False
self._active = False
self._has_been_entered = False
self._timeout_handle: asyncio.TimerHandle | None = None
self._cancel_handle: asyncio.Handle | None = None
self._tasks: set[asyncio.Task] = set()
Expand All @@ -420,11 +422,12 @@ def __init__(self, deadline: float = math.inf, shield: bool = False):
self._pending_uncancellations = None

def __enter__(self) -> Self:
if self._active:
if self._has_been_entered:
raise RuntimeError(
"Each CancelScope may only be used for a single 'with' block"
)

self._has_been_entered = True
self._host_task = host_task = cast(asyncio.Task, current_task())
self._tasks.add(host_task)
try:
Expand Down
36 changes: 36 additions & 0 deletions tests/test_taskgroups.py
Original file line number Diff line number Diff line change
Expand Up @@ -1604,6 +1604,42 @@ async def test_cancelscope_exit_before_enter() -> None:
pytest.raises(RuntimeError, scope.__exit__, None, None, None)


async def test_cancelscope_reuse() -> None:
"""
Test that a RuntimeError is raised if one tries to enter a cancel scope that has
already been exited.

"""
scope = CancelScope()
with scope:
pass

with pytest.raises(
RuntimeError,
match="Each CancelScope may only be used for a single 'with' block",
):
with scope:
pass


async def test_cancelscope_reuse_after_cancel() -> None:
"""
Test that reusing a cancelled cancel scope raises a RuntimeError instead of
silently cancelling the body of the second ``with`` block.

"""
scope = CancelScope()
with scope:
scope.cancel()

with pytest.raises(
RuntimeError,
match="Each CancelScope may only be used for a single 'with' block",
):
with scope:
await checkpoint()


@pytest.mark.parametrize(
"anyio_backend", asyncio_params
) # trio does not check for this yet
Expand Down
Loading