[Pitch] Structured Task Cancellation Tokens

We should be able to do a bit better within the context of structured concurrency. Trio for instance uses the concept of cancellation scopes, which run the code inside a scope under certain cancellation conditions, such as a timeout:

This avoids the need to explicitly create and pass around cancellation tokens, since the cancellation state is part of the ambient environment. The design you've proposed using task-local storage to track the cancellation token can do this too; however, we could introduce a variety of cancellation-scope-introducing APIs that each have their own token and reason value(s) to propagate to users. If each scope provides its own token, that could address the concerns about extensibility in this thread, without requiring all tokens and reasons to conform to some centralized protocol.

9 Likes