trio icon indicating copy to clipboard operation
trio copied to clipboard

use case for deriving from CancelScope

Open belm0 opened this issue 3 years ago • 0 comments

CancelScope is a useful starting point for extension, so I'm wondering if the Final guard could be removed.

trio-util has move_on_when(). Since it yields a CancelScope, shield and deadline can be used in addition to its ability to cancel when the given async function returns. But like shield and deadline, I'd like the possibility to change the wait function dynamically.

async with move_on_when(my_event.wait) as cancel_scope:
    cancel_scope.shield = True
    await do_something()
    cancel_scope.wait_fn = None  # disable cancel by my_event
    await do_other_things()

It's not possible to extend CancelScope this way due to the meta=Final subclassing guard.

alternatives to subclassing

  • parent the cancel scope in some some other thing - move_on_when() returns MoveOnWhenContext, which has wait_fn and (similar to nursery) cancel_scope fields.
  • wrap CancelScope - make a MoveOnWhenScope that has the same API as CancelScope, plus wait_fn.

belm0 avatar Jun 28 '22 05:06 belm0