API Reference¶

Cancelled¶

Exception class that represents cancellation. See Dealing with Cancellation.

Warning

Actually, this is not an exception class but a tuple of exception classes for now. But that’s an implementation detail, and it might become an actual class in the future; therefore, your code must be compatible in both cases.

class Event¶
async def async_fn(e):
    args, kwargs = await e.wait()
    assert args == (2, )
    assert kwargs == {'crow': 'raven', }

    args, kwargs = await e.wait()
    assert args == (3, )
    assert kwargs == {'toad': 'frog', }

e = Event()
e.fire(1, crocodile='alligator')
task = start(async_fn(e))
e.fire(2, crow='raven')
e.fire(3, toad='frog')
assert task.finished

Warning

This differs from asyncio.Event, as it does not have a “set” state. await e.wait() will always block the caller until someone else calls fire() after the wait has started. Use StatefulEvent if you want something closer to asyncio.Event.

Changed in version 0.7.0: This is now completely different from the previous version’s.

Changed in version 0.10.0: This is now weak-referenceable.

fire(*args, **kwargs)¶
wait() Awaitable[tuple[tuple, dict]]¶

Waits for the event to be fired.

class ExclusiveEvent¶

Similar to Event, but this version does not allow multiple tasks to wait() simultaneously. As a result, it operates faster.

Changed in version 0.10.1: This is now weak-referenceable.

fire(*args, **kwargs)¶
wait() Awaitable[tuple[tuple, dict]]¶
exception InvalidStateError¶

Operation is not allowed in the current state.

class Nursery¶

A task supervisor similar to trio.Nursery. Do not instantiate this class directly; use open_nursery().

Nursery closes when any of the following occurs:

  • close() is called.

  • Any child task raises an exception.

  • Any child task with close_on_finish=True completes.

  • All child tasks complete.

  • Only daemon child tasks remain running.

When it closes, the nursery cancels any remaining child tasks.

close()¶

Cancels all child tasks in the nursery as soon as possible. After this method is called, no new child tasks can be started.

property closed: bool¶
start(aw: Awaitable | Task, /, *, daemon=False, close_on_finish=False) Task¶

Immediately start a task under the supervision of the nursery.

Parameters:
  • daemon – This acts like the one in the threading module. When only daemon tasks are left, they get cancelled, and the nursery closes.

  • close_on_finish – When any of the tasks with this set to True completes, the nursery closes.

Changed in version 0.11.0: The daemon parameter was replaced by role.

Changed in version 0.11.1: The change made in 0.11.0 was reverted, and the close_on_finish parameter was added.

class StatefulEvent¶

The closest thing to asyncio.Event in this library.

StatefulEvent

asyncio.Event

.fire()

.set()

.wait()

.wait()

.clear()

.clear()

.is_fired

.is_set()

.params

–

async def async_fn(e):
    args, kwargs = await e.wait()
    assert args == (1, )
    assert kwargs == {'crow': 'raven', }

e = StatefulEvent()
task = start(async_fn(e))
assert not task.finished
e.fire(1, crow='raven')
assert task.finished

Added in version 0.7.2.

Changed in version 0.9.0: The .refire() and .fire_or_refire() methods have been removed.

Changed in version 0.10.0: This is now weak-referenceable.

clear()¶

Sets the event to a non-fired state.

fire(*args, **kwargs)¶

Fires the event if it’s not in a fired state.

property is_fired: bool¶
property params: tuple¶

The parameters passed to the last fire. Raises InvalidStateError if the event is not in a “fired” state. This is a convenient way to access the parameters from synchronous context.

e = StatefulEvent()

e.fire(1, crow='raven')
args, kwargs = e.params
assert args == (1, )
assert kwargs == {'crow': 'raven', }

e.clear()
e.fire(2, parasol='umbrella')
args, kwargs = e.params
assert args == (2, )
assert kwargs == {'parasol': 'umbrella', }
wait() Awaitable[tuple[tuple, dict]]¶
StatelessEvent¶

An alias of Event.

Added in version 0.7.2.

class Task(aw: Awaitable, /)¶
cancel()¶

Cancel the task as soon as possible.

property cancelled: bool¶

Whether the task has been cancelled.

close()¶

An alias of cancel().

property finished: bool¶

Whether the task has completed execution.

property result: Any¶

Result of the task. If the task is not finished, InvalidStateError will be raised.

property root_coro: Coroutine¶

The starting point of the coroutine chain for the task.

property state: TaskState¶

The current state of the task.

class TaskState¶

Enum class that represents the Task state.

CANCELLED¶

The execution has been cancelled. The cause of the cancellation is either an explicit or implicit call to Task.cancel() or an unhandled exception.

CREATED¶

Waiting to start execution.

FINISHED¶

The execution has been completed.

STARTED¶

Currently running or suspended.

current_task() Awaitable[Task]¶

Returns the Task instance corresponding to the caller.

task = await current_task()
dummy_task = <asyncgui.Task object>¶

An already closed task. This can be utilized to prevent the need for the common null validation mentioned below.

Before:

class MyClass:
    def __init__(self):
        self._task = None

    def restart(self):
        if self._task is not None:
            self._task.cancel()
        self._task = asyncgui.start(self.main())

    async def main(self):
        ...

After:

class MyClass:
    def __init__(self):
        self._task = asyncgui.dummy_task

    def restart(self):
        self._task.cancel()
        self._task = asyncgui.start(self.main())

    async def main(self):
        ...
move_on_when(aw: Awaitable | Task) AbstractAsyncContextManager[Task]¶

Returns an async context manager that runs the given task and the code inside the with-block concurrently, then waits for either one to complete. As soon as that happens, the other will be cancelled if it is still running.

This is equivalent to trio_util.move_on_when().

async with move_on_when(async_fn()) as task:
    ...
if task.finished:
    print(f"async_fn completed with a return value of {task.result}.")
else:
    print(f"async_fn was cancelled.")

You can replicate the same behavior with open_nursery() as follows:

async with open_nursery() as nursery:
    task = nursery.start(async_fn(), daemon=True, close_on_finish=True)
    ...
open_nursery() AbstractAsyncContextManager[Nursery]¶

An equivalent of trio.open_nursery().

async with open_nursery() as nursery:
    nursery.start(async_fn1())
    nursery.start(async_fn2(), daemon=True)
run_as_daemon(aw: Awaitable | Task) AbstractAsyncContextManager[Task]¶

Returns an async context manager that runs the given task and the code inside the with-block concurrently, then waits for the with-block to complete. As soon as that happens, the task will be cancelled if it is still running.

This is equivalent to trio_util.run_and_cancelling().

async with run_as_daemon(async_fn()) as task:
    ...
if task.finished:
    print(f"async_fn completed with a return value of {task.result}.")
else:
    print(f"async_fn was cancelled.")

You can replicate the same behavior with open_nursery() as follows:

async with open_nursery() as nursery:
    task = nursery.start(async_fn(), daemon=True)
    ...
sleep_forever()¶
await sleep_forever()
start(aw: Awaitable | Task, /) Task¶

Immediately start a Task.

async def async_func():
    ...

task = start(async_func())

Warning

Tasks started with this function are root tasks. You must ensure they aren’t garbage-collected while still running —for example, by explicitly calling Task.cancel() before the program exits.

async wait_all(*aws: Iterable[Awaitable | Task]) Awaitable[list[Task]]¶

Runs multiple tasks concurrently, then waits for all of them to either complete or be cancelled.

tasks = await wait_any(async_fn0(), async_fn1(), async_fn2())
for i, task in enumerate(tasks):
    if task.finished:
        print(f"async_fn{i} completed with a return value of {task.result}.")
    else:
        print(f"async_fn{i} was cancelled.")
async wait_any(*aws: Iterable[Awaitable | Task]) Awaitable[list[Task]]¶

Runs multiple tasks concurrently, then waits until either one completes or all are cancelled. As soon as one completes, the others will be cancelled.

tasks = await wait_any(async_fn0(), async_fn1(), async_fn2())
for i, task in enumerate(tasks):
    if task.finished:
        print(f"async_fn{i} completed with a return value of {task.result}.")
    else:
        print(f"async_fn{i} was cancelled.")