API reference

Event loop

anyio.run(func, *args, backend='asyncio', backend_options=None)

Run the given coroutine function in an asynchronous event loop.

The current thread must not be already running an event loop.

Parameters
  • func (Callable[…, Coroutine[Any, Any, +T_Retval]]) – a coroutine function

  • args – positional arguments to func

  • backend (str) – name of the asynchronous event loop implementation – one of asyncio, curio and trio

  • backend_options (Optional[Dict[str, Any]]) – keyword arguments to call the backend run() implementation with

Return type

+T_Retval

Returns

the return value of the coroutine function

Raises
  • RuntimeError – if an asynchronous event loop is already running in this thread

  • LookupError – if the named backend is not found

Miscellaneous

anyio.finalize(resource)

Return a context manager that automatically closes an asynchronous resource on exit.

Parameters

resource (~T_Agen) – an asynchronous generator or other resource with an aclose() method

Return type

Asynccontextmanager[~T_Agen]

Returns

an asynchronous context manager that yields the given object

coroutine anyio.sleep(delay)

Pause the current task for the specified duration.

Parameters

delay (float) – the duration, in seconds

Return type

Coroutine[Any, Any, None]

anyio.get_cancelled_exc_class()

Return the current async library’s cancellation exception class.

Return type

Type[BaseException]

Timeouts and cancellation

anyio.open_cancel_scope(*, shield=False)

Open a cancel scope.

Parameters

shield (bool) – True to shield the cancel scope from external cancellation

Return type

CancelScope

Returns

a cancel scope

anyio.move_on_after(delay, *, shield=False)

Create an async context manager which is exited if it does not complete within the given time.

Parameters
  • delay (Optional[float]) – maximum allowed time (in seconds) before exiting the context block, or None to disable the timeout

  • shield (bool) – True to shield the cancel scope from external cancellation

Return type

Asynccontextmanager[CancelScope]

Returns

an asynchronous context manager that yields a cancel scope

anyio.fail_after(delay, *, shield=False)

Create an async context manager which raises an exception if does not finish in time.

Parameters
  • delay (Optional[float]) – maximum allowed time (in seconds) before raising the exception, or None to disable the timeout

  • shield (bool) – True to shield the cancel scope from external cancellation

Return type

Asynccontextmanager[CancelScope]

Returns

an asynchronous context manager that yields a cancel scope

Raises

TimeoutError – if the block does not complete within the allotted time

coroutine anyio.current_effective_deadline()

Return the nearest deadline among all the cancel scopes effective for the current task.

Returns

a clock value from the event loop’s internal clock (float('inf') if there is no deadline in effect)

Return type

float

coroutine anyio.current_time()

Return the current value of the event loop’s internal clock.

:return the clock value (seconds) :rtype: float

class anyio.abc.CancelScope
abstract property cancel_called

True if cancel() has been called.

Return type

bool

abstract property deadline

The time (clock value) when this scope is cancelled automatically.

Will be float('inf')` if no timeout has been set.

Return type

float

abstract property shield

True if this scope is shielded from external cancellation.

While a scope is shielded, it will not receive cancellations from outside.

Return type

bool

Task groups

anyio.create_task_group()

Create a task group.

Return type

TaskGroup

Returns

a task group

class anyio.abc.TaskGroup

Groups several asynchronous tasks together.

Variables

cancel_scope (CancelScope) – the cancel scope inherited by all child tasks

Threads

coroutine anyio.run_in_thread(func, *args)

Start a thread that calls the given function with the given arguments.

Parameters
  • func (Callable[…, +T_Retval]) – a callable

  • args – positional arguments for the callable

Return type

Awaitable[+T_Retval]

Returns

an awaitable that yields the return value of the function.

anyio.run_async_from_thread(func, *args)

Call a coroutine function from a worker thread.

Parameters
  • func (Callable[…, Coroutine[Any, Any, +T_Retval]]) – a coroutine function

  • args – positional arguments for the callable

Return type

+T_Retval

Returns

the return value of the coroutine function

Async file I/O

coroutine anyio.aopen(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Open a file asynchronously.

The arguments are exactly the same as for the builtin open().

Returns

an asynchronous file object

Return type

AsyncFile

class anyio.abc.AsyncFile

An asynchronous file object.

This class wraps a standard file object and provides async friendly versions of the following blocking methods (where available on the original file object):

  • read

  • read1

  • readline

  • readlines

  • readinto

  • readinto1

  • write

  • writelines

  • truncate

  • seek

  • tell

  • flush

  • close

All other methods are directly passed through.

This class supports the asynchronous context manager protocol which closes the underlying file at the end of the context block.

This class also supports asynchronous iteration:

async with await aopen(...) as f:
    async for line in f:
        print(line)

Sockets and networking

coroutine anyio.wait_socket_readable(sock)

Wait until the given socket has data to be read.

Parameters

sock (socket) – a socket object

Raises
  • anyio.exceptions.ClosedResourceError – if the socket was closed while waiting for the socket to become readable

  • anyio.exceptions.ResourceBusyError – if another task is already waiting for the socket to become readable

Return type

Awaitable[None]

coroutine anyio.wait_socket_writable(sock)

Wait until the given socket can be written to.

Parameters

sock (socket) – a socket object

Raises
  • anyio.exceptions.ClosedResourceError – if the socket was closed while waiting for the socket to become writable

  • anyio.exceptions.ResourceBusyError – if another task is already waiting for the socket to become writable

Return type

Awaitable[None]

coroutine anyio.notify_socket_close(sock)

Notify any relevant tasks that you are about to close a socket.

This will cause ClosedResourceError to be raised on any task waiting for the socket to become readable or writable.

Parameters

sock (socket) – the socket to be closed after this

Return type

Awaitable[None]

class anyio.abc.Stream
abstract property buffered_data

Return the data currently in the read buffer.

Return type

bytes

abstract receive_chunks(max_size)

Return an async iterable which yields chunks of bytes as soon as they are received.

The generator will yield new chunks until the stream is closed.

Parameters

max_size (int) – maximum number of bytes to return in one iteration

Return type

Asynciterable[bytes]

Returns

an async iterable yielding bytes

Raises

ssl.SSLEOFError – if tls_standard_compatible was set to True in a TLS stream and the peer prematurely closed the connection

abstract receive_delimited_chunks(delimiter, max_chunk_size)

Return an async iterable which yields chunks of bytes as soon as they are received.

The generator will yield new chunks until the stream is closed.

Parameters
  • delimiter (bytes) – the marker to look for in the stream

  • max_chunk_size (int) – maximum number of bytes that will be read for each chunk before raising DelimiterNotFound

Return type

Asynciterable[bytes]

Returns

an async iterable yielding bytes

Raises
  • anyio.exceptions.IncompleteRead – if the stream was closed before the delimiter was found

  • anyio.exceptions.DelimiterNotFound – if the delimiter is not found within the bytes read up to the maximum allowed

  • ssl.SSLEOFError – if tls_standard_compatible was set to True in a TLS stream and the peer prematurely closed the connection

class anyio.abc.SocketStream

Bases: anyio.abc.Stream

abstract property alpn_protocol

The ALPN protocol selected during the TLS handshake.

Return type

Optional[str]

Returns

The selected ALPN protocol, or None if no ALPN protocol was selected

Raises

anyio.exceptions.TLSRequired – if a TLS handshake has not been done

abstract property cipher

The cipher selected in the TLS handshake.

See ssl.SSLSocket.cipher() for more information.

Return type

Tuple[str, str, int]

Returns

a 3-tuple of (cipher name, TLS version which defined it, number of bits)

Raises

anyio.exceptions.TLSRequired – if a TLS handshake has not been done

abstract get_channel_binding(cb_type='tls-unique')

Get the channel binding data for the current connection.

See ssl.SSLSocket.get_channel_binding() for more information.

Parameters

cb_type (str) – type of the channel binding to get

Return type

bytes

Returns

the channel binding data

Raises

anyio.exceptions.TLSRequired – if a TLS handshake has not been done

abstract getpeercert(binary_form=False)

Get the certificate for the peer on the other end of the connection.

See ssl.SSLSocket.getpeercert() for more information.

Parameters

binary_form (bool) – False to return the certificate as a dict, True to return it as bytes

Return type

Union[Dict[str, Union[str, tuple]], bytes, None]

Returns

the peer’s certificate, or None if there is not certificate for the peer

Raises

anyio.exceptions.TLSRequired – if a TLS handshake has not been done

abstract getsockopt(level, optname, *args)

Get a socket option from the underlying socket.

Returns

the return value of getsockopt()

abstract property server_hostname

The server host name.

Return type

Optional[str]

Returns

the server host name, or None if this is the server side of the connection

Raises

anyio.exceptions.TLSRequired – if a TLS handshake has not been done

abstract property server_side

True if this is the server side of the connection, False if this is the client.

Return type

bool

Returns

True if this is the server side, False if this is the client side

Raises

anyio.exceptions.TLSRequired – if a TLS handshake has not been done

abstract setsockopt(level, optname, value, *args)

Set a socket option.

This calls setsockopt() on the underlying socket.

Return type

None

abstract property shared_ciphers

The list of ciphers supported by both parties in the TLS handshake.

See ssl.SSLSocket.shared_ciphers() for more information.

Return type

List[Tuple[str, str, int]]

Returns

a list of 3-tuples (cipher name, TLS version which defined it, number of bits)

Raises

anyio.exceptions.TLSRequired – if a TLS handshake has not been done

abstract property tls_version

The TLS version negotiated during the TLS handshake.

See ssl.SSLSocket.version() for more information.

Return type

Optional[str]

Returns

the TLS version string (e.g. “TLSv1.3”), or None if the underlying socket is not using TLS

class anyio.abc.SocketStreamServer
abstract accept_connections()

Return an async iterable yielding streams from accepted incoming connections.

Return type

Asynciterable[SocketStream]

Returns

an async context manager

abstract property address

Return the bound address of the underlying socket.

Return type

Union[Tuple[str, int], Tuple[str, int, int, int], str]

abstract getsockopt(level, optname, *args)

Get a socket option from the underlying socket.

Returns

the return value of getsockopt()

abstract property port

The currently bound port of the underlying TCP socket.

Equivalent to server.address[1]. :raises ValueError: if the socket is not a TCP socket

Return type

int

abstract setsockopt(level, optname, value, *args)

Set a socket option.

This calls setsockopt() on the underlying socket.

Return type

None

class anyio.abc.UDPSocket
abstract property address

Return the bound address of the underlying socket.

Return type

Union[Tuple[str, int], Tuple[str, int, int, int]]

abstract getsockopt(level, optname, *args)

Get a socket option from the underlying socket.

Returns

the return value of getsockopt()

abstract property port

Return the currently bound port of the underlying socket.

Equivalent to socket.address[1].

Return type

int

abstract receive_packets(max_size)

Return an async iterable which yields packets read from the socket.

The iterable exits if the socket is closed.

Return type

Asynciterable[Tuple[bytes, str]]

Returns

an async iterable yielding (bytes, source address) tuples

abstract setsockopt(level, optname, value, *args)

Set a socket option.

This calls setsockopt() on the underlying socket.

Return type

None

Synchronization

anyio.create_semaphore(value)

Create an asynchronous semaphore.

Parameters

value (int) – the semaphore’s initial value

Return type

Semaphore

Returns

a semaphore object

anyio.create_lock()

Create an asynchronous lock.

Return type

Lock

Returns

a lock object

anyio.create_event()

Create an asynchronous event object.

Return type

Event

Returns

an event object

anyio.create_condition(lock=None)

Create an asynchronous condition.

Parameters

lock (Optional[Lock]) – the lock to base the condition object on

Return type

Condition

Returns

a condition object

anyio.create_queue(capacity)

Create an asynchronous queue.

Parameters

capacity (int) – maximum number of items the queue will be able to store

Return type

Queue

Returns

a queue object

class anyio.abc.Semaphore
abstract property value

The current value of the semaphore.

Return type

int

class anyio.abc.Lock
abstract locked()

Return True if the lock is currently held.

Return type

bool

class anyio.abc.Event
abstract clear()

Clear the flag, so that listeners can receive another notification.

Return type

None

abstract is_set()

Return True if the flag is set, False if not.

Return type

None

class anyio.abc.Condition
abstract locked()

Return True if the lock is set.

Return type

bool

class anyio.abc.Queue
abstract empty()

Return True if the queue is not holding any items.

Return type

bool

abstract full()

Return True if the queue is holding the maximum number of items.

Return type

bool

abstract qsize()

Return the number of items the queue is currently holding.

Return type

int

Operating system signals

coroutine anyio.receive_signals(*signals)

Start receiving operating system signals.

Parameters

signals (int) – signals to receive (e.g. signal.SIGINT)

Return type

Asynccontextmanager[Asynciterator[int]]

Returns

an asynchronous context manager for an asynchronous iterator which yields signal numbers

Warning

Windows does not support signals natively so it is best to avoid relying on this in cross-platform applications.

Testing and debugging

class anyio.TaskInfo(id, parent_id, name, coro)

Represents an asynchronous task.

Variables
  • id (int) – the unique identifier of the task

  • parent_id (Optional[int]) – the identifier of the parent task, if any

  • name (str) – the description of the task (if any)

  • coro (Coroutine) – the coroutine object of the task