Dependency injection without the boilerplate.
Project description
Asyncio Cancel Scope
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 patches the TaskGroup to capture the tasks created
within it. When the cancel callback is called, it cancels all those tasks.
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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file asyncio_cancel_scope-0.2.0.tar.gz.
File metadata
- Download URL: asyncio_cancel_scope-0.2.0.tar.gz
- Upload date:
- Size: 6.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.7.17
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ec91c29fb7c207afbbce11d12beca347eca5ea89960dc85f251976e1bf3a3da7
|
|
| MD5 |
cde97accb7c73f2384c94c80700b473f
|
|
| BLAKE2b-256 |
61b8b1b25158f40b6f32818913db74bb08eaca287fcb3bbe28346f2d8148ac4e
|
File details
Details for the file asyncio_cancel_scope-0.2.0-py3-none-any.whl.
File metadata
- Download URL: asyncio_cancel_scope-0.2.0-py3-none-any.whl
- Upload date:
- Size: 4.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.7.17
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
403c32887b086983913c5035c6b68f9a95c698f72b9b14d24d3ffc3ba0beecde
|
|
| MD5 |
8d6778bce786da8c940765a5a782c65b
|
|
| BLAKE2b-256 |
dc7a38475b46319e5266d996d1b159919ce25b8692870991f36ba0bca272ee65
|