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.2.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.2-py3-none-any.whl (5.0 kB view details)

Uploaded Python 3

File details

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

File metadata

File hashes

Hashes for asyncio_cancel_scope-0.1.2.tar.gz
Algorithm Hash digest
SHA256 13dd5d449d6df9a8c53698b78a5bee28535a5a217d9f2174f01fec099ccec09a
MD5 282971921d418ed7c29d59f401744adb
BLAKE2b-256 a358166b185c9a7594208fee6a2bcb03e8484add9cec96397c2eae5c945bac0a

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for asyncio_cancel_scope-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 a9a4f4b456532e7a41f1a8798cd9ebc6aa4fc45052e4729e8635b7358cb88261
MD5 840bef39425c383db03e7db53f5677fc
BLAKE2b-256 c88577111f04033a01d9489a983caeb5dbd3c248dcca36c9da2c3802621563ae

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