Skip to content

API reference

Utility classes and functions for AnyIO.

CancelledError

Bases: BaseException

The operation has been cancelled.

Event

An event object. Not thread-safe.

An event can be used to notify multiple tasks that some event has happened.

An Event object manages an internal flag that can be set to True with the set() method and reset to False with the clear() method. The wait() method blocks until the flag is set to True. The flag is set to False initially.

clear()

Clear (unset) the event.

Tasks awaiting on wait() will now block until the set() method is called again.

is_set()

Returns:

Type Description
bool

True if the event is set.

set()

Set the event.

All tasks waiting for event to be set will be immediately awakened.

wait() async

Wait until the event is set.

Returns:

Type Description
bool

If the event is set, return True immediately. Otherwise block until another task calls set().

Future

Bases: Generic[T]

A Future represents an eventual result of an asynchronous operation. Not thread-safe.

Future is an awaitable object. Coroutines can await on Future objects until they either have a result or an exception set, or until they are cancelled. A Future can be awaited multiple times and the result is same.

Typically Futures are used to enable low-level callback-based code to interoperate with high-level async/await code.

add_done_callback(callback)

Add a callback to be run when the Future is done.

The callback is called with the Future object as its only argument.

If the Future is already done when this method is called, the callback is scheduled immediately.

cancel(raise_exception=False)

Cancel the Future and schedule callbacks.

If the Future is already done or cancelled, return False. Otherwise, change the Future's state to cancelled, schedule the callbacks, and return True.

Parameters:

Name Type Description Default
raise_exception bool

Whether to raise a CancelledError.

False

Returns:

Type Description
bool

False if the Future is already done or cancelled, True otherwise.

cancelled()

Returns:

Type Description
bool

True if the Future was cancelled, False otherwise.

done()

A Future is done if it was cancelled or if it has a result or an exception set with set_result() or set_exception() calls.

Returns:

Type Description
bool

True if the Future is done.

exception()

The exception (or None if no exception was set) is returned only if the Future is done.

If the Future has been cancelled, this method raises a CancelledError exception.

If the Future isn’t done yet, this method raises an InvalidStateError exception.

Returns:

Type Description
BaseException | None

The exception that was set on this Future.

remove_done_callback(callback)

Remove callback from the callbacks list.

Returns:

Type Description
int

The number of callbacks removed, which is typically 1, unless a callback was added more than once.

result()

If the Future is done and has a result set by the set_result() method, the result value is returned.

If the Future is done and has an exception set by the set_exception() method, this method raises the exception.

If the Future has been cancelled, this method raises a CancelledError exception.

If the Future’s result isn’t yet available, this method raises an InvalidStateError exception.

Returns:

Type Description
T

The result of the Future.

set_exception(value)

Mark the Future as done and set an exception.

Raises:

Type Description
InvalidStateError

The Future is already done.

set_result(value)

Mark the Future as done and set its result.

Raises:

Type Description
InvalidStateError

The Future is already done.

wait() async

Wait for the Future to be done or cancelled.

Returns:

Type Description
T | None

The Furure's return value.

InvalidStateError

Bases: BaseException

Invalid internal state of Task or Future.

Can be raised in situations like setting a result value for a Future object that already has a result value set.

Monitor

result property

The result of the measurement (greater than 1). The closer to 1, the less saturated the event-loop is. The greater, the more saturated the event-loop is.

__init__(period=0.01)

Create a Monitor with a run() method that runs a task in the background and measures how saturated the event-loop is. This can also be used to detect (long) blocking calls in the event-loop.

The Monitor can be used as an async context manager, in which case it will automatically run, or by launching its run() method in the backgroup manually.

Parameters:

Name Type Description Default
period float

The period in seconds to make the measurement.

0.01

run() async

Run the Monitor. This has to be run in the background.

Queue

Bases: Generic[T]

maxsize property

Number of items allowed in the queue.

__init__(maxsize=0)

A first in, first out (FIFO) queue.

If maxsize is less than or equal to zero, the queue size is infinite. If it is an integer greater than 0, then await put() blocks when the queue reaches maxsize until an item is removed by get().

empty()

Returns:

Type Description
bool

True if the queue is empty, False otherwise.

full()

Returns:

Type Description
bool

True if there are maxsize items in the queue.

get() async

Remove and return an item from the queue. If queue is empty, wait until an item is available.

Returns:

Type Description
T

The item from the queue.

get_nowait()

Returns:

Type Description
T

An item if one is immediately available.

put(item) async

Put an item into the queue. If the queue is full, wait until a free slot is available before adding the item.

Parameters:

Name Type Description Default
item T

The item to put into the queue.

required

put_nowait(item)

Put an item into the queue without blocking.

Parameters:

Name Type Description Default
item T

The item to put into the queue.

required

qsize()

Returns:

Type Description
int

The number of items in the queue.

Task

Bases: Generic[T]

A Future-like object that runs a Python coroutine. Not thread-safe.

Tasks are used to run coroutines in event loops. If a coroutine awaits on a Future, the Task suspends the execution of the coroutine and waits for the completion of the Future. When the Future is done, the execution of the wrapped coroutine resumes.

Event loops use cooperative scheduling: an event loop runs one Task at a time. While a Task awaits for the completion of a Future, the event loop runs other Tasks, callbacks, or performs IO operations.

Use the high-level anyioutils.create_task() function to create Tasks. Manual instantiation of Tasks is discouraged.

To cancel a running Task use the cancel() method. Calling it will cause the Task to throw a CancelledError exception into the wrapped coroutine. If a coroutine is awaiting on a Future object during cancellation, the Future object will be cancelled.

cancelled() can be used to check if the Task was cancelled.

add_done_callback(callback)

Add a callback to be run when the Task is done.

This method should only be used in low-level callback-based code.

See the documentation of Future.add_done_callback() for more details.

cancel(raise_exception=False)

Request the Task to be cancelled.

cancelled()

Returns:

Type Description
bool

True if the Task is cancelled.

done()

A Task is done when the wrapped coroutine either returned a value, raised an exception, or the Task was cancelled.

Return

True if the Task is done.

exception()

If the wrapped coroutine raised an exception that exception is returned. If the wrapped coroutine returned normally this method returns None.

If the Task has been cancelled, this method raises a CancelledError exception.

If the Task isn't done yet, this method raises an InvalidStateError exception.

Returns:

Type Description
BaseException | None

The exception of the Task.

remove_done_callback(callback)

Remove callback from the callbacks list.

This method should only be used in low-level callback-based code.

See the documentation of Future.remove_done_callback() for more details.

result()

If the Task is done, the result of the wrapped coroutine is returned (or if the coroutine raised an exception, that exception is re-raised).

If the Task has been cancelled, this method raises a CancelledError exception.

If the Task's result is't yet available, this method raises an InvalidStateError exception.

Return

The result of the Task.

wait() async

Wait for the Task to be done or cancelled.

Returns:

Type Description
T | None

The return value of the coroutine, if not cancelled, otherwise None.

wait_started() async

Wait for the task to be started. The task must have been created with start_task(), not create_task.

Returns:

Type Description
Any

The started value.

TaskGroup

An asynchronous context manager holding a group of tasks. Tasks can be added to the group using create_task(). All tasks are awaited when the context manager exits, unless they have been created with background=True.

Tasks created down the call stack using create_task() or start_task() may not need to be passed a TaskGroup, since they could use this TaskGroup implicitly.

cancel_scope property

Returns:

Type Description
CancelScope

The TaskGroup's CancelScope.

create_task(coro, *, name=None, background=False)

Create a task in this task group.

Parameters:

Name Type Description Default
background bool

Whether to run the task in the background, in which case it will be cancelled when the task group exits.

False
name str | None

The task name.

None

Returns: The created Task.

create_task(coro, task_group=None, *, name=None, exception_handler=None)

Wrap the coro coroutine into a Task and schedule its execution.

Parameters:

Name Type Description Default
task_group TaskGroup | None

An optional TaskGroup (from AnyIO) to run the Task in. If not provided, a TaskGroup (from anyioutils) will be looked up the call stack and used if found.

None
exception_handler ExceptionHandler | None

An optional exception handler. When an exception occurs in the Task, the exception handler is called with the exception. The exception is considered to be handled if the exception handler returns True, otherwise the exception is raised.

None

Returns:

Type Description
Task[T]

The Task object.

start_guest_run(async_fn, *, run_sync_soon_threadsafe, done_callback, run_sync_soon_not_threadsafe=None, backend='asyncio')

See Trio's guest mode.

start_task(async_fn, task_group=None, *, name=None, exception_handler=None)

Create a coroutine from the async_fn async function, wrap it into a Task and schedule its execution.

The Task's wait() method will only return None, but its wait_started() method will return its started value.

Parameters:

Name Type Description Default
task_group TaskGroup | None

An optional TaskGroup (from AnyIO) to run the Task in. If not provided, a TaskGroup (from anyioutils) will be looked up the call stack and used, if found.

None
exception_handler ExceptionHandler | None

An optional exception handler. When an exception occurs in the Task, the exception handler is called with the exception. The exception is considered to be handled if the exception handler returns True, otherwise the exception is raised.

None

Returns:

Type Description
Task[None]

The Task object.

wait(aws, task_group=None, *, timeout=None, return_when=ALL_COMPLETED) async

Run Future and Task instances in the aws iterable concurrently and block until the condition specified by return_when.

return_when indicates when this function should return. It must be one of the following constants:

Constant Description
anyioutils.FIRST_COMPLETED The function will return when any future finishes or is cancelled.
anyioutils.FIRST_EXCEPTION The function will return when any future finishes by raising an exception. If no future raises an exception then it is equivalent to [ALL_COMPLETED.
anyioutils.ALL_COMPLETED The function will return when all futures finish or are cancelled.

Parameters:

Name Type Description Default
timeout float | int | None

If specified, can be used to control the maximum number of seconds to wait before returning. Note that this function does not raise TimeoutError. Futures or Tasks that aren't done when the timeout occurs are simply returned in the second set.

None
return_when Literal['ALL_COMPLETED', 'FIRST_COMPLETED', 'FIRST_EXCEPTION']

Indicates when this function should return. It must be one of the following constants:

ALL_COMPLETED

Returns:

Type Description
tuple[set[Task | Future], set[Task | Future]]

Two sets of Tasks/Futures: (done, pending).