From 5eb2b1ad9d0f6057fc2d57008778035c8d06744d Mon Sep 17 00:00:00 2001 From: tony1233200 Date: Thu, 19 Nov 2026 19:44:12 +0000 Subject: [PATCH] Let fail_at/fail_after scopes be inspected before entering --- newsfragments/3090.feature.rst | 5 +++ src/trio/_tests/test_timeouts.py | 15 +++++-- src/trio/_timeouts.py | 68 +++++++++++++++++++++++++------- 3 files changed, 69 insertions(+), 19 deletions(-) create mode 100644 newsfragments/3090.feature.rst diff --git a/newsfragments/3090.feature.rst b/newsfragments/3090.feature.rst new file mode 100644 index 0000000000..e25968bd4a --- /dev/null +++ b/newsfragments/3090.feature.rst @@ -0,0 +1,5 @@ +``trio.fail_at`` and ``trio.fail_after`` now return an object wrapping the +underlying `trio.CancelScope`, so its attributes (such as ``deadline`` and +``relative_deadline``) can be inspected and modified before the scope is +entered. Entering the object enters the wrapped scope and returns it, and +exiting still raises `trio.TooSlowError` if the scope caught a cancellation. diff --git a/src/trio/_tests/test_timeouts.py b/src/trio/_tests/test_timeouts.py index fa974fcf21..2663452892 100644 --- a/src/trio/_tests/test_timeouts.py +++ b/src/trio/_tests/test_timeouts.py @@ -268,9 +268,16 @@ async def test_invalid_access_unentered() -> None: cs.relative_deadline = 7 -@pytest.mark.xfail(reason="not implemented") -async def test_fail_access_before_entering() -> None: # pragma: no cover +async def test_fail_access_before_entering() -> None: my_fail_at = fail_at(5) - assert my_fail_at.deadline # type: ignore[attr-defined] + assert my_fail_at.deadline == 5 my_fail_after = fail_after(5) - assert my_fail_after.relative_deadline # type: ignore[attr-defined] + assert my_fail_after.relative_deadline == 5 + + # Attribute writes go to the wrapped scope as well, and take effect + # when the scope is entered. + my_fail_after.relative_deadline = 100 + assert my_fail_after.relative_deadline == 100 + with my_fail_after as scope: + assert scope.deadline > _core.current_time() + assert not my_fail_after.cancelled_caught diff --git a/src/trio/_timeouts.py b/src/trio/_timeouts.py index d95cbe4cfc..c35a53fc76 100644 --- a/src/trio/_timeouts.py +++ b/src/trio/_timeouts.py @@ -2,13 +2,12 @@ import math import sys -from contextlib import contextmanager from typing import TYPE_CHECKING, NoReturn import trio if TYPE_CHECKING: - from collections.abc import Generator + from types import TracebackType def move_on_at(deadline: float, *, shield: bool = False) -> trio.CancelScope: @@ -118,12 +117,56 @@ class TooSlowError(Exception): """ -@contextmanager +class _FailScope: + """The object returned by :func:`fail_at` and :func:`fail_after`. + + Wraps the underlying `~trio.CancelScope` so that its attributes (such + as ``deadline`` and ``relative_deadline``) can be inspected and + modified before the scope is entered, which a plain context manager + does not allow. Entering it enters the wrapped scope and returns the + scope itself; exiting raises `TooSlowError` if the scope caught a + cancellation, exactly as the previous generator-based implementation + did. All other attribute access is passed through to the wrapped + scope. + """ + + def __init__(self, scope: trio.CancelScope) -> None: + object.__setattr__(self, "_scope", scope) + + def __enter__(self) -> trio.CancelScope: + return self._scope.__enter__() + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> bool: + suppressed = self._scope.__exit__(exc_type, exc_value, traceback) + if self._scope.cancelled_caught and (exc_type is None or suppressed): + raise TooSlowError + return suppressed + + def __getattr__(self, name: str) -> object: + if name == "_scope": + raise AttributeError(name) + return getattr(self._scope, name) + + def __setattr__(self, name: str, value: object) -> None: + if name == "_scope": + object.__setattr__(self, name, value) + else: + setattr(self._scope, name, value) + + def __repr__(self) -> str: + return f"" + + def fail_at( deadline: float, *, shield: bool = False, -) -> Generator[trio.CancelScope, None, None]: +) -> _FailScope: """Creates a cancel scope with the given deadline, and raises an error if it is actually cancelled. @@ -146,18 +189,14 @@ def fail_at( ValueError: if deadline is NaN. """ - with move_on_at(deadline, shield=shield) as scope: - yield scope - if scope.cancelled_caught: - raise TooSlowError + return _FailScope(move_on_at(deadline, shield=shield)) -@contextmanager def fail_after( seconds: float, *, shield: bool = False, -) -> Generator[trio.CancelScope, None, None]: +) -> _FailScope: """Creates a cancel scope with the given timeout, and raises an error if it is actually cancelled. @@ -181,10 +220,7 @@ def fail_after( ValueError: if *seconds* is less than zero or NaN. """ - with move_on_after(seconds, shield=shield) as scope: - yield scope - if scope.cancelled_caught: - raise TooSlowError + return _FailScope(move_on_after(seconds, shield=shield)) # Users don't need to know that fail_at & fail_after wraps move_on_at and move_on_after @@ -194,4 +230,6 @@ def fail_after( import inspect for c in (fail_at, fail_after): - c.__signature__ = inspect.Signature.from_callable(c).replace(return_annotation=trio.CancelScope) # type: ignore[union-attr] + c.__signature__ = inspect.Signature.from_callable(c).replace( + return_annotation=trio.CancelScope + ) # type: ignore[union-attr]