Skip to main content

Dependency injection without the boilerplate.

Project description

Asyncio Cancel Scope

PyPI - Version PyPI - Python Version License: MIT

A utility for cancelling asyncio task groups in the absence of one from the standard library.

Installation

pip install asyncio_cancel_scope

Usage

The cancel_scope function allows you to cleanly cancel all the tasks within a task group:

import asyncio
from asyncio_cancel_scope import cancel_scope

async def main():
    async with cancel_scope(asyncio.TaskGroup()) as (tg, cancel):
        tg.create_task(asyncio.sleep(1))
        tg.create_task(asyncio.sleep(2))
        tg.create_task(asyncio.sleep(3))
        tg.create_task(asyncio.sleep(4))
        cancel()  # cancels all tasks in the group and exits without an exception

asyncio.run(main())

Alternatives

Without this you'd need to manually cancel each task in the group, which can be cumbersome and error-prone:

import asyncio


async def main():
    tasks = []
    async with asyncio.TaskGroup() as tg:
        tasks.append(tg.create_task(asyncio.sleep(1)))
        tasks.append(tg.create_task(asyncio.sleep(2)))
        tasks.append(tg.create_task(asyncio.sleep(3)))
        tasks.append(tg.create_task(asyncio.sleep(4)))
        for task in tasks:
            task.cancel()  # manually cancel each task
            try:
                await task  # wait until the task is cancelled
            except asyncio.CancelledError:
                pass  # supress the cancellation exception

Under the Hood

Behind the scenes, cancel_scope creates a background task to run the task group. This makes it easy to cancel all the group's underlying tasks without needing to manually track them. The implementation looks roughly like this:

import asyncio
import contextlib


@contextlib.asynccontextmanager
async def cancel_scope(tg):
    did_enter = asyncio.Event()
    will_exit = asyncio.Event()
    did_exit = asyncio.Event()

    async def wrapper():
        try:
            async with tg:
                did_enter.set()
                await will_exit.wait()
        finally:
            did_exit.set()

    task = asyncio.create_task(wrapper())
    await did_enter.wait()  # ensure the task has entered the context manager

    try:
        yield tg, task.cancel
        will_exit.set()
        await did_exit.wait()
    except BaseException:
        if task.cancel():
            with contextlib.suppress(asyncio.CancelledError):
                await task
        raise

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

asyncio_cancel_scope-0.1.1.tar.gz (6.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

asyncio_cancel_scope-0.1.1-py3-none-any.whl (5.0 kB view details)

Uploaded Python 3

File details

Details for the file asyncio_cancel_scope-0.1.1.tar.gz.

File metadata

File hashes

Hashes for asyncio_cancel_scope-0.1.1.tar.gz
Algorithm Hash digest
SHA256 7238c7d7b27f483fd3f88b6d33bf05b3e714ae0eadb6bffbb018367a25fb306a
MD5 ae5761f21923363ad364133e2f454afe
BLAKE2b-256 7bd8b7a9d235f4b578ebe2cfb753e66a743e0661fb541d8d86936f7699d5bf24

See more details on using hashes here.

File details

Details for the file asyncio_cancel_scope-0.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for asyncio_cancel_scope-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 d0f15751e0e19d572a083f3122d7375367fae51d74f64fd4d54d242ab2b9392b
MD5 8ed8eff330298606f289eda2ed441d48
BLAKE2b-256 a849ac068b0ca5962d6752b026af8f8aac8f33f76144770084d0d87e4581686a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page