Skip to main content

Task control for asyncio.

Project description

https://img.shields.io/pypi/v/quattro.svg https://github.com/Tinche/quattro/workflows/CI/badge.svg https://codecov.io/gh/Tinche/quattro/branch/main/graph/badge.svg?token=9IE6FHZV2K https://img.shields.io/badge/code%20style-black-000000.svg

quattro is an Apache 2 licensed library, written in Python, for task control in asyncio applications. quattro is influenced by structured concurrency concepts from the Trio framework.

quattro supports Python versions 3.9 - 3.11, including PyPy.

Installation

To install quattro, simply:

$ pip install quattro

Task Groups

quattro contains a TaskGroup implementation. TaskGroups are inspired by Trio nurseries.

from quattro import TaskGroup

async def my_handler():
    # We want to spawn some tasks, and ensure they are all handled before we return.
    async def task_1():
        ...

    async def task_2():
        ...

    async with TaskGroup() as tg:
        t1 = tg.create_task(task_1)
        t2 = tg.create_task(task_2)

    # The end of the `async with` block awaits the tasks, ensuring they are handled.

TaskGroups are essential building blocks for achieving the concept of structured concurrency. In simple terms, structured concurrency means your code does not leak tasks - when a coroutine finishes, all tasks spawned by that coroutine and all its children are also finished. (In fancy terms, the execution flow becomes a directed acyclic graph.)

Structured concurrency can be achieved by using TaskGroups instead of asyncio.create_task to start background tasks. TaskGroups essentially do two things:

  • when exiting from a TaskGroup async with block, the TaskGroup awaits all of its children, ensuring they are finished when it exits

  • when a TaskGroup child task raises an exception, all other children and the task inside the context manager are cancelled

The implementation has been borrowed from the EdgeDB project.

Cancel Scopes

quattro contains an independent, asyncio implementation of Trio CancelScopes. Due to fundamental differences between asyncio and Trio the actual runtime behavior isn’t exactly the same, but close.

from quattro import move_on_after

async def my_handler():
    with move_on_after(1.0) as cancel_scope:
        await long_query()

    # 1 second later, the function continues running

quattro contains the following helpers:

  • move_on_after

  • move_on_at

  • fail_after

  • fail_at

All helpers produce instances of quattro.CancelScope, which is largely similar to the Trio variant.

CancelScopes have the following attributes:

  • cancel() - a method through which the scope can be cancelled manually

  • deadline - read/write, an optional deadline for the scope, at which the scope will be cancelled

  • cancelled_caught - a readonly bool property, whether the scope finished via cancellation

quattro also supports retrieving the current effective deadline in a task using quattro.current_effective_deadline. The current effective deadline is a float value, with float('inf') standing in for no deadline.

Python versions 3.11 and higher contain similar helpers, asyncio.timeout and asyncio.timeout_at. The quattro fail_after and fail_at helpers are effectively equivalent to the asyncio timeouts, and pass the test suite for them.

The differences are:

  • The quattro versions are normal context managers (used with just with), asyncio versions are async context managers (using async with). Neither version needs to be async since nothing is awaited; quattro chooses to be non-async to signal there are no suspension points being hit, match Trio and be a little more readable.

  • quattro additionally contains the move_on_at and move_on_after helpers.

  • The quattro versions support getting the current effective deadline.

  • The quattro versions are available on all supported Python versions, not just 3.11+.

asyncio and Trio differences

fail_after and fail_at raise asyncio.Timeout instead of trio.Cancelled exceptions when they fail.

asyncio has edge-triggered cancellation semantics, while Trio has level-triggered cancellation semantics. The following example will behave differently in quattro and Trio:

with trio.move_on_after(TIMEOUT):
    conn = make_connection()
    try:
        await conn.send_hello_msg()
    finally:
        await conn.send_goodbye_msg()

In Trio, if the TIMEOUT expires while awaiting send_hello_msg(), send_goodbye_msg() will also be cancelled. In quattro, send_goodbye_msg() will run (and potentially block) anyway. This is a limitation of the underlying framework.

In quattro, cancellation scopes cannot be shielded.

Changelog

22.1.0 (UNRELEASED)

  • Restore TaskGroup copyright notice.

  • TaskGroups now raise ExceptionGroups (using the PyPI backport when necessary) on child errors.

  • Add support for Python 3.11, drop 3.8.

  • TaskGroups no longer have a name and the repr is slightly different, to harmonize with the Python 3.11 standard library implementation.

  • TaskGroups no longer swallow child exceptions when aborting, to harmonize with the Python 3.11 standard library implementation.

  • Switch to CalVer.

0.3.0 (2022-01-08)

  • Add py.typed to enable typing information.

  • Flesh out type annotations for TaskGroups.

0.2.0 (2021-12-27)

  • Add quattro.current_effective_deadline.

0.1.0 (2021-12-08)

  • Initial release, containing task groups and cancellation scopes.

Credits

The initial TaskGroup implementation has been taken from the EdgeDB project. The CancelScope implementation was heavily influenced by Trio, and inspired by the async_timeout package.

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

quattro-22.1.0.tar.gz (19.2 kB view details)

Uploaded Source

Built Distribution

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

quattro-22.1.0-py3-none-any.whl (12.4 kB view details)

Uploaded Python 3

File details

Details for the file quattro-22.1.0.tar.gz.

File metadata

  • Download URL: quattro-22.1.0.tar.gz
  • Upload date:
  • Size: 19.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.1 CPython/3.10.6

File hashes

Hashes for quattro-22.1.0.tar.gz
Algorithm Hash digest
SHA256 c74e7eff4a61e650852bb2a72991630cb5e4aad029c96501e8f62b42c2f3019d
MD5 e24cf5926517a1310c593a8223eb38ed
BLAKE2b-256 9d777ba3ba19fa6eaaec420cf6a503f2f68dc04866c39e5b3372f65e823d2ebb

See more details on using hashes here.

File details

Details for the file quattro-22.1.0-py3-none-any.whl.

File metadata

  • Download URL: quattro-22.1.0-py3-none-any.whl
  • Upload date:
  • Size: 12.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.1 CPython/3.10.6

File hashes

Hashes for quattro-22.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 5a2718be7df63a0127f6f82106b08e17e57e212f356d4ba9f0958b391dc1cbb9
MD5 4f69836a6dfbd29ad2fab9b94b51ea1d
BLAKE2b-256 85dc47d7c883c17a78a78a2ecbb318f9583f40e5c2410c04510f48bb339d6294

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