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

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

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

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 async cancel()

Cancel this scope immediately.

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

abstract async spawn(func, *args, name=None)

Launch a new task in this task group.

Parameters
  • func (Callable[…, Coroutine[+T_co, -T_contra, +V_co]]) – a coroutine function

  • args – positional arguments to call the function with

  • name – name of the task, for the purposes of introspection and debugging

Return type

None

Threads

anyio.run_in_thread(func, *args, limiter=None)

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

  • limiter (Optional[CapacityLimiter]) – capacity limiter to use to limit the total amount of threads running (if omitted, the default limiter is used)

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

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

async anyio.connect_tcp(address, port, *, ssl_context=None, autostart_tls=False, bind_host=None, bind_port=None, tls_standard_compatible=True)

Connect to a host using the TCP protocol.

Parameters
  • address (Union[str, IPv4Address, IPv6Address]) – the IP address or host name to connect to

  • port (int) – port on the target host to connect to

  • ssl_context (Optional[SSLContext]) – default SSL context to use for TLS handshakes

  • autostart_tls (bool) – True to do a TLS handshake on connect

  • bind_host (Union[str, IPv4Address, IPv6Address, None]) – the interface address or name to bind the socket to before connecting

  • bind_port (Optional[int]) – the port to bind the socket to before connecting

  • tls_standard_compatible (bool) – If True, performs the TLS shutdown handshake before closing the stream and requires that the server does this as well. Otherwise, SSLEOFError may be raised during reads from the stream. Some protocols, such as HTTP, require this option to be False. See wrap_socket() for details.

Return type

SocketStream

Returns

a socket stream object

async anyio.connect_unix(path)

Connect to the given UNIX socket.

Not available on Windows.

Parameters

path (Union[str, PathLike]) – path to the socket

Return type

SocketStream

Returns

a socket stream object

async anyio.create_tcp_server(port=0, interface=None, ssl_context=None, autostart_tls=True, tls_standard_compatible=True)

Start a TCP socket server.

Parameters
  • port (int) – port number to listen on

  • interface (Union[str, IPv4Address, IPv6Address, None]) – IP address of the interface to listen on. If omitted, listen on all IPv4 and IPv6 interfaces. To listen on all interfaces on a specific address family, use 0.0.0.0 for IPv4 or :: for IPv6.

  • ssl_context (Optional[SSLContext]) – an SSL context object for TLS negotiation

  • autostart_tls (bool) – automatically do the TLS handshake on new connections if ssl_context has been provided

  • tls_standard_compatible (bool) – If True, performs the TLS shutdown handshake before closing a connected stream and requires that the client does this as well. Otherwise, SSLEOFError may be raised during reads from a client stream. Some protocols, such as HTTP, require this option to be False. See wrap_socket() for details.

Return type

SocketStreamServer

Returns

a server object

async anyio.create_unix_server(path, *, mode=None)

Start a UNIX socket server.

Not available on Windows.

Parameters
Return type

SocketStreamServer

Returns

a server object

async anyio.create_udp_socket(*, interface=None, port=None, target_host=None, target_port=None)

Create a UDP socket.

If port has been given, the socket will be bound to this port on the local machine, making this socket suitable for providing UDP based services.

Parameters
Return type

UDPSocket

Returns

a UDP socket

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]

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]

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 async close()

Close the stream.

Return type

None

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

abstract async receive_exactly(nbytes)

Read exactly the given amount of bytes from the stream.

Parameters

nbytes (int) – the number of bytes to read

Return type

bytes

Returns

the bytes read

Raises
  • anyio.exceptions.IncompleteRead – if the stream was closed before the requested amount of bytes could be read from the stream

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

abstract async receive_some(max_bytes)

Reads up to the given amount of bytes from the stream.

Parameters

max_bytes (int) – maximum number of bytes to read

Return type

bytes

Returns

the bytes read

Raises

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

abstract async receive_until(delimiter, max_bytes)

Read from the stream until the delimiter is found or max_bytes have been read.

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

  • max_bytes (int) – maximum number of bytes that will be read before raising DelimiterNotFound

Return type

bytes

Returns

the bytes read, including the delimiter

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

abstract async send_all(data)

Send all of the given data to the other end.

Parameters

data (bytes) – the bytes to send

Return type

None

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 async start_tls(context=None)

Start the TLS handshake.

If the handshake fails, the stream will be closed.

Parameters

context (Optional[SSLContext]) – an explicit SSL context to use for the handshake

Return type

None

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 async accept()

Accept an incoming connection.

Return type

SocketStream

Returns

the socket stream for the accepted connection

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 async close()

Close the underlying socket.

Return type

None

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 async close()

Close the underlying socket.

Return type

None

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 async receive(max_bytes)

Receive a datagram.

No more than max_bytes of the received datagram will be returned, even if the datagram was really larger.

Parameters

max_bytes (int) – maximum amount of bytes to be returned

Return type

Tuple[bytes, Tuple[str, int]]

Returns

a tuple of (bytes received, (source IP address, source port))

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 async send(data, address=None, port=None)

Send a datagram.

If the default destination has been set, then address and port are optional.

Parameters
  • data (bytes) – the bytes to send

  • address (Optional[str]) – the destination IP address or host name

  • port (Optional[int]) – the destination port

Return type

None

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

anyio.create_capacity_limiter(total_tokens)

Create a capacity limiter.

Parameters

total_tokens (float) – the total number of tokens available for borrowing (can be an integer or math.inf)

Return type

CapacityLimiter

Returns

a capacity limiter 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

abstract async set()

Set the flag, notifying all listeners.

Return type

None

abstract async wait()

Wait until the flag has been set.

If the flag has already been set when this method is called, it returns immediately.

Return type

bool

class anyio.abc.Condition
abstract locked()

Return True if the lock is set.

Return type

bool

abstract async notify(n=1)

Notify exactly n listeners.

Return type

None

abstract async notify_all()

Notify all the listeners.

Return type

None

abstract async wait()

Wait for a notification.

Return type

None

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 async get()

Get an item from the queue.

If there are no items in the queue, this method will block until one is available.

Returns

the removed item

abstract async put(item)

Put an item into the queue.

If the queue is currently full, this method will block until there is at least one free slot available.

Parameters

item – the object to put into the queue

Return type

None

abstract qsize()

Return the number of items the queue is currently holding.

Return type

int

class anyio.abc.CapacityLimiter
abstract async acquire()

Acquire a token for the current task, waiting if necessary for one to become available.

Raises

anyio.exceptions.WouldBlock – if there are no tokens available for borrowing

Return type

None

abstract async acquire_nowait()

Acquire a token for the current task without waiting for one to become available.

Raises

anyio.exceptions.WouldBlock – if there are no tokens available for borrowing

Return type

None

abstract async acquire_on_behalf_of(borrower)

Acquire a token, waiting if necessary for one to become available.

Parameters

borrower – the entity borrowing a token

Raises

anyio.exceptions.WouldBlock – if there are no tokens available for borrowing

Return type

None

abstract async acquire_on_behalf_of_nowait(borrower)

Acquire a token without waiting for one to become available.

Parameters

borrower – the entity borrowing a token

Raises

anyio.exceptions.WouldBlock – if there are no tokens available for borrowing

Return type

None

abstract property available_tokens

The number of tokens currently available to be borrowed

Return type

float

abstract property borrowed_tokens

The number of tokens that have currently been borrowed.

Return type

int

abstract async release()

Release the token held by the current task. :raises RuntimeError: if the current task has not borrowed a token from this limiter.

Return type

None

abstract async release_on_behalf_of(borrower)

Release the token held by the given borrower.

Raises

RuntimeError – if the borrower has not borrowed a token from this limiter.

Return type

None

abstract property total_tokens

The total number of tokens available for borrowing.

Return type

float

Operating system signals

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

async anyio.get_current_task()

Return the current task.

Return type

TaskInfo

Returns

a representation of the current task

async anyio.get_running_tasks()

Return a list of running tasks in the current event loop.

Return type

List[TaskInfo]

Returns

a list of task info objects

async anyio.wait_all_tasks_blocked()

Wait until all other tasks are waiting for something.

Return type

None