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

anyio.get_all_backends()

Return a tuple of the names of all built-in backends.

Return type

Tuple[str, …]

anyio.get_cancelled_exc_class()

Return the current async library’s cancellation exception class.

Return type

Type[BaseException]

async anyio.sleep(delay)

Pause the current task for the specified duration.

Parameters

delay (float) – the duration, in seconds

Return type

None

async anyio.current_time()

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

Return type

float

Returns

the clock value (seconds)

Asynchronous resources

async anyio.aclose_forcefully(resource)

Close an asynchronous resource in a cancelled scope.

Doing this closes the resource without waiting on anything.

Parameters

resource (AsyncResource) – the resource to close

Return type

None

class anyio.abc.AsyncResource

Bases: object

Abstract base class for all closeable asynchronous resources.

Works as an asynchronous context manager which returns the instance itself on enter, and calls aclose() on exit.

abstract async aclose()

Close the resource.

Return type

None

Typed attributes

anyio.typed_attribute()

Return a unique object, used to mark typed attributes.

class anyio.TypedAttributeSet

Bases: object

Superclass for typed attribute collections.

Checks that every public attribute of every subclass has a type annotation.

class anyio.TypedAttributeProvider

Bases: object

Base class for classes that wish to provide typed extra attributes.

extra(attribute, default=undefined)

Return the value of the given typed extra attribute.

Parameters
  • attribute – the attribute (member of a TypedAttributeSet) to look for

  • default – the value that should be returned if no value is found for the attribute

Raises

TypedAttributeLookupError – if the search failed and no default value was given

property extra_attributes

A mapping of the extra attributes to callables that return the corresponding values.

If the provider wraps another provider, the attributes from that wrapper should also be included in the returned mapping (but the wrapper may override the callables from the wrapped instance).

Return type

Mapping[~T_Attr, Callable[[], ~T_Attr]]

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

Returns

an asynchronous context manager that yields a cancel scope

Return type

AsyncContextManager[CancelScope]

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

Returns

an asynchronous context manager that yields a cancel scope

Return type

AsyncContextManager[CancelScope]

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

class anyio.abc.CancelScope

Bases: object

abstract async cancel()

Cancel this scope immediately.

Return type

None

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

Bases: object

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]) – 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

async anyio.run_sync_in_worker_thread(func, *args, cancellable=False, limiter=None)

Call the given function with the given arguments in a worker thread.

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 callable

  • args – positional arguments for the callable

  • cancellable (bool) – True to allow cancellation of the operation

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

Return type

~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

anyio.current_default_worker_thread_limiter()

Return the capacity limiter that is used by default to limit the number of concurrent threads.

Return type

CapacityLimiter

Returns

a capacity limiter object

anyio.create_blocking_portal()

Create a portal for running functions in the event loop thread from external threads.

Use this function in asynchronous code when you need to allow external threads access to the event loop where your asynchronous code is currently running.

Return type

BlockingPortal

anyio.start_blocking_portal(backend='asyncio', backend_options=None)

Start a new event loop in a new thread and run a blocking portal in its main task.

The parameters are the same as for run().

Parameters
Return type

BlockingPortal

Returns

a blocking portal object

class anyio.abc.BlockingPortal

Bases: object

An object tied that lets external threads run code in an asynchronous event loop.

call(func, *args)

Call the given function in the event loop thread.

If the callable returns a coroutine object, it is awaited on.

Parameters

func – any callable

Raises

RuntimeError – if this method is called from within the event loop thread

async sleep_until_stopped()

Sleep until stop() is called.

Return type

None

async stop(cancel_remaining=False)

Signal the portal to shut down.

This marks the portal as no longer accepting new calls and exits from sleep_until_stopped().

Parameters

cancel_remaining (bool) – True to cancel all the remaining tasks, False to let them finish before returning

Return type

None

stop_from_external_thread(cancel_remaining=False)

Signal the portal to stop and wait for the event loop thread to finish.

Parameters

cancel_remaining (bool) – True to cancel all the remaining tasks, False to let them finish before returning

Return type

None

Async file I/O

async anyio.open_file(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().

Return type

AsyncFile

Returns

an asynchronous file object

class anyio.AsyncFile(fp)

Bases: anyio.abc.AsyncResource

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

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 anyio.open_file(...) as f:
    async for line in f:
        print(line)
async aclose()

Close the resource.

Return type

None

property wrapped

The wrapped file object.

Streams and stream wrappers

anyio.create_memory_object_stream(max_buffer_size=0, item_type=None)

Create a memory object stream.

Parameters
  • max_buffer_size – number of items held in the buffer until send() starts blocking

  • item_type – type of item, for marking the streams with the right generic type for static typing (not used at run time)

Returns

a tuple of (send stream, receive stream)

class anyio.abc.UnreliableObjectReceiveStream

Bases: typing.Generic, anyio.abc.AsyncResource, anyio.TypedAttributeProvider

An interface for receiving objects.

This interface makes no guarantees that the received messages arrive in the order in which they were sent, or that no messages are missed.

Asynchronously iterating over objects of this type will yield objects matching the given type parameter.

abstract async receive()

Receive the next item.

Raises
Return type

~T_Item

class anyio.abc.UnreliableObjectSendStream

Bases: typing.Generic, anyio.abc.AsyncResource, anyio.TypedAttributeProvider

An interface for sending objects.

This interface makes no guarantees that the messages sent will reach the recipient(s) in the same order in which they were sent, or at all.

abstract async send(item)

Send an item to the peer(s).

Parameters

item (~T_Item) – the item to send

Raises
Return type

None

class anyio.abc.UnreliableObjectStream

Bases: anyio.abc.UnreliableObjectReceiveStream, anyio.abc.UnreliableObjectSendStream

A bidirectional message stream which does not guarantee the order or reliability of message delivery.

class anyio.abc.ObjectReceiveStream

Bases: anyio.abc.UnreliableObjectReceiveStream

A receive message stream which guarantees that messages are received in the same order in which they were sent, and that no messages are missed.

class anyio.abc.ObjectSendStream

Bases: anyio.abc.UnreliableObjectSendStream

A send message stream which guarantees that messages are delivered in the same order in which they were sent, without missing any messages in the middle.

class anyio.abc.ObjectStream

Bases: anyio.abc.ObjectReceiveStream, anyio.abc.ObjectSendStream, anyio.abc.UnreliableObjectStream

A bidirectional message stream which guarantees the order and reliability of message delivery.

abstract async send_eof()

Send an end-of-file indication to the peer.

You should not try to send any further data to this stream after calling this method. This method is idempotent (does nothing on successive calls).

Return type

None

class anyio.abc.ByteReceiveStream

Bases: anyio.abc.AsyncResource, anyio.TypedAttributeProvider

An interface for receiving bytes from a single peer.

Iterating this byte stream will yield a byte string of arbitrary length, but no more than 65536 bytes.

abstract async receive(max_bytes=65536)

Receive at most max_bytes bytes from the peer.

Parameters

max_bytes (int) – maximum number of bytes to receive

Return type

bytes

Returns

the received bytes

Raises

EndOfStream – if this stream has been closed from the other end

class anyio.abc.ByteSendStream

Bases: anyio.abc.AsyncResource, anyio.TypedAttributeProvider

An interface for sending bytes to a single peer.

abstract async send(item)

Send the given bytes to the peer.

Parameters

item (bytes) – the bytes to send

Return type

None

class anyio.abc.ByteStream

Bases: anyio.abc.ByteReceiveStream, anyio.abc.ByteSendStream

A bidirectional byte stream.

abstract async send_eof()

Send an end-of-file indication to the peer.

You should not try to send any further data to this stream after calling this method. This method is idempotent (does nothing on successive calls).

Return type

None

class anyio.abc.Listener(*args, **kwds)

Bases: typing.Generic, anyio.abc.AsyncResource, anyio.TypedAttributeProvider

An interface for objects that let you accept incoming connections.

abstract async serve(handler, task_group=None)

Accept incoming connections as they come in and spawn tasks to handle them.

Parameters
  • handler (Callable[[~T_Stream], Any]) – a callable that will be used to handle each accepted connection

  • task_group (Optional[TaskGroup]) – the task group that will be used to spawn tasks for handling each accepted connection (if omitted, an ad-hoc task group will be created)

Return type

None

anyio.abc.AnyUnreliableByteReceiveStream = typing.Union[anyio.abc.UnreliableObjectReceiveStream[bytes], anyio.abc.ByteReceiveStream]

Union type; Union[X, Y] means either X or Y.

To define a union, use e.g. Union[int, str]. Details:

  • The arguments must be types and there must be at least one.

  • None as an argument is a special case and is replaced by type(None).

  • Unions of unions are flattened, e.g.:

    Union[Union[int, str], float] == Union[int, str, float]
    
  • Unions of a single argument vanish, e.g.:

    Union[int] == int  # The constructor actually returns int
    
  • Redundant arguments are skipped, e.g.:

    Union[int, str, int] == Union[int, str]
    
  • When comparing unions, the argument order is ignored, e.g.:

    Union[int, str] == Union[str, int]
    
  • When two arguments have a subclass relationship, the least derived argument is kept, e.g.:

    class Employee: pass
    class Manager(Employee): pass
    Union[int, Employee, Manager] == Union[int, Employee]
    Union[Manager, int, Employee] == Union[int, Employee]
    Union[Employee, Manager] == Employee
    
  • Similar for object:

    Union[int, object] == object
    
  • You cannot subclass or instantiate a union.

  • You can use Optional[X] as a shorthand for Union[X, None].

anyio.abc.AnyUnreliableByteSendStream = typing.Union[anyio.abc.UnreliableObjectSendStream[bytes], anyio.abc.ByteSendStream]

Union type; Union[X, Y] means either X or Y.

To define a union, use e.g. Union[int, str]. Details:

  • The arguments must be types and there must be at least one.

  • None as an argument is a special case and is replaced by type(None).

  • Unions of unions are flattened, e.g.:

    Union[Union[int, str], float] == Union[int, str, float]
    
  • Unions of a single argument vanish, e.g.:

    Union[int] == int  # The constructor actually returns int
    
  • Redundant arguments are skipped, e.g.:

    Union[int, str, int] == Union[int, str]
    
  • When comparing unions, the argument order is ignored, e.g.:

    Union[int, str] == Union[str, int]
    
  • When two arguments have a subclass relationship, the least derived argument is kept, e.g.:

    class Employee: pass
    class Manager(Employee): pass
    Union[int, Employee, Manager] == Union[int, Employee]
    Union[Manager, int, Employee] == Union[int, Employee]
    Union[Employee, Manager] == Employee
    
  • Similar for object:

    Union[int, object] == object
    
  • You cannot subclass or instantiate a union.

  • You can use Optional[X] as a shorthand for Union[X, None].

anyio.abc.AnyUnreliableByteStream = typing.Union[anyio.abc.UnreliableObjectStream[bytes], anyio.abc.ByteStream]

Union type; Union[X, Y] means either X or Y.

To define a union, use e.g. Union[int, str]. Details:

  • The arguments must be types and there must be at least one.

  • None as an argument is a special case and is replaced by type(None).

  • Unions of unions are flattened, e.g.:

    Union[Union[int, str], float] == Union[int, str, float]
    
  • Unions of a single argument vanish, e.g.:

    Union[int] == int  # The constructor actually returns int
    
  • Redundant arguments are skipped, e.g.:

    Union[int, str, int] == Union[int, str]
    
  • When comparing unions, the argument order is ignored, e.g.:

    Union[int, str] == Union[str, int]
    
  • When two arguments have a subclass relationship, the least derived argument is kept, e.g.:

    class Employee: pass
    class Manager(Employee): pass
    Union[int, Employee, Manager] == Union[int, Employee]
    Union[Manager, int, Employee] == Union[int, Employee]
    Union[Employee, Manager] == Employee
    
  • Similar for object:

    Union[int, object] == object
    
  • You cannot subclass or instantiate a union.

  • You can use Optional[X] as a shorthand for Union[X, None].

anyio.abc.AnyByteReceiveStream = typing.Union[anyio.abc.ObjectReceiveStream[bytes], anyio.abc.ByteReceiveStream]

Union type; Union[X, Y] means either X or Y.

To define a union, use e.g. Union[int, str]. Details:

  • The arguments must be types and there must be at least one.

  • None as an argument is a special case and is replaced by type(None).

  • Unions of unions are flattened, e.g.:

    Union[Union[int, str], float] == Union[int, str, float]
    
  • Unions of a single argument vanish, e.g.:

    Union[int] == int  # The constructor actually returns int
    
  • Redundant arguments are skipped, e.g.:

    Union[int, str, int] == Union[int, str]
    
  • When comparing unions, the argument order is ignored, e.g.:

    Union[int, str] == Union[str, int]
    
  • When two arguments have a subclass relationship, the least derived argument is kept, e.g.:

    class Employee: pass
    class Manager(Employee): pass
    Union[int, Employee, Manager] == Union[int, Employee]
    Union[Manager, int, Employee] == Union[int, Employee]
    Union[Employee, Manager] == Employee
    
  • Similar for object:

    Union[int, object] == object
    
  • You cannot subclass or instantiate a union.

  • You can use Optional[X] as a shorthand for Union[X, None].

anyio.abc.AnyByteSendStream = typing.Union[anyio.abc.ObjectSendStream[bytes], anyio.abc.ByteSendStream]

Union type; Union[X, Y] means either X or Y.

To define a union, use e.g. Union[int, str]. Details:

  • The arguments must be types and there must be at least one.

  • None as an argument is a special case and is replaced by type(None).

  • Unions of unions are flattened, e.g.:

    Union[Union[int, str], float] == Union[int, str, float]
    
  • Unions of a single argument vanish, e.g.:

    Union[int] == int  # The constructor actually returns int
    
  • Redundant arguments are skipped, e.g.:

    Union[int, str, int] == Union[int, str]
    
  • When comparing unions, the argument order is ignored, e.g.:

    Union[int, str] == Union[str, int]
    
  • When two arguments have a subclass relationship, the least derived argument is kept, e.g.:

    class Employee: pass
    class Manager(Employee): pass
    Union[int, Employee, Manager] == Union[int, Employee]
    Union[Manager, int, Employee] == Union[int, Employee]
    Union[Employee, Manager] == Employee
    
  • Similar for object:

    Union[int, object] == object
    
  • You cannot subclass or instantiate a union.

  • You can use Optional[X] as a shorthand for Union[X, None].

anyio.abc.AnyByteStream = typing.Union[anyio.abc.ObjectStream[bytes], anyio.abc.ByteStream]

Union type; Union[X, Y] means either X or Y.

To define a union, use e.g. Union[int, str]. Details:

  • The arguments must be types and there must be at least one.

  • None as an argument is a special case and is replaced by type(None).

  • Unions of unions are flattened, e.g.:

    Union[Union[int, str], float] == Union[int, str, float]
    
  • Unions of a single argument vanish, e.g.:

    Union[int] == int  # The constructor actually returns int
    
  • Redundant arguments are skipped, e.g.:

    Union[int, str, int] == Union[int, str]
    
  • When comparing unions, the argument order is ignored, e.g.:

    Union[int, str] == Union[str, int]
    
  • When two arguments have a subclass relationship, the least derived argument is kept, e.g.:

    class Employee: pass
    class Manager(Employee): pass
    Union[int, Employee, Manager] == Union[int, Employee]
    Union[Manager, int, Employee] == Union[int, Employee]
    Union[Employee, Manager] == Employee
    
  • Similar for object:

    Union[int, object] == object
    
  • You cannot subclass or instantiate a union.

  • You can use Optional[X] as a shorthand for Union[X, None].

class anyio.streams.buffered.BufferedByteReceiveStream(receive_stream)

Bases: anyio.abc.ByteReceiveStream

Wraps any bytes-based receive stream and uses a buffer to provide sophisticated receiving capabilities in the form of a byte stream.

async aclose()

Close the resource.

Return type

None

property buffer

The bytes currently in the buffer.

Return type

bytes

property extra_attributes

A mapping of the extra attributes to callables that return the corresponding values.

If the provider wraps another provider, the attributes from that wrapper should also be included in the returned mapping (but the wrapper may override the callables from the wrapped instance).

async receive(max_bytes=65536)

Receive at most max_bytes bytes from the peer.

Parameters

max_bytes (int) – maximum number of bytes to receive

Return type

bytes

Returns

the received bytes

Raises

EndOfStream – if this stream has been closed from the other end

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

IncompleteRead – if the stream was closed before the requested amount of bytes could be read from the stream

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
  • IncompleteRead – if the stream was closed before the delimiter was found

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

class anyio.streams.memory.MemoryObjectReceiveStream(_state)

Bases: anyio.abc.ObjectReceiveStream

async aclose()

Close the resource.

Return type

None

clone()

Create a clone of this receive stream.

Each clone can be closed separately. Only when all clones have been closed will the receiving end of the memory stream be considered closed by the sending ends.

Return type

MemoryObjectReceiveStream

Returns

the cloned stream

async receive()

Receive the next item.

Raises
Return type

~T_Item

async receive_nowait()

Receive the next item if it can be done without waiting.

Return type

~T_Item

Returns

the received item

Raises
  • ClosedResourceError – if this send stream has been closed

  • EndOfStream – if the buffer is empty and this stream has been closed from the sending end

  • WouldBlock – if there are no items in the buffer and no tasks waiting to send

class anyio.streams.memory.MemoryObjectSendStream(_state)

Bases: anyio.abc.ObjectSendStream

async aclose()

Close the resource.

Return type

None

clone()

Create a clone of this send stream.

Each clone can be closed separately. Only when all clones have been closed will the sending end of the memory stream be considered closed by the receiving ends.

Return type

MemoryObjectSendStream

Returns

the cloned stream

async send(item)

Send an item to the peer(s).

Parameters

item (~T_Item) – the item to send

Raises
Return type

None

async send_nowait(item)

Send an item immediately if it can be done without waiting.

Parameters

item (~T_Item) – the item to send

Raises
Return type

None

class anyio.streams.stapled.MultiListener(listeners)

Bases: anyio.abc.Listener

Combines multiple listeners into one, serving connections from all of them at once.

Any MultiListeners in the given collection of listeners will have their listeners moved into this one.

Extra attributes are provided from each listener, with each successive listener overriding any conflicting attributes from the previous one.

Parameters

listeners (Sequence[Listener[T_Stream]]) – listeners to serve

async aclose()

Close the resource.

Return type

None

property extra_attributes

A mapping of the extra attributes to callables that return the corresponding values.

If the provider wraps another provider, the attributes from that wrapper should also be included in the returned mapping (but the wrapper may override the callables from the wrapped instance).

async serve(handler, task_group=None)

Accept incoming connections as they come in and spawn tasks to handle them.

Parameters
  • handler (Callable[[~T_Stream], Any]) – a callable that will be used to handle each accepted connection

  • task_group (Optional[TaskGroup]) – the task group that will be used to spawn tasks for handling each accepted connection (if omitted, an ad-hoc task group will be created)

Return type

None

class anyio.streams.stapled.StapledByteStream(send_stream, receive_stream)

Bases: anyio.abc.ByteStream

Combines two byte streams into a single, bidirectional byte stream.

Extra attributes will be provided from both streams, with the receive stream providing the values in case of a conflict.

Parameters
async aclose()

Close the resource.

Return type

None

property extra_attributes

A mapping of the extra attributes to callables that return the corresponding values.

If the provider wraps another provider, the attributes from that wrapper should also be included in the returned mapping (but the wrapper may override the callables from the wrapped instance).

async receive(max_bytes=65536)

Receive at most max_bytes bytes from the peer.

Parameters

max_bytes (int) – maximum number of bytes to receive

Return type

bytes

Returns

the received bytes

Raises

EndOfStream – if this stream has been closed from the other end

async send(item)

Send the given bytes to the peer.

Parameters

item (bytes) – the bytes to send

Return type

None

async send_eof()

Send an end-of-file indication to the peer.

You should not try to send any further data to this stream after calling this method. This method is idempotent (does nothing on successive calls).

Return type

None

class anyio.streams.stapled.StapledObjectStream(send_stream, receive_stream)

Bases: anyio.abc.ObjectStream

Combines two object streams into a single, bidirectional object stream.

Extra attributes will be provided from both streams, with the receive stream providing the values in case of a conflict.

Parameters
async aclose()

Close the resource.

Return type

None

property extra_attributes

A mapping of the extra attributes to callables that return the corresponding values.

If the provider wraps another provider, the attributes from that wrapper should also be included in the returned mapping (but the wrapper may override the callables from the wrapped instance).

async receive()

Receive the next item.

Raises
Return type

~T_Item

async send(item)

Send an item to the peer(s).

Parameters

item (~T_Item) – the item to send

Raises
Return type

None

async send_eof()

Send an end-of-file indication to the peer.

You should not try to send any further data to this stream after calling this method. This method is idempotent (does nothing on successive calls).

Return type

None

class anyio.streams.text.TextReceiveStream(transport_stream, encoding='utf-8', errors='strict')

Bases: anyio.abc.ObjectReceiveStream

Stream wrapper that decodes bytes to strings using the given encoding.

Receives from the wrapped stream until the given delimiter is found, and then returns the string (without the delimiter).

Parameters
  • transport_stream (Union[ObjectReceiveStream[bytes], ByteReceiveStream]) – any bytes-based receive stream

  • encoding (InitVar) – character encoding to use for decoding bytes to strings (defaults to utf-8)

  • errors (InitVar) – handling scheme for decoding errors (defaults to strict; see the codecs module documentation for a comprehensive list of options)

async aclose()

Close the resource.

Return type

None

property extra_attributes

A mapping of the extra attributes to callables that return the corresponding values.

If the provider wraps another provider, the attributes from that wrapper should also be included in the returned mapping (but the wrapper may override the callables from the wrapped instance).

async receive()

Receive the next item.

Raises
Return type

str

class anyio.streams.text.TextSendStream(transport_stream, encoding='utf-8', errors='strict')

Bases: anyio.abc.ObjectSendStream

Sends strings to the wrapped stream as bytes using the given encoding.

Parameters
  • transport_stream (AnyByteSendStream) – any bytes-based send stream

  • encoding (str) – character encoding to use for encoding strings to bytes (defaults to utf-8)

  • errors (str) – handling scheme for encoding errors (defaults to strict; see the codecs module documentation for a comprehensive list of options)

async aclose()

Close the resource.

Return type

None

property extra_attributes

A mapping of the extra attributes to callables that return the corresponding values.

If the provider wraps another provider, the attributes from that wrapper should also be included in the returned mapping (but the wrapper may override the callables from the wrapped instance).

async send(item)

Send an item to the peer(s).

Parameters

item (str) – the item to send

Raises
Return type

None

class anyio.streams.text.TextStream(transport_stream, encoding='utf-8', errors='strict')

Bases: anyio.abc.ObjectStream

A bidirectional stream that decodes bytes to strings on receive and encodes strings to bytes on send.

Extra attributes will be provided from both streams, with the receive stream providing the values in case of a conflict.

Parameters
  • transport_stream (AnyByteStream) – any bytes-based stream

  • encoding (str) – character encoding to use for encoding/decoding strings to/from bytes (defaults to utf-8)

  • errors (str) – handling scheme for encoding errors (defaults to strict; see the codecs module documentation for a comprehensive list of options)

async aclose()

Close the resource.

Return type

None

property extra_attributes

A mapping of the extra attributes to callables that return the corresponding values.

If the provider wraps another provider, the attributes from that wrapper should also be included in the returned mapping (but the wrapper may override the callables from the wrapped instance).

async receive()

Receive the next item.

Raises
Return type

str

async send(item)

Send an item to the peer(s).

Parameters

item (str) – the item to send

Raises
Return type

None

async send_eof()

Send an end-of-file indication to the peer.

You should not try to send any further data to this stream after calling this method. This method is idempotent (does nothing on successive calls).

Return type

None

class anyio.streams.tls.TLSAttribute

Bases: anyio.TypedAttributeSet

Contains Transport Layer Security related attributes.

alpn_protocol: Optional[str] = <object object>

the selected ALPN protocol

channel_binding_tls_unique: bytes = <object object>

the channel binding for type tls-unique

cipher: Tuple[str, str, int] = <object object>

the selected cipher

peer_certificate: Optional[Dict[str, Union[str, tuple]]] = <object object>

the peer certificate in dictionary form (see ssl.SSLSocket.getpeercert() for more information)

peer_certificate_binary: Optional[bytes] = <object object>

the peer certificate in binary form

server_side: bool = <object object>

True if this is the server side of the connection

shared_ciphers: List[Tuple[str, str, int]] = <object object>

ciphers shared between both ends of the TLS connection

ssl_object: ssl.SSLObject = <object object>

the SSLObject used for encryption

standard_compatible: bool = <object object>

True if this stream does (and expects) a closing TLS handshake when the stream is being closed

tls_version: str = <object object>

the TLS protocol version (e.g. TLSv1.2)

class anyio.streams.tls.TLSStream(transport_stream, standard_compatible, _ssl_object, _read_bio, _write_bio)

Bases: anyio.abc.ByteStream

A stream wrapper that encrypts all sent data and decrypts received data.

This class has no public initializer; use wrap() instead. All extra attributes from TLSAttribute are supported.

Variables

transport_stream (AnyByteStream) – the wrapped stream

async aclose()

Close the resource.

Return type

None

property extra_attributes

A mapping of the extra attributes to callables that return the corresponding values.

If the provider wraps another provider, the attributes from that wrapper should also be included in the returned mapping (but the wrapper may override the callables from the wrapped instance).

async receive(max_bytes=65536)

Receive at most max_bytes bytes from the peer.

Parameters

max_bytes (int) – maximum number of bytes to receive

Return type

bytes

Returns

the received bytes

Raises

EndOfStream – if this stream has been closed from the other end

async send(item)

Send the given bytes to the peer.

Parameters

item (bytes) – the bytes to send

Return type

None

async send_eof()

Send an end-of-file indication to the peer.

You should not try to send any further data to this stream after calling this method. This method is idempotent (does nothing on successive calls).

Return type

None

async unwrap()

Does the TLS closing handshake.

Return type

Tuple[Union[ObjectStream[bytes], ByteStream], bytes]

Returns

a tuple of (wrapped byte stream, bytes left in the read buffer)

async classmethod wrap(transport_stream, *, server_side=None, hostname=None, ssl_context=None, standard_compatible=True)

Wrap an existing stream with Transport Layer Security.

This performs a TLS handshake with the peer.

Parameters
  • transport_stream (Union[ObjectStream[bytes], ByteStream]) – a bytes-transporting stream to wrap

  • server_side (Optional[bool]) – True if this is the server side of the connection, False if this is the client side (if omitted, will be set to False if hostname has been provided, False otherwise). Used only to create a default context when an explicit context has not been provided.

  • hostname (Optional[str]) – host name of the peer (if host name checking is desired)

  • ssl_context (Optional[SSLContext]) – the SSLContext object to use (if not provided, a secure default will be created)

  • standard_compatible (bool) – if False, skip the closing handshake when closing the connection, and don’t raise an exception if the peer does the same

Raises

SSLError – if the TLS handshake fails

Return type

TLSStream

class anyio.streams.tls.TLSListener(listener, ssl_context, standard_compatible=True)

Bases: anyio.abc.Listener

A convenience listener that wraps another listener and auto-negotiates a TLS session on every accepted connection.

Supports only the standard_compatible extra attribute.

Parameters
async aclose()

Close the resource.

Return type

None

property extra_attributes

A mapping of the extra attributes to callables that return the corresponding values.

If the provider wraps another provider, the attributes from that wrapper should also be included in the returned mapping (but the wrapper may override the callables from the wrapped instance).

async serve(handler, task_group=None)

Accept incoming connections as they come in and spawn tasks to handle them.

Parameters
  • handler (Callable[[TLSStream], Any]) – a callable that will be used to handle each accepted connection

  • task_group (Optional[TaskGroup]) – the task group that will be used to spawn tasks for handling each accepted connection (if omitted, an ad-hoc task group will be created)

Return type

None

Sockets and networking

async anyio.connect_tcp(remote_host, remote_port, *, local_host=None, tls=False, ssl_context=None, tls_standard_compatible=True, tls_hostname=None, 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. On IPv6 enabled systems, an IPv6 address (if available) is tried first.

When the connection has been established, a TLS handshake will be done if either ssl_context or tls_hostname is not None, or if tls is True.

Parameters
  • remote_host – the IP address or host name to connect to

  • remote_port – port on the target host to connect to

  • local_host – the interface address or name to bind the socket to before connecting

  • tlsTrue to do a TLS handshake with the connected stream and return a TLSStream instead

  • ssl_context – the SSL context object to use (if omitted, a default context is created)

  • tls_standard_compatible – 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.

  • tls_hostname – host name to check the server certificate against (defaults to the value of remote_host)

  • happy_eyeballs_delay – delay (in seconds) before starting the next connection attempt

Returns

a socket stream object if no TLS handshake was done, otherwise a TLS stream

Raises

OSError – if the connection attempt fails

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_listener(*, local_host=None, local_port=0, family=<AddressFamily.AF_UNSPEC: 0>, backlog=65536, reuse_port=False)

Create a TCP socket listener.

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

  • local_host (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.

  • family (Literal[<AddressFamily.AF_UNSPEC: 0>, <AddressFamily.AF_INET: 2>, <AddressFamily.AF_INET6: 10>]) – address family (used if interface was omitted)

  • backlog (int) – maximum number of queued incoming connections (up to a maximum of 2**16, or 65536)

  • reuse_port (bool) – True to allow multiple sockets to bind to the same address/port (not supported on Windows)

Return type

MultiListener[SocketStream[Tuple[str, int]]]

Returns

a list of listener objects

async anyio.create_unix_listener(path, *, mode=None, backlog=65536)

Create a UNIX socket listener.

Not available on Windows.

Parameters
  • path (Union[str, PathLike]) – path of the socket

  • mode (Optional[int]) – permissions to set on the socket

  • backlog (int) – maximum number of queued incoming connections (up to a maximum of 2**16, or 65536)

Return type

SocketListener[str]

Returns

a listener object

async anyio.create_udp_socket(family=<AddressFamily.AF_UNSPEC: 0>, *, local_host=None, local_port=0, reuse_port=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 (Literal[<AddressFamily.AF_UNSPEC: 0>, <AddressFamily.AF_INET: 2>, <AddressFamily.AF_INET6: 10>]) – address family (AF_INET or AF_INET6) – automatically determined from interface or target_host if omitted

  • local_host (Union[str, IPv4Address, IPv6Address, None]) – IP address or host name of the local interface to bind to

  • local_port (int) – local port to bind to

  • reuse_port (bool) – True to allow multiple sockets to bind to the same address/port (not supported on Windows)

Return type

UDPSocket

Returns

a UDP socket

async anyio.create_connected_udp_socket(remote_host, remote_port, *, family=<AddressFamily.AF_UNSPEC: 0>, local_host=None, local_port=0, reuse_port=False)

Create a connected UDP socket.

Connected UDP sockets can only communicate with the specified remote host/port, and any packets sent from other sources are dropped.

Parameters
  • remote_host (Union[str, IPv4Address, IPv6Address]) – remote host to set as the default target

  • remote_port (int) – port on the remote host to set as the default target

  • family (Literal[<AddressFamily.AF_UNSPEC: 0>, <AddressFamily.AF_INET: 2>, <AddressFamily.AF_INET6: 10>]) – address family (AF_INET or AF_INET6) – automatically determined from local_host or remote_host if omitted

  • local_host (Union[str, IPv4Address, IPv6Address, None]) – IP address or host name of the local interface to bind to

  • local_port (int) – local port to bind to

  • reuse_port (bool) – True to allow multiple sockets to bind to the same address/port (not supported on Windows)

Return type

ConnectedUDPSocket

Returns

a connected UDP socket

async 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.

Note

4-tuple IPv6 socket addresses are automatically converted to 2-tuples of (host, port), unlike what socket.getaddrinfo() does.

Parameters
  • host (Union[bytearray, bytes, str]) – host name

  • port (Union[str, int, None]) – port number

  • family (int) – socket family (‘AF_INET`, …)

  • type (int) – socket type (SOCK_STREAM, …)

  • proto (int) – protocol number

  • flags (int) – flags to pass to upstream getaddrinfo()

Return type

List[Tuple[AddressFamily, SocketKind, int, str, Tuple[str, int]]]

Returns

list of tuples containing (family, type, proto, canonname, sockaddr)

anyio.getnameinfo(sockaddr, flags=0)

Look up the host name of an IP address.

Parameters
  • sockaddr (Tuple[str, int]) – socket address (e.g. (ipaddress, port) for IPv4)

  • flags (int) – flags to pass to upstream getnameinfo()

Return type

Awaitable[Tuple[str, str]]

Returns

a tuple of (host name, service name)

anyio.wait_socket_readable(sock)

Wait until the given socket has data to be read.

This does NOT work on Windows when using the asyncio backend with a proactor event loop (default on py3.8+).

Parameters

sock (socket) – a socket object

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

  • BusyResourceError – 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.

This does NOT work on Windows when using the asyncio backend with a proactor event loop (default on py3.8+).

Parameters

sock (socket) – a socket object

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

  • BusyResourceError – if another task is already waiting for the socket to become writable

Return type

Awaitable[None]

class anyio.abc.SocketAttribute

Bases: anyio.TypedAttributeSet

class anyio.abc.SocketStream

Bases: anyio.abc.ByteStream, anyio.abc.sockets._SocketProvider

Transports bytes over a socket.

Supports all relevant extra attributes from SocketAttribute.

class anyio.abc.SocketListener

Bases: anyio.abc.Listener, anyio.abc.sockets._SocketProvider

Listens to incoming socket connections.

Supports all relevant extra attributes from SocketAttribute.

abstract async accept()

Accept an incoming connection.

Return type

SocketStream[~T_SockAddr]

async serve(handler, task_group=None)

Accept incoming connections as they come in and spawn tasks to handle them.

Parameters
  • handler (Callable[[~T_Stream], Any]) – a callable that will be used to handle each accepted connection

  • task_group (Optional[TaskGroup]) – the task group that will be used to spawn tasks for handling each accepted connection (if omitted, an ad-hoc task group will be created)

Return type

None

class anyio.abc.UDPSocket

Bases: anyio.abc.UnreliableObjectStream, anyio.abc.sockets._SocketProvider

Represents an unconnected UDP socket.

Supports all relevant extra attributes from SocketAttribute.

async sendto(data, host, port)

Alias for send() ((data, (host, port))).

Return type

None

class anyio.abc.ConnectedUDPSocket

Bases: anyio.abc.UnreliableObjectStream, anyio.abc.sockets._SocketProvider

Represents an connected UDP socket.

Supports all relevant extra attributes from SocketAttribute.

Subprocesses

async anyio.run_process(command, *, input=None, stdout=- 1, stderr=- 1, check=True)

Run an external command in a subprocess and wait until it completes.

See also

subprocess.run()

Parameters
Return type

CompletedProcess

Returns

an object representing the completed process

Raises

CalledProcessError – if check is True and the process exits with a nonzero return code

async anyio.open_process(command, *, stdin=- 1, stdout=- 1, stderr=- 1)

Start an external command in a subprocess.

See also

subprocess.Popen

Parameters
Return type

Process

Returns

an asynchronous process object

class anyio.abc.Process

Bases: anyio.abc.AsyncResource

An asynchronous version of subprocess.Popen.

abstract kill()

Kills the process.

On Windows, this calls TerminateProcess(). On POSIX systems, this sends SIGKILL to the process.

Return type

None

abstract property pid

The process ID of the process.

Return type

int

abstract property returncode

The return code of the process. If the process has not yet terminated, this will be None.

Return type

Optional[int]

abstract send_signal(signal)

Send a signal to the subprocess.

Parameters

signal (int) – the signal number (e.g. signal.SIGHUP)

Return type

None

abstract property stderr

The stream for the standard error output of the process.

Return type

Optional[ByteReceiveStream]

abstract property stdin

The stream for the standard input of the process.

Return type

Optional[ByteSendStream]

abstract property stdout

The stream for the standard output of the process.

Return type

Optional[ByteReceiveStream]

abstract terminate()

Terminates the process, gracefully if possible.

On Windows, this calls TerminateProcess(). On POSIX systems, this sends SIGTERM to the process.

Return type

None

abstract async wait()

Wait until the process exits.

Return type

int

Returns

the exit code of the process

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_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

Bases: object

abstract async acquire()

Decrement the semaphore value, blocking if necessary.

Return type

None

abstract async release()

Increment the semaphore value.

Return type

None

abstract property value

The current value of the semaphore.

Return type

int

class anyio.abc.Lock

Bases: object

abstract async acquire()

Acquire the lock.

Return type

None

abstract locked()

Return True if the lock is currently held.

Return type

bool

abstract async release()

Release the lock.

Return type

None

class anyio.abc.Event

Bases: object

abstract is_set()

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

Return type

bool

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

Bases: object

abstract async acquire()

Acquire the underlying lock.

Return type

None

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 release()

Release the underlying lock.

Return type

None

abstract async wait()

Wait for a notification.

Return type

None

class anyio.abc.CapacityLimiter

Bases: object

abstract async acquire()

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

Return type

None

abstract async acquire_nowait()

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

Raises

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

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

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 async set_total_tokens(value)

Set the total number of tokens.

If the total number of tokens is increased, the proportionate number of tasks waiting on this limiter will be granted their tokens.

Parameters

value (float) – the new total number of tokens (>= 1)

Return type

None

abstract property total_tokens

The total number of tokens available for borrowing.

Return type

float

Operating system signals

anyio.open_signal_receiver(*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)

Bases: object

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

Exceptions

exception anyio.BrokenResourceError

Bases: Exception

Raised when trying to use a resource that has been rendered unusuable due to external causes (e.g. a send stream whose peer has disconnected).

exception anyio.BusyResourceError(action)

Bases: Exception

Raised when two tasks are trying to read from or write to the same resource concurrently.

exception anyio.ClosedResourceError

Bases: Exception

Raised when trying to use a resource that has been closed.

exception anyio.DelimiterNotFound(max_bytes)

Bases: Exception

Raised during receive_until() if the maximum number of bytes has been read without the delimiter being found.

exception anyio.EndOfStream

Bases: Exception

Raised when trying to read from a stream that has been closed from the other end.

exception anyio.ExceptionGroup

Bases: BaseException

Raised when multiple exceptions have been raised in a task group.

exception anyio.IncompleteRead

Bases: Exception

Raised during receive_exactly() or receive_until() if the connection is closed before the requested amount of bytes has been read.

exception anyio.TypedAttributeLookupError

Bases: LookupError

Raised by extra() when the given typed attribute is not found and no default value has been given.

exception anyio.WouldBlock

Bases: Exception

Raised by X_nowait functions if X() would block.