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 functionargs – positional arguments to
func
backend (
str
) – name of the asynchronous event loop implementation – one ofasyncio
,curio
andtrio
backend_options (
Optional
[Dict
[str
,Any
]]) – keyword arguments to call the backendrun()
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.
-
anyio.
get_cancelled_exc_class
()¶ Return the current async library’s cancellation exception class.
- Return type
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
- 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
- Return type
- 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
- Return type
- 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
-
anyio.
current_time
()¶ Return the current value of the event loop’s internal clock.
:return the clock value (seconds) :rtype: float
Task groups¶
-
class
anyio.abc.
TaskGroup
¶ Groups several asynchronous tasks together.
- Variables
cancel_scope (CancelScope) – the cancel scope inherited by all child tasks
Threads¶
-
anyio.
run_in_thread
(func, *args, cancellable=False, limiter=None)¶ Start a thread that calls the given function with the given arguments.
If the
cancellable
option is enabled and the task waiting for its completion is cancelled, the thread will still run its course but its return value (or any raised exception) will be ignored.- Parameters
func (
Callable
[…, +T_Retval]) – a callableargs – positional arguments for the callable
cancellable (
bool
) –True
to allow cancellation of the operationlimiter (
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.
-
anyio.
current_default_thread_limiter
()¶ Return the capacity limiter that is used by default to limit the number of concurrent threads.
- Return type
- Returns
a capacity limiter object
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
-
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, happy_eyeballs_delay=0.25)¶ Connect to a host using the TCP protocol.
This function implements the stateless version of the Happy Eyeballs algorithm (RFC 6555). If
address
is a host name that resolves to multiple IP addresses, each one is tried until one connection attempt succeeds. If the first attempt does not connected within 250 milliseconds, a second attempt is started using the next address in the list, and so on. For IPv6 enabled systems, IPv6 addresses are tried first.- Parameters
address (
Union
[str
,IPv4Address
,IPv6Address
]) – the IP address or host name to connect toport (
int
) – port on the target host to connect tossl_context (
Optional
[SSLContext
]) – default SSL context to use for TLS handshakesautostart_tls (
bool
) –True
to do a TLS handshake on connectbind_host (
Union
[str
,IPv4Address
,IPv6Address
,None
]) – the interface address or name to bind the socket to before connectingbind_port (
Optional
[int
]) – the port to bind the socket to before connectingtls_standard_compatible (
bool
) – IfTrue
, 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 beFalse
. Seewrap_socket()
for details.happy_eyeballs_delay (
float
) – delay (in seconds) before starting the next connection attempt
- Return type
- Returns
a socket stream object
- Raises
OSError – if the connection attempt fails
-
async
anyio.
connect_unix
(path)¶ Connect to the given UNIX socket.
Not available on Windows.
- Parameters
- Return type
- 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 oninterface (
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, use0.0.0.0
for IPv4 or::
for IPv6.ssl_context (
Optional
[SSLContext
]) – an SSL context object for TLS negotiationautostart_tls (
bool
) – automatically do the TLS handshake on new connections ifssl_context
has been providedtls_standard_compatible (
bool
) – IfTrue
, 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 beFalse
. Seewrap_socket()
for details.
- Return type
- Returns
a server object
-
async
anyio.
create_unix_server
(path, *, mode=None)¶ Start a UNIX socket server.
Not available on Windows.
-
async
anyio.
create_udp_socket
(*, family=<AddressFamily.AF_UNSPEC: 0>, interface=None, port=None, target_host=None, target_port=None, reuse_address=False)¶ 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
family (
int
) – address family (AF_INET
orAF_INET6
) – automatically determined frominterface
ortarget_host
if omittedinterface (
Union
[str
,IPv4Address
,IPv6Address
,None
]) – IP address of the interface to bind totarget_host (
Union
[str
,IPv4Address
,IPv6Address
,None
]) – remote host to set as the default targettarget_port (
Optional
[int
]) – port on the remote host to set as the default targetreuse_address (
bool
) –True
to allow multiple sockets to bind to the same address/port
- Return type
- Returns
a UDP socket
-
anyio.
getaddrinfo
(host, port, *, family=0, type=0, proto=0, flags=0)¶ Look up a numeric IP address given a host name.
Internationalized domain names are translated according to the (non-transitional) IDNA 2008 standard.
- Parameters
- Return type
Awaitable
[List
[Tuple
[AddressFamily
,SocketKind
,int
,str
,Union
[Tuple
[str
,int
],Tuple
[str
,int
,int
,int
]]]]]- Returns
list of tuples containing (family, type, proto, canonname, sockaddr)
See also
-
anyio.
getnameinfo
(sockaddr, flags=0)¶ Look up the host name of an IP address.
- Parameters
- Return type
- Returns
a tuple of (host name, service name)
See also
-
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 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
- Returns
an async iterable yielding bytes
- Raises
ssl.SSLEOFError – if
tls_standard_compatible
was set toTrue
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
- Return type
- 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 toTrue
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
- 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 toTrue
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
- Returns
the bytes read
- Raises
ssl.SSLEOFError – if
tls_standard_compatible
was set toTrue
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
- Return type
- Returns
the bytes read (not 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 toTrue
in a TLS stream and the peer prematurely closed the connection
-
abstract async
-
class
anyio.abc.
SocketStream
¶ Bases:
anyio.abc.Stream
-
property
address
¶ Return the bound address of the underlying local socket.
For IPv4 TCP streams, this is a tuple of (IP address, port). For IPv6 TCP streams, this is a tuple of (IP address, port, flowinfo, scopeid). For UNIX socket streams, this is the path to the socket.
-
abstract property
alpn_protocol
¶ The ALPN protocol selected during the TLS handshake.
-
abstract property
cipher
¶ The cipher selected in the TLS handshake.
See
ssl.SSLSocket.cipher()
for more information.
-
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.
-
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
- 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()
-
property
peer_address
¶ Return the address this socket is connected to.
For IPv4 TCP streams, this is a tuple of (IP address, port). For IPv6 TCP streams, this is a tuple of (IP address, port, flowinfo, scopeid). For UNIX socket streams, this is the path to the socket.
-
abstract property
server_hostname
¶ The server host name.
-
abstract property
server_side
¶ True
if this is the server side of the connection,False
if this is the client.- Return type
- 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
The list of ciphers supported by both parties in the TLS handshake.
See
ssl.SSLSocket.shared_ciphers()
for more information.
-
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
-
property
-
class
anyio.abc.
SocketStreamServer
¶ -
abstract async
accept
()¶ Accept an incoming connection.
- Return type
- Returns
the socket stream for the accepted connection
-
abstract
accept_connections
()¶ Return an async iterable yielding streams from accepted incoming connections.
- Return type
- Returns
an async context manager
-
abstract property
address
¶ Return the bound address of the underlying socket.
-
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
-
abstract
setsockopt
(level, optname, value, *args)¶ Set a socket option.
This calls
setsockopt()
on the underlying socket.- Return type
None
-
abstract async
-
class
anyio.abc.
UDPSocket
¶ -
abstract property
address
¶ Return the bound address of the underlying socket.
-
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
-
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.
-
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
- 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
andport
are optional.- Parameters
data (
bytes
) – the bytes to sendaddress (
Union
[str
,IPv4Address
,IPv6Address
,None
]) – the destination IP address or host name
- Return type
None
-
abstract
setsockopt
(level, optname, value, *args)¶ Set a socket option.
This calls
setsockopt()
on the underlying socket.- Return type
None
-
abstract property
Synchronization¶
-
anyio.
create_semaphore
(value)¶ Create an asynchronous semaphore.
-
anyio.
create_event
()¶ Create an asynchronous event object.
- Return type
- Returns
an event object
-
anyio.
create_condition
(lock=None)¶ Create an asynchronous condition.
-
anyio.
create_queue
(capacity)¶ Create an asynchronous queue.
-
anyio.
create_capacity_limiter
(total_tokens)¶ Create a capacity limiter.
-
class
anyio.abc.
Semaphore
¶
-
class
anyio.abc.
Lock
¶
-
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
-
class
anyio.abc.
Condition
¶ -
-
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
-
abstract async
-
class
anyio.abc.
Queue
¶ -
-
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 async
-
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
-
abstract property
borrowed_tokens
¶ The number of tokens that have currently been borrowed.
- Return type
-
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 async
Operating system signals¶
-
anyio.
receive_signals
(*signals)¶ Start receiving operating system signals.
- Parameters
signals (
int
) – signals to receive (e.g.signal.SIGINT
)- Return type
- 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.
-
async
anyio.
get_current_task
()¶ Return the current task.
- Return type
- Returns
a representation of the current task
-
async
anyio.
get_running_tasks
()¶ Return a list of running tasks in the current event loop.
-
async
anyio.
wait_all_tasks_blocked
()¶ Wait until all other tasks are waiting for something.
- Return type
None