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[[Unpack[TypeVarTuple]],Awaitable[TypeVar(T_Retval)]]) – a coroutine functionargs (
Unpack[TypeVarTuple]) – positional arguments tofuncbackend (
str) – name of the asynchronous event loop implementation – currently eitherasyncioortriobackend_options (
dict[str,Any] |None) – keyword arguments to call the backendrun()implementation with (documented here)
- Return type:
TypeVar(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.
- anyio.get_available_backends()
Test for the availability of built-in backends.
:return a tuple of the built-in backend names that were successfully imported
Added in version 4.12.
- anyio.get_cancelled_exc_class()
Return the current async library’s cancellation exception class.
- Raises:
NoEventLoopError – if no supported asynchronous event loop is running in the current thread
- Return type:
- async anyio.sleep(delay)
Pause the current task for the specified duration.
- async anyio.sleep_forever()
Pause the current task until it’s cancelled.
This is a shortcut for
sleep(math.inf).Added in version 3.1.
- Return type:
- async anyio.sleep_until(deadline)
Pause the current task until the given time.
- Parameters:
deadline (
float) – the absolute time to wake up at (according to the internal monotonic clock of the event loop)- Return type:
Added in version 3.1.
- anyio.current_time()
Return the current value of the event loop’s internal clock.
- Return type:
- Returns:
the clock value (seconds)
- Raises:
NoEventLoopError – if no supported asynchronous event loop is running in the current thread
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:
Typed attributes
- class anyio.TypedAttributeSet
Bases:
objectSuperclass for typed attribute collections.
Checks that every public attribute of every subclass has a type annotation.
- class anyio.TypedAttributeProvider
Bases:
objectBase class for classes that wish to provide typed extra attributes.
- extra(attribute, default=<object object>)
Return the value of the given typed extra attribute.
- Parameters:
attribute (
Any) – the attribute (member of aTypedAttributeSet) to look fordefault (
object) – 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
- Return type:
- property extra_attributes: Mapping[T_Attr, Callable[[], T_Attr]]
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).
Timeouts and cancellation
- anyio.move_on_after(delay, shield=False)
Create a cancel scope with a deadline that expires after the given delay.
- Parameters:
- Return type:
- Returns:
a cancel scope
- Raises:
NoEventLoopError – if no supported asynchronous event loop is running in the current thread
- anyio.fail_after(delay, shield=False)
Create a context manager which raises a
TimeoutErrorif does not finish in time.- Parameters:
- Returns:
a context manager that yields a cancel scope
- Return type:
- Raises:
NoEventLoopError – if no supported asynchronous event loop is running in the current thread
- 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 (or
float('inf')if there is no deadline in effect, orfloat('-inf')if the current scope has been cancelled)- Return type:
- Raises:
NoEventLoopError – if no supported asynchronous event loop is running in the current thread
- class anyio.CancelScope(*, deadline: float = inf, shield: bool = False)
Bases:
objectWraps a unit of work that can be made separately cancellable.
- Parameters:
deadline – The time (clock value) when this scope is cancelled automatically
shield –
Trueto shield the cancel scope from external cancellation
- Raises:
NoEventLoopError – if no supported asynchronous event loop is running in the current thread
- cancel(reason=None)
Cancel this scope immediately.
- property cancelled_caught: bool
Trueif this scope suppressed a cancellation exception it itself raised.This is typically used to check if any work was interrupted, or to see if the scope was cancelled due to its deadline being reached. The value will, however, only be
Trueif the cancellation was triggered by the scope itself (and not an outer scope).
Task groups
- anyio.create_task_group()
Create a task group.
- Return type:
- Returns:
a task group
- Raises:
NoEventLoopError – if no supported asynchronous event loop is running in the current thread
- class anyio.TaskHandle(coro, name)
Bases:
Generic[T_co]Returned from
TaskGroup.create_task(). Can be awaited on to get the return value of the task (or the raised exception). If the task was terminated by aBaseException,TaskFailedwill be raised (or its subclassTaskCancelledif the task was cancelled).Added in version 4.14.0.
- class Status(value)
Bases:
EnumThe status of a task handle.
- PENDING
The task has not finished yet.
- FINISHED
The task has finished with a return value.
- CANCELLING
The task has been cancelled but has not finished yet.
- CANCELLED
The task was cancelled and has finished since.
- FAILED
The task raised an exception.
- cancel()
Set the task to a cancelled state.
This will interrupt any interruptible asynchronous operation, and will cause any further awaits on this task to get immediately cancelled, unless done in a shielded cancel scope.
If the task has already finished, this method has no effect.
- Return type:
- property coro: Coroutine[Any, Any, T_co]
The coroutine object that was passed to
TaskGroup.create_task().
- property exception: BaseException | None
The exception raised by the task, or
Noneif it finished without raising.- Raises:
TaskNotFinished – if the task has not finished yet
TaskCancelled – if the task was cancelled
- property return_value: T_co
The return value of the task.
- Raises:
TaskNotFinished – if the task has not finished yet
TaskCancelled – if the task was cancelled
TaskFailed – if the task raised an exception
- property status: Status
The current status of the task.
Every task starts in the
PENDINGstate. If a task is cancelled while in this state, it will transition to theCANCELLINGstate. When the task finishes, it will transition to one of the three final states (FINISHED,FAILED, orCANCELLING) depending on the exception the task raised, if any. No other status transitions will happen.
- class anyio.abc.TaskGroup
Bases:
objectGroups several asynchronous tasks together.
- Variables:
cancel_scope (CancelScope) – the cancel scope inherited by all child tasks
Note
On asyncio, support for eager task factories is considered to be experimental. In particular, they don’t follow the usual semantics of new tasks being scheduled on the next iteration of the event loop, and may thus cause unexpected behavior in code that wasn’t written with such semantics in mind.
- cancel(reason=None)
Cancel this task group’s cancel scope immediately.
This is a shortcut for calling
.cancel_scope.cancel()on the task group.Added in version 4.14.0.
- create_task(coro, *, name=None, context=None)
Create a new task from a coroutine object and schedule it to run.
- Parameters:
- Return type:
TaskHandle[TypeVar(T_Retval)]- Returns:
a task handle
Added in version 4.14.0.
- abstractmethod async start(func, *args, name=None)
Start a new task and wait until it signals for readiness.
The target callable must accept a keyword argument
task_status(of typeTaskStatus). Awaiting on this method will return whatever was passed totask_status.started()(Noneby default).Note
The
TaskStatusclass is generic, and the type argument should indicate the type of the value that will be passed totask_status.started().- Parameters:
- Return type:
- Returns:
the value passed to
task_status.started()- Raises:
RuntimeError – if the task finishes without calling
task_status.started()
See also
Added in version 3.0.
- abstractmethod start_soon(func, *args, name=None)
Start a new task in this task group.
- Parameters:
- Return type:
Added in version 3.0.
Running code in worker threads
- async anyio.to_thread.run_sync(func, *args, abandon_on_cancel=False, cancellable=None, limiter=None)
Call the given function with the given arguments in a worker thread.
If the
abandon_on_canceloption 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[[Unpack[TypeVarTuple]],TypeVar(T_Retval)]) – a callableargs (
Unpack[TypeVarTuple]) – positional arguments for the callableabandon_on_cancel (
bool) –Trueto abandon the thread (leaving it to run unchecked on own) if the host task is cancelled,Falseto ignore cancellations in the host task until the operation has completed in the worker threadcancellable (
bool|None) – deprecated alias ofabandon_on_cancel; will overrideabandon_on_cancelif both parameters are passedlimiter (
CapacityLimiter|None) – capacity limiter to use to limit the total amount of threads running (if omitted, the default limiter is used)
- Raises:
NoEventLoopError – if no supported asynchronous event loop is running in the current thread
- Return type:
TypeVar(T_Retval)- Returns:
an awaitable that yields the return value of the function.
- anyio.to_thread.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
- Raises:
NoEventLoopError – if no supported asynchronous event loop is running in the current thread
Running code in subinterpreters
- async anyio.to_interpreter.run_sync(func, *args, limiter=None)
Call the given function with the given arguments in a subinterpreter.
Warning
On Python 3.13, the
concurrent.interpretersmodule was not yet available, so the code path for that Python version relies on an undocumented, private API. As such, it is recommended to not rely on this function for anything mission-critical on Python 3.13.- Parameters:
func (
Callable[[Unpack[TypeVarTuple]],TypeVar(T_Retval)]) – a callableargs (
Unpack[TypeVarTuple]) – the positional arguments for the callablelimiter (
CapacityLimiter|None) – capacity limiter to use to limit the total number of subinterpreters running (if omitted, the default limiter is used)
- Return type:
TypeVar(T_Retval)- Returns:
the result of the call
- Raises:
BrokenWorkerInterpreter – if there’s an internal error in a subinterpreter
- anyio.to_interpreter.current_default_interpreter_limiter()
Return the capacity limiter used by default to limit the number of concurrently running subinterpreters.
Defaults to the number of CPU cores.
- Return type:
- Returns:
a capacity limiter object
Running code in worker processes
- async anyio.to_process.run_sync(func, *args, cancellable=False, limiter=None)
Call the given function with the given arguments in a worker process.
If the
cancellableoption is enabled and the task waiting for its completion is cancelled, the worker process running it will be abruptly terminated using SIGKILL (orterminateProcess()on Windows).- Parameters:
func (
Callable[[Unpack[TypeVarTuple]],TypeVar(T_Retval)]) – a callableargs (
Unpack[TypeVarTuple]) – positional arguments for the callablecancellable (
bool) –Trueto allow cancellation of the operation while it’s runninglimiter (
CapacityLimiter|None) – capacity limiter to use to limit the total amount of processes running (if omitted, the default limiter is used)
- Raises:
NoEventLoopError – if no supported asynchronous event loop is running in the current thread
- Return type:
TypeVar(T_Retval)- Returns:
an awaitable that yields the return value of the function.
- anyio.to_process.current_default_process_limiter()
Return the capacity limiter that is used by default to limit the number of worker processes.
- Return type:
- Returns:
a capacity limiter object
Running asynchronous code from other threads
- anyio.from_thread.run(func, *args, token=None)
Call a coroutine function from a worker thread.
- Parameters:
func (
Callable[[Unpack[TypeVarTuple]],Awaitable[TypeVar(T_Retval)]]) – a coroutine functionargs (
Unpack[TypeVarTuple]) – positional arguments for the callabletoken (
EventLoopToken|None) – an event loop token to use to get back to the event loop thread (required if calling this function from outside an AnyIO worker thread)
- Return type:
TypeVar(T_Retval)- Returns:
the return value of the coroutine function
- Raises:
MissingTokenError – if no token was provided and called from outside an AnyIO worker thread
RunFinishedError – if the event loop tied to
tokenis no longer running
Changed in version 4.11.0: Added the
tokenparameter.
- anyio.from_thread.run_sync(func, *args, token=None)
Call a function in the event loop thread from a worker thread.
- Parameters:
func (
Callable[[Unpack[TypeVarTuple]],TypeVar(T_Retval)]) – a callableargs (
Unpack[TypeVarTuple]) – positional arguments for the callabletoken (
EventLoopToken|None) – an event loop token to use to get back to the event loop thread (required if calling this function from outside an AnyIO worker thread)
- Return type:
TypeVar(T_Retval)- Returns:
the return value of the callable
- Raises:
MissingTokenError – if no token was provided and called from outside an AnyIO worker thread
RunFinishedError – if the event loop tied to
tokenis no longer running
Changed in version 4.11.0: Added the
tokenparameter.
- anyio.from_thread.check_cancelled()
Check if the cancel scope of the host task’s running the current worker thread has been cancelled.
If the host task’s current cancel scope has indeed been cancelled, the backend-specific cancellation exception will be raised.
- Raises:
RuntimeError – if the current thread was not spawned by
to_thread.run_sync()- Return type:
- anyio.from_thread.start_blocking_portal(backend='asyncio', backend_options=None, *, name=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:
- Returns:
a context manager that yields a blocking portal
Changed in version 3.0: Usage as a context manager is now required.
- class anyio.from_thread.BlockingPortal
Bases:
objectAn object that lets external threads run code in an asynchronous event loop.
- Raises:
NoEventLoopError – if no supported asynchronous event loop is running in the current thread
- call(func, *args)
Call the given function in the event loop thread.
If the callable returns a coroutine object, it is awaited on.
- start_task(func, *args, name=None)
Start a task in the portal’s task group and wait until it signals for readiness.
This method works the same way as
abc.TaskGroup.start().- Parameters:
- Returns:
a tuple of (future, task_status_value) where the
task_status_valueis the value passed totask_status.started()from within the target function- Return type:
tuple[concurrent.futures.Future[T_Retval], Any]
Added in version 3.0.
- start_task_soon(func, *args, name=None)
Start a task in the portal’s task group.
The task will be run inside a cancel scope which can be cancelled by cancelling the returned future.
- Parameters:
- Returns:
a future that resolves with the return value of the callable if the task completes successfully, or with the exception raised in the task
- Raises:
RuntimeError – if the portal is not running or if this method is called from within the event loop thread
- Return type:
concurrent.futures.Future[T_Retval]
Added in version 3.0.
- 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().
- wrap_async_context_manager(cm)
Wrap an async context manager as a synchronous context manager via this portal.
Spawns a task that will call both
__aenter__()and__aexit__(), stopping in the middle until the synchronous context manager exits.- Parameters:
cm (
AbstractAsyncContextManager[TypeVar(T_co, covariant=True)]) – an asynchronous context manager- Return type:
AbstractContextManager[TypeVar(T_co, covariant=True)]- Returns:
a synchronous context manager
Added in version 2.1.
- class anyio.from_thread.BlockingPortalProvider(backend='asyncio', backend_options=None)
Bases:
objectA manager for a blocking portal. Used as a context manager. The first thread to enter this context manager causes a blocking portal to be started with the specific parameters, and the last thread to exit causes the portal to be shut down. Thus, there will be exactly one blocking portal running in this context as long as at least one thread has entered this context manager.
The parameters are the same as for
run().- Parameters:
Added in version 4.4.
Async file I/O
- async anyio.open_file(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None, *, limiter=None)
Open a file asynchronously.
Except for
limiter, the arguments are exactly the same as for the builtinopen().- Parameters:
limiter (
CapacityLimiter|None) – an optional capacity limiter to use with the file instead of the default one- Return type:
- Returns:
an asynchronous file object
Changed in version 4.14.0: Added the
limiterkeyword argument.
- anyio.wrap_file(file, *, limiter=None)
Wrap an existing file as an asynchronous file.
- Parameters:
limiter (
CapacityLimiter|None) – an optional capacity limiter to use with the file instead of the default one
- Return type:
AsyncFile[AnyStr]- Returns:
an asynchronous file object
Changed in version 4.14.0: Added the
limiterkeyword argument.
- class anyio.AsyncFile(fp, *, limiter=None)
Bases:
AsyncResource,GenericAn 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 open_file(...) as f: async for line in f: print(line)
- property limiter: CapacityLimiter | None
The capacity limiter used by this file object, if not the global limiter.
- class anyio.Path(*args, limiter=None)
Bases:
objectAn asynchronous version of
pathlib.Path.This class cannot be substituted for
pathlib.Pathorpathlib.PurePath, but it is compatible with theos.PathLikeinterface.It implements the Python 3.10 version of
pathlib.Pathinterface, except for the deprecatedlink_to()method.Some methods may be unavailable or have limited functionality, based on the Python version:
copy()(available on Python 3.14 or later)copy_into()(available on Python 3.14 or later)from_uri()(available on Python 3.13 or later)full_match()(available on Python 3.13 or later)info(available on Python 3.14 or later)is_junction()(available on Python 3.12 or later)match()(thecase_sensitiveparameter is only available on Python 3.13 or later)move()(available on Python 3.14 or later)move_into()(available on Python 3.14 or later)relative_to()(thewalk_upparameter is only available on Python 3.12 or later)walk()(available on Python 3.12 or later)
Any methods that do disk I/O need to be awaited on. These methods are:
Additionally, the following methods return an async iterator yielding
Pathobjects:Changed in version 4.14.0: Added the
limiterkeyword argument.- property limiter: CapacityLimiter | None
The capacity limiter used by this path, if not the global limiter.
Temporary files and directories
- async anyio.mkstemp(suffix=None, prefix=None, dir=None, text=False)
Asynchronously create a temporary file and return an OS-level handle and the file name.
This function wraps tempfile.mkstemp and executes it in a background thread.
- Parameters:
- Return type:
- Returns:
A tuple containing the file descriptor and the file name.
- async anyio.mkdtemp(suffix=None, prefix=None, dir=None)
Asynchronously create a temporary directory and return its path.
This function wraps tempfile.mkdtemp and executes it in a background thread.
- Parameters:
- Return type:
- Returns:
The path of the created temporary directory.
- async anyio.gettempdir()
Asynchronously return the name of the directory used for temporary files.
This function wraps tempfile.gettempdir and executes it in a background thread.
- Return type:
- Returns:
The path of the temporary directory as a string.
- async anyio.gettempdirb()
Asynchronously return the name of the directory used for temporary files in bytes.
This function wraps tempfile.gettempdirb and executes it in a background thread.
- Return type:
- Returns:
The path of the temporary directory as bytes.
- class anyio.TemporaryFile(mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, *, errors=None)
Bases:
GenericAn asynchronous temporary file that is automatically created and cleaned up.
This class provides an asynchronous context manager interface to a temporary file. The file is created using Python’s standard tempfile.TemporaryFile function in a background thread, and is wrapped as an asynchronous file using AsyncFile.
- Parameters:
mode (OpenTextMode | OpenBinaryMode) – The mode in which the file is opened. Defaults to “w+b”.
buffering (int) – The buffering policy (-1 means the default buffering).
encoding (str | None) – The encoding used to decode or encode the file. Only applicable in text mode.
newline (str | None) – Controls how universal newlines mode works (only applicable in text mode).
suffix (str | None) – The suffix for the temporary file name.
prefix (str | None) – The prefix for the temporary file name.
dir (str | None) – The directory in which the temporary file is created.
errors (str | None) – The error handling scheme used for encoding/decoding errors.
- class anyio.NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True, *, errors=None, delete_on_close=True)
Bases:
GenericAn asynchronous named temporary file that is automatically created and cleaned up.
This class provides an asynchronous context manager for a temporary file with a visible name in the file system. It uses Python’s standard
NamedTemporaryFile()function and wraps the file object withAsyncFilefor asynchronous operations.- Parameters:
mode (OpenBinaryMode | OpenTextMode) – The mode in which the file is opened. Defaults to “w+b”.
buffering (int) – The buffering policy (-1 means the default buffering).
encoding (str | None) – The encoding used to decode or encode the file. Only applicable in text mode.
newline (str | None) – Controls how universal newlines mode works (only applicable in text mode).
suffix (str | None) – The suffix for the temporary file name.
prefix (str | None) – The prefix for the temporary file name.
dir (str | None) – The directory in which the temporary file is created.
delete (bool) – Whether to delete the file when it is closed.
errors (str | None) – The error handling scheme used for encoding/decoding errors.
delete_on_close (bool) – (Python 3.12+) Whether to delete the file on close.
- class anyio.SpooledTemporaryFile(max_size=0, mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None, *, errors=None)
Bases:
AsyncFileAn asynchronous spooled temporary file that starts in memory and is spooled to disk.
This class provides an asynchronous interface to a spooled temporary file, much like Python’s standard
SpooledTemporaryFile. It supports asynchronous write operations and provides a method to force a rollover to disk.- Parameters:
max_size (int) – Maximum size in bytes before the file is rolled over to disk.
mode (OpenBinaryMode | OpenTextMode) – The mode in which the file is opened. Defaults to “w+b”.
buffering (int) – The buffering policy (-1 means the default buffering).
encoding (str | None) – The encoding used to decode or encode the file (text mode only).
newline (str | None) – Controls how universal newlines mode works (text mode only).
suffix (str | None) – The suffix for the temporary file name.
prefix (str | None) – The prefix for the temporary file name.
dir (str | None) – The directory in which the temporary file is created.
errors (str | None) – The error handling scheme used for encoding/decoding errors.
- async write(b)
Asynchronously write data to the spooled temporary file.
If the file has not yet been rolled over, the data is written synchronously, and a rollover is triggered if the size exceeds the maximum size.
- Parameters:
s – The data to write.
- Return type:
int
- Returns:
The number of bytes written.
- Raises:
RuntimeError – If the underlying file is not initialized.
- async writelines(lines)
Asynchronously write a list of lines to the spooled temporary file.
If the file has not yet been rolled over, the lines are written synchronously, and a rollover is triggered if the size exceeds the maximum size.
- Parameters:
lines (
Iterable[str] |Iterable[ReadableBuffer]) – An iterable of lines to write.- Raises:
RuntimeError – If the underlying file is not initialized.
- Return type:
- class anyio.TemporaryDirectory(suffix=None, prefix=None, dir=None, *, ignore_cleanup_errors=False, delete=True)
Bases:
GenericAn asynchronous temporary directory that is created and cleaned up automatically.
This class provides an asynchronous context manager for creating a temporary directory. It wraps Python’s standard
TemporaryDirectoryto perform directory creation and cleanup operations in a background thread.- Parameters:
suffix (
Optional[AnyStr]) – Suffix to be added to the temporary directory name.prefix (
Optional[AnyStr]) – Prefix to be added to the temporary directory name.dir (
Optional[AnyStr]) – The parent directory where the temporary directory is created.ignore_cleanup_errors (
bool) – Whether to ignore errors during cleanupdelete (
bool) – Whether to delete the directory upon closing (Python 3.12+).
Context manager mix-in classes
- class anyio.ContextManagerMixin
Bases:
objectMixin class providing context manager functionality via a generator-based implementation.
This class allows you to implement a context manager via
__contextmanager__()which should return a generator. The mechanics are meant to mirror those of@contextmanager.Note
Classes using this mix-in are not reentrant as context managers, meaning that once you enter it, you can’t re-enter before first exiting it.
See also
- abstractmethod __contextmanager__()
Implement your context manager logic here.
This method must be decorated with
@contextmanager.Note
Remember that the
yieldwill raise any exception raised in the enclosed context block, so use afinally:block to clean up resources!- Return type:
- Returns:
a context manager object
- class anyio.AsyncContextManagerMixin
Bases:
objectMixin class providing async context manager functionality via a generator-based implementation.
This class allows you to implement a context manager via
__asynccontextmanager__(). The mechanics are meant to mirror those of@asynccontextmanager.Note
Classes using this mix-in are not reentrant as context managers, meaning that once you enter it, you can’t re-enter before first exiting it.
See also
- abstractmethod __asynccontextmanager__()
Implement your async context manager logic here.
This method must be decorated with
@asynccontextmanager.Note
Remember that the
yieldwill raise any exception raised in the enclosed context block, so use afinally:block to clean up resources!- Return type:
- Returns:
an async context manager object
Streams and stream wrappers
- anyio.create_memory_object_stream(max_buffer_size: float = 0, item_type: object = None) tuple[MemoryObjectSendStream[T_Item], MemoryObjectReceiveStream[T_Item]]
Create a memory object stream.
The stream’s item type can be annotated like
create_memory_object_stream[T_Item]().- Parameters:
max_buffer_size – number of items held in the buffer until
send()starts blockingitem_type –
old way of marking the streams with the right generic type for static typing (does nothing on AnyIO 4)
Deprecated since version 4.0: Use
create_memory_object_stream[YourItemType](...)instead.
- Returns:
a tuple of (send stream, receive stream)
- class anyio.abc.UnreliableObjectReceiveStream
Bases:
Generic[T_co],AsyncResource,TypedAttributeProviderAn 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.
- abstractmethod async receive()
Receive the next item.
- Raises:
ClosedResourceError – if the receive stream has been explicitly closed
EndOfStream – if this stream has been closed from the other end
BrokenResourceError – if this stream has been rendered unusable due to external causes
- Return type:
TypeVar(T_co, covariant=True)
- class anyio.abc.UnreliableObjectSendStream
Bases:
Generic[T_contra],AsyncResource,TypedAttributeProviderAn 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.
- abstractmethod async send(item)
Send an item to the peer(s).
- Parameters:
item (
TypeVar(T_contra, contravariant=True)) – the item to send- Raises:
ClosedResourceError – if the send stream has been explicitly closed
BrokenResourceError – if this stream has been rendered unusable due to external causes
- Return type:
- class anyio.abc.UnreliableObjectStream
Bases:
UnreliableObjectReceiveStream[T_Item],UnreliableObjectSendStream[T_Item]A bidirectional message stream which does not guarantee the order or reliability of message delivery.
- class anyio.abc.ObjectReceiveStream
Bases:
UnreliableObjectReceiveStream[T_co]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:
UnreliableObjectSendStream[T_contra]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:
ObjectReceiveStream[T_Item],ObjectSendStream[T_Item],UnreliableObjectStream[T_Item]A bidirectional message stream which guarantees the order and reliability of message delivery.
- class anyio.abc.ByteReceiveStream
Bases:
AsyncResource,TypedAttributeProviderAn 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.
- abstractmethod async receive(max_bytes=65536)
Receive at most
max_bytesbytes from the peer.Note
Implementers of this interface should not return an empty
bytesobject, and users should ignore them.- Parameters:
max_bytes (
int) – maximum number of bytes to receive- Return type:
- Returns:
the received bytes
- Raises:
EndOfStream – if this stream has been closed from the other end
- class anyio.abc.ByteSendStream
Bases:
AsyncResource,TypedAttributeProviderAn interface for sending bytes to a single peer.
- class anyio.abc.ByteStream
Bases:
ByteReceiveStream,ByteSendStreamA bidirectional byte stream.
- class anyio.abc.Listener
Bases:
Generic[T_co],AsyncResource,TypedAttributeProviderAn interface for objects that let you accept incoming connections.
- abstractmethod async serve(handler, task_group=None)
Accept incoming connections as they come in and start tasks to handle them.
- Parameters:
- Return type:
- class anyio.abc.ObjectStreamConnectable
Bases:
Generic[T_co]- abstractmethod async connect()
Connect to the remote endpoint.
- Return type:
ObjectStream[TypeVar(T_co, covariant=True)]- Returns:
an object stream connected to the remote end
- Raises:
ConnectionFailed – if the connection fails
- class anyio.abc.ByteStreamConnectable
Bases:
object- abstractmethod async connect()
Connect to the remote endpoint.
- Return type:
- Returns:
a bytestream connected to the remote end
- Raises:
ConnectionFailed – if the connection fails
- anyio.abc.AnyUnreliableByteReceiveStream
alias of
UnreliableObjectReceiveStream[bytes] |ByteReceiveStream
- anyio.abc.AnyUnreliableByteSendStream
alias of
UnreliableObjectSendStream[bytes] |ByteSendStream
- anyio.abc.AnyUnreliableByteStream
alias of
UnreliableObjectStream[bytes] |ByteStream
- anyio.abc.AnyByteReceiveStream
alias of
ObjectReceiveStream[bytes] |ByteReceiveStream
- anyio.abc.AnyByteSendStream
alias of
ObjectSendStream[bytes] |ByteSendStream
- anyio.abc.AnyByteStream
alias of
ObjectStream[bytes] |ByteStream
- anyio.abc.AnyByteStreamConnectable
alias of
ObjectStreamConnectable[bytes] |ByteStreamConnectable
- class anyio.streams.buffered.BufferedByteReceiveStream(receive_stream)
Bases:
ByteReceiveStreamWraps any bytes-based receive stream and uses a buffer to provide sophisticated receiving capabilities in the form of a byte stream.
- property extra_attributes: Mapping[Any, Callable[[], Any]]
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).
- feed_data(data, /)
Append data directly into the buffer.
Any data in the buffer will be consumed by receive operations before receiving anything from the wrapped stream.
- Parameters:
data (
Iterable[SupportsIndex]) – the data to append to the buffer (can be bytes or anything else that supports__index__())- Return type:
- async receive(max_bytes=65536)
Receive at most
max_bytesbytes from the peer.Note
Implementers of this interface should not return an empty
bytesobject, and users should ignore them.- Parameters:
max_bytes (
int) – maximum number of bytes to receive- Return type:
- 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:
- 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 streammax_bytes (
int) – maximum number of bytes that will be read before raisingDelimiterNotFound
- Return type:
- Returns:
the bytes read (not 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.buffered.BufferedByteStream(stream)
Bases:
BufferedByteReceiveStream,ByteStreamA full-duplex variant of
BufferedByteReceiveStream. All writes are passed through to the wrapped stream as-is.- async send(item)
Send the given bytes to the peer.
- class anyio.streams.file.FileStreamAttribute
Bases:
TypedAttributeSet
- class anyio.streams.file.FileReadStream(file)
Bases:
_BaseFileStream,ByteReceiveStreamA byte stream that reads from a file in the file system.
Added in version 3.0.
- async classmethod from_path(path)
Create a file read stream by opening the given file.
- Parameters:
- Return type:
- async receive(max_bytes=65536)
Receive at most
max_bytesbytes from the peer.Note
Implementers of this interface should not return an empty
bytesobject, and users should ignore them.- Parameters:
max_bytes (
int) – maximum number of bytes to receive- Return type:
- Returns:
the received bytes
- Raises:
EndOfStream – if this stream has been closed from the other end
- async seek(position, whence=0)
Seek the file to the given position.
See also
Note
Not all file descriptors are seekable.
- class anyio.streams.file.FileWriteStream(file)
Bases:
_BaseFileStream,ByteSendStreamA byte stream that writes to a file in the file system.
Added in version 3.0.
- async classmethod from_path(path, append=False)
Create a file write stream by opening the given file for writing.
- Parameters:
- Return type:
- class anyio.streams.memory.MemoryObjectReceiveStream(_state)
Bases:
Generic[T_co],ObjectReceiveStream[T_co]- 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[TypeVar(T_co, covariant=True)]- Returns:
the cloned stream
- close()
Close the stream.
This works the exact same way as
aclose(), but is provided as a special case for the benefit of synchronous callbacks.- Return type:
- async receive()
Receive the next item.
- Raises:
ClosedResourceError – if the receive stream has been explicitly closed
EndOfStream – if this stream has been closed from the other end
BrokenResourceError – if this stream has been rendered unusable due to external causes
- Return type:
TypeVar(T_co, covariant=True)
- receive_nowait()
Receive the next item if it can be done without waiting.
- Return type:
TypeVar(T_co, covariant=True)- 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
- statistics()
Return statistics about the current state of this stream.
Added in version 3.0.
- Return type:
- class anyio.streams.memory.MemoryObjectSendStream(_state)
Bases:
Generic[T_contra],ObjectSendStream[T_contra]- 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[TypeVar(T_contra, contravariant=True)]- Returns:
the cloned stream
- close()
Close the stream.
This works the exact same way as
aclose(), but is provided as a special case for the benefit of synchronous callbacks.- Return type:
- async send(item)
Send an item to the stream.
If the buffer is full, this method blocks until there is again room in the buffer or the item can be sent directly to a receiver.
- Parameters:
item (
TypeVar(T_contra, contravariant=True)) – the item to send- Raises:
ClosedResourceError – if this send stream has been closed
BrokenResourceError – if the stream has been closed from the receiving end
- Return type:
- send_nowait(item)
Send an item immediately if it can be done without waiting.
- Parameters:
item (
TypeVar(T_contra, contravariant=True)) – the item to send- Raises:
ClosedResourceError – if this send stream has been closed
BrokenResourceError – if the stream has been closed from the receiving end
WouldBlock – if the buffer is full and there are no tasks waiting to receive
- Return type:
- statistics()
Return statistics about the current state of this stream.
Added in version 3.0.
- Return type:
- class anyio.streams.memory.MemoryObjectStreamStatistics(current_buffer_used, max_buffer_size, open_send_streams, open_receive_streams, tasks_waiting_send, tasks_waiting_receive)
Bases:
NamedTuple-
tasks_waiting_receive:
int number of tasks blocked on
MemoryObjectReceiveStream.receive()
-
tasks_waiting_send:
int number of tasks blocked on
MemoryObjectSendStream.send()
-
tasks_waiting_receive:
- class anyio.streams.stapled.MultiListener(listeners)
Bases:
Generic[T_Stream],Listener[T_Stream]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
- property extra_attributes: Mapping[Any, Callable[[], Any]]
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 start tasks to handle them.
- Parameters:
- Return type:
- class anyio.streams.stapled.StapledByteStream(send_stream, receive_stream)
Bases:
ByteStreamCombines 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:
send_stream (ByteSendStream) – the sending byte stream
receive_stream (ByteReceiveStream) – the receiving byte stream
- property extra_attributes: Mapping[Any, Callable[[], Any]]
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_bytesbytes from the peer.Note
Implementers of this interface should not return an empty
bytesobject, and users should ignore them.- Parameters:
max_bytes (
int) – maximum number of bytes to receive- Return type:
- 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.
- class anyio.streams.stapled.StapledObjectStream(send_stream, receive_stream)
Bases:
Generic[T_Item],ObjectStream[T_Item]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:
send_stream (ObjectSendStream) – the sending object stream
receive_stream (ObjectReceiveStream) – the receiving object stream
- property extra_attributes: Mapping[Any, Callable[[], Any]]
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:
ClosedResourceError – if the receive stream has been explicitly closed
EndOfStream – if this stream has been closed from the other end
BrokenResourceError – if this stream has been rendered unusable due to external causes
- Return type:
TypeVar(T_Item)
- async send(item)
Send an item to the peer(s).
- Parameters:
item (
TypeVar(T_Item)) – the item to send- Raises:
ClosedResourceError – if the send stream has been explicitly closed
BrokenResourceError – if this stream has been rendered unusable due to external causes
- Return type:
- class anyio.streams.text.TextReceiveStream(transport_stream, encoding='utf-8', errors='strict')
Bases:
ObjectReceiveStream[str]Stream wrapper that decodes bytes to strings using the given encoding.
Decoding is done using
IncrementalDecoderwhich returns any completely received unicode characters as soon as they come in.- Parameters:
transport_stream (
Union[ObjectReceiveStream[bytes],ByteReceiveStream]) – any bytes-based receive streamencoding (
InitVar) – character encoding to use for decoding bytes to strings (defaults toutf-8)errors (
InitVar) – handling scheme for decoding errors (defaults tostrict; see the codecs module documentation for a comprehensive list of options)
- property extra_attributes: Mapping[Any, Callable[[], Any]]
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:
ClosedResourceError – if the receive stream has been explicitly closed
EndOfStream – if this stream has been closed from the other end
BrokenResourceError – if this stream has been rendered unusable due to external causes
- Return type:
- class anyio.streams.text.TextSendStream(transport_stream, encoding='utf-8', errors='strict')
Bases:
ObjectSendStream[str]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)
- property extra_attributes: Mapping[Any, Callable[[], Any]]
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:
ClosedResourceError – if the send stream has been explicitly closed
BrokenResourceError – if this stream has been rendered unusable due to external causes
- Return type:
- class anyio.streams.text.TextStream(transport_stream, encoding='utf-8', errors='strict')
Bases:
ObjectStream[str]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)
- property extra_attributes: Mapping[Any, Callable[[], Any]]
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:
ClosedResourceError – if the receive stream has been explicitly closed
EndOfStream – if this stream has been closed from the other end
BrokenResourceError – if this stream has been rendered unusable due to external causes
- Return type:
- async send(item)
Send an item to the peer(s).
- Parameters:
item (
str) – the item to send- Raises:
ClosedResourceError – if the send stream has been explicitly closed
BrokenResourceError – if this stream has been rendered unusable due to external causes
- Return type:
- class anyio.streams.text.TextConnectable(connectable)
Bases:
ObjectStreamConnectable[str]- async connect()
Connect to the remote endpoint.
- Return type:
- Returns:
an object stream connected to the remote end
- Raises:
ConnectionFailed – if the connection fails
- class anyio.streams.tls.TLSAttribute
Bases:
TypedAttributeSetContains Transport Layer Security related attributes.
ciphers shared by the client during the TLS handshake (
Noneif this is the client side)
- class anyio.streams.tls.TLSStream(transport_stream, standard_compatible, _ssl_object, _read_bio, _write_bio)
Bases:
ByteStreamA stream wrapper that encrypts all sent data and decrypts received data.
This class has no public initializer; use
wrap()instead. All extra attributes fromTLSAttributeare supported.- Variables:
transport_stream (AnyByteStream) – the wrapped stream
- property extra_attributes: Mapping[Any, Callable[[], Any]]
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_bytesbytes from the peer.Note
Implementers of this interface should not return an empty
bytesobject, and users should ignore them.- Parameters:
max_bytes (
int) – maximum number of bytes to receive- Return type:
- 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.
- 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:
- 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 wrapserver_side (
bool|None) –Trueif this is the server side of the connection,Falseif this is the client side (if omitted, will be set toFalseifhostnamehas been provided,Falseotherwise). Used only to create a default context when an explicit context has not been provided.hostname (
str|None) – host name of the peer (if host name checking is desired)ssl_context (
SSLContext|None) – the SSLContext object to use (if not provided, a secure default will be created)standard_compatible (
bool) – ifFalse, 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:
- class anyio.streams.tls.TLSListener(listener, ssl_context, standard_compatible=True, handshake_timeout=30)
-
A convenience listener that wraps another listener and auto-negotiates a TLS session on every accepted connection.
If the TLS handshake times out or raises an exception,
handle_handshake_error()is called to do whatever post-mortem processing is deemed necessary.Supports only the
standard_compatibleextra attribute.- Parameters:
listener (Listener) – the listener to wrap
ssl_context (
SSLContext) – the SSL context objectstandard_compatible (
bool) – a flag passed through toTLSStream.wrap()handshake_timeout (
float) – time limit for the TLS handshake (passed tofail_after())
- property extra_attributes: Mapping[Any, Callable[[], Any]]
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 static handle_handshake_error(exc, stream)
Handle an exception raised during the TLS handshake.
This method does 3 things:
Forcefully closes the original stream
Logs the exception (unless it was a cancellation exception) using the
anyio.streams.tlsloggerReraises the exception if it was a base exception or a cancellation exception
- Parameters:
exc (
BaseException) – the exceptionstream (
Union[ObjectStream[bytes],ByteStream]) – the original stream
- Return type:
- async serve(handler, task_group=None)
Accept incoming connections as they come in and start tasks to handle them.
- Parameters:
- Return type:
- class anyio.streams.tls.TLSConnectable(connectable, *, hostname=None, ssl_context=None, standard_compatible=True)
Bases:
ByteStreamConnectableWraps another connectable and does TLS negotiation after a successful connection.
- Parameters:
connectable (
Union[ObjectStreamConnectable[bytes],ByteStreamConnectable]) – the connectable to wraphostname (
str|None) – host name of the server (if host name checking is desired)ssl_context (
SSLContext|None) – the SSLContext object to use (if not provided, a secure default will be created)standard_compatible (
bool) – ifFalse, skip the closing handshake when closing the connection, and don’t raise an exception if the server does the same
- async connect()
Connect to the remote endpoint.
- Return type:
- Returns:
a bytestream connected to the remote end
- Raises:
ConnectionFailed – if the connection fails
Sockets and networking
- anyio.as_connectable(remote, /, *, tls=False, ssl_context=None, tls_hostname=None, tls_standard_compatible=True)
Return a byte stream connectable from the given object.
If a bytestream connectable is given, it is returned unchanged. If a tuple of (host, port) is given, a TCP connectable is returned. If a string or bytes path is given, a UNIX connectable is returned.
If
tls=True, the connectable will be wrapped in aTLSConnectable.- Parameters:
remote (
ByteStreamConnectable|tuple[str|IPv4Address|IPv6Address,int] |str|bytes|PathLike[str]) – a connectable, a tuple of (host, port) or a path to a UNIX sockettls (
bool) – ifTrue, wrap the plaintext connectable in aTLSConnectable, using the provided TLS settings)ssl_context (
SSLContext|None) – iftls=True, the SSLContext object to use (if not provided, a secure default will be created)tls_hostname (
str|None) – iftls=True, host name of the server to use for checking the server certificate (defaults to the host portion of the address for TCP connectables)tls_standard_compatible (
bool) – ifFalseandtls=True, makes the TLS stream skip the closing handshake when closing the connection, so it won’t raise an exception if the server does the same
- Return type:
- async anyio.connect_tcp(remote_host, remote_port, *, local_host=None, local_port=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
remote_hostis 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_contextortls_hostnameis notNone, or iftlsisTrue.- Parameters:
remote_host (
str|IPv4Address|IPv6Address) – the IP address or host name to connect toremote_port (
int) – port on the target host to connect tolocal_host (
str|IPv4Address|IPv6Address|None) – the interface address or name to bind the socket to before connectinglocal_port (
int|None) – the local port to bind to (requireslocal_hostto also be set)tls (
bool) –Trueto do a TLS handshake with the connected stream and return aTLSStreaminsteadssl_context (
SSLContext|None) – the SSL context object to use (if omitted, a default context is created)tls_standard_compatible (
bool) – IfTrue, performs the TLS shutdown handshake before closing the stream and requires that the server does this as well. Otherwise,SSLEOFErrormay be raised during reads from the stream. Some protocols, such as HTTP, require this option to beFalse. Seewrap_socket()for details.tls_hostname (
str|None) – host name to check the server certificate against (defaults to the value ofremote_host)happy_eyeballs_delay (
float) – delay (in seconds) before starting the next connection attempt
- Return type:
- Returns:
a socket stream object if no TLS handshake was done, otherwise a TLS stream
- Raises:
ConnectionFailed – if the connection fails
- async anyio.connect_unix(path)
Connect to the given UNIX socket.
Not available on Windows.
- Parameters:
- Return type:
- Returns:
a socket stream object
- Raises:
ConnectionFailed – if the connection fails
- async anyio.create_tcp_listener(*, local_host=None, local_port=0, family=AddressFamily.AF_UNSPEC, backlog=65536, reuse_port=False)
Create a TCP socket listener.
- Parameters:
local_port (
int) – port number to listen onlocal_host (
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.0for IPv4 or::for IPv6.family (
Literal[<AddressFamily.AF_UNSPEC: 0>,<AddressFamily.AF_INET: 2>,<AddressFamily.AF_INET6: 10>]) – address family (used iflocal_hostwas omitted)backlog (
int) – maximum number of queued incoming connections (up to a maximum of 2**16, or 65536)reuse_port (
bool) –Trueto allow multiple sockets to bind to the same address/port (not supported on Windows)
- Return type:
- Returns:
a multi-listener object containing one or more socket listeners
- Raises:
OSError – if there’s an error creating a socket, or binding to one or more interfaces failed
- async anyio.create_unix_listener(path, *, mode=None, backlog=65536)
Create a UNIX socket listener.
Not available on Windows.
- Parameters:
- Return type:
- Returns:
a listener object
Changed in version 3.0: If a socket already exists on the file system in the given path, it will be removed first.
- async anyio.create_udp_socket(family=AddressFamily.AF_UNSPEC, *, local_host=None, local_port=0, reuse_port=False)
Create a UDP socket.
If
porthas 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_INETorAF_INET6) – automatically determined fromlocal_hostif omittedlocal_host (
str|IPv4Address|IPv6Address|None) – IP address or host name of the local interface to bind tolocal_port (
int) – local port to bind toreuse_port (
bool) –Trueto allow multiple sockets to bind to the same address/port (not supported on Windows)
- Return type:
- Returns:
a UDP socket
- async anyio.create_connected_udp_socket(remote_host, remote_port, *, family=AddressFamily.AF_UNSPEC, 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, an any packets sent from other sources are dropped.
- Parameters:
remote_host (
str|IPv4Address|IPv6Address) – remote host to set as the default targetremote_port (
int) – port on the remote host to set as the default targetfamily (
Literal[<AddressFamily.AF_UNSPEC: 0>,<AddressFamily.AF_INET: 2>,<AddressFamily.AF_INET6: 10>]) – address family (AF_INETorAF_INET6) – automatically determined fromlocal_hostorremote_hostif omittedlocal_host (
str|IPv4Address|IPv6Address|None) – IP address or host name of the local interface to bind tolocal_port (
int) – local port to bind toreuse_port (
bool) –Trueto allow multiple sockets to bind to the same address/port (not supported on Windows)
- Return type:
- 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:
- Return type:
list[tuple[AddressFamily,SocketKind,int,str,tuple[str,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)
- Raises:
NoEventLoopError – if no supported asynchronous event loop is running in the current thread
See also
- anyio.wait_readable(obj)
Wait until the given object has data to be read.
On Unix systems,
objmust either be an integer file descriptor, or else an object with a.fileno()method which returns an integer file descriptor. Any kind of file descriptor can be passed, though the exact semantics will depend on your kernel. For example, this probably won’t do anything useful for on-disk files.On Windows systems,
objmust either be an integerSOCKEThandle, or else an object with a.fileno()method which returns an integerSOCKEThandle. File descriptors aren’t supported, and neither are handles that refer to anything besides aSOCKET.On backends where this functionality is not natively provided (asyncio
ProactorEventLoopon Windows), it is provided using a separate selector thread which is set to shut down when the interpreter shuts down.Warning
Don’t use this on raw sockets that have been wrapped by any higher level constructs like socket streams!
- Parameters:
obj (
object) – an object with a.fileno()method or an integer handle- Raises:
ClosedResourceError – if the object was closed while waiting for the object to become readable
BusyResourceError – if another task is already waiting for the object to become readable
NoEventLoopError – if no supported asynchronous event loop is running in the current thread
- Return type:
- anyio.wait_socket_readable(sock)
Deprecated since version 4.7.0: Use
wait_readable()instead.Wait until the given socket has data to be read.
Warning
Only use this on raw sockets that have not been wrapped by any higher level constructs like socket streams!
- 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
NoEventLoopError – if no supported asynchronous event loop is running in the current thread
- Return type:
- anyio.wait_socket_writable(sock)
Deprecated since version 4.7.0: Use
wait_writable()instead.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+).
Warning
Only use this on raw sockets that have not been wrapped by any higher level constructs like socket streams!
- 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
NoEventLoopError – if no supported asynchronous event loop is running in the current thread
- Return type:
- anyio.wait_writable(obj)
Wait until the given object can be written to.
- Parameters:
obj (
FileDescriptorLike) – an object with a.fileno()method or an integer handle- Raises:
ClosedResourceError – if the object was closed while waiting for the object to become writable
BusyResourceError – if another task is already waiting for the object to become writable
NoEventLoopError – if no supported asynchronous event loop is running in the current thread
- Return type:
See also
See the documentation of
wait_readable()for the definition ofobjand notes on backend compatibility.Warning
Don’t use this on raw sockets that have been wrapped by any higher level constructs like socket streams!
- class anyio.abc.SocketAttribute
Bases:
TypedAttributeSet- family: socket.AddressFamily
the address family of the underlying socket
- raw_socket: socket.socket
the underlying stdlib socket object
- class anyio.abc.SocketStream
Bases:
ByteStream,_SocketProviderTransports bytes over a socket.
Supports all relevant extra attributes from
SocketAttribute.- async classmethod from_socket(sock_or_fd)
Wrap an existing socket object or file descriptor as a socket stream.
The newly created socket wrapper takes ownership of the socket being passed in. The existing socket must already be connected.
- class anyio.abc.SocketListener
Bases:
Listener[SocketStream],_SocketProviderListens to incoming socket connections.
Supports all relevant extra attributes from
SocketAttribute.- abstractmethod async accept()
Accept an incoming connection.
- Return type:
- async classmethod from_socket(sock_or_fd)
Wrap an existing socket object or file descriptor as a socket listener.
The newly created listener takes ownership of the socket being passed in.
- async serve(handler, task_group=None)
Accept incoming connections as they come in and start tasks to handle them.
- Parameters:
handler (
Callable[[SocketStream],Any]) – a callable that will be used to handle each accepted connectiontask_group (
TaskGroup|None) – the task group that will be used to start tasks for handling each accepted connection (if omitted, an ad-hoc task group will be created)
- Return type:
- class anyio.abc.UDPSocket
Bases:
UnreliableObjectStream[tuple[bytes,tuple[str,int]]],_SocketProviderRepresents an unconnected UDP socket.
Supports all relevant extra attributes from
SocketAttribute.- async classmethod from_socket(sock_or_fd)
Wrap an existing socket object or file descriptor as a UDP socket.
The newly created socket wrapper takes ownership of the socket being passed in. The existing socket must be bound to a local address.
- class anyio.abc.ConnectedUDPSocket
Bases:
UnreliableObjectStream[bytes],_SocketProviderRepresents an connected UDP socket.
Supports all relevant extra attributes from
SocketAttribute.- async classmethod from_socket(sock_or_fd)
Wrap an existing socket object or file descriptor as a connected UDP socket.
The newly created socket wrapper takes ownership of the socket being passed in. The existing socket must already be connected.
- class anyio.abc.UNIXSocketStream
Bases:
SocketStream- async classmethod from_socket(sock_or_fd)
Wrap an existing socket object or file descriptor as a UNIX socket stream.
The newly created socket wrapper takes ownership of the socket being passed in. The existing socket must already be connected.
- abstractmethod async receive_fds(msglen, maxfds)
Receive file descriptors along with a message from the peer.
- class anyio.abc.UNIXDatagramSocket
Bases:
UnreliableObjectStream[tuple[bytes,str]],_SocketProviderRepresents an unconnected Unix datagram socket.
Supports all relevant extra attributes from
SocketAttribute.- async classmethod from_socket(sock_or_fd)
Wrap an existing socket object or file descriptor as a UNIX datagram socket.
The newly created socket wrapper takes ownership of the socket being passed in.
- class anyio.abc.ConnectedUNIXDatagramSocket
Bases:
UnreliableObjectStream[bytes],_SocketProviderRepresents a connected Unix datagram socket.
Supports all relevant extra attributes from
SocketAttribute.- async classmethod from_socket(sock_or_fd)
Wrap an existing socket object or file descriptor as a connected UNIX datagram socket.
The newly created socket wrapper takes ownership of the socket being passed in. The existing socket must already be connected.
- class anyio.TCPConnectable(host, port)
Bases:
ByteStreamConnectableConnects to a TCP server at the given host and port.
- Parameters:
host (
str|IPv4Address|IPv6Address) – host name or IP address of the serverport (
int) – TCP port number of the server
- async connect()
Connect to the remote endpoint.
- Return type:
- Returns:
a bytestream connected to the remote end
- Raises:
ConnectionFailed – if the connection fails
- class anyio.UNIXConnectable(path)
Bases:
ByteStreamConnectableConnects to a UNIX domain socket at the given path.
- Parameters:
path (
str|bytes|PathLike[str] |PathLike[bytes]) – the file system path of the socket
- async connect()
Connect to the remote endpoint.
- Return type:
- Returns:
a bytestream connected to the remote end
- Raises:
ConnectionFailed – if the connection fails
Subprocesses
- async anyio.run_process(command, *, input=None, stdin=None, stdout=-1, stderr=-1, check=True, cwd=None, env=None, startupinfo=None, creationflags=0, start_new_session=False, pass_fds=(), user=None, group=None, extra_groups=None, umask=-1)
Run an external command in a subprocess and wait until it completes.
See also
- Parameters:
command (
str|bytes|PathLike[str] |PathLike[bytes] |Sequence[str|bytes|PathLike[str] |PathLike[bytes]]) – either a string to pass to the shell, or an iterable of strings containing the executable name or path and its argumentsinput (
bytes|None) – bytes passed to the standard input of the subprocessstdin (
Union[int,IO[Any],None]) – one ofsubprocess.PIPE,subprocess.DEVNULL, a file-like object, or None;inputoverrides thisstdout (
Union[int,IO[Any],None]) – one ofsubprocess.PIPE,subprocess.DEVNULL, a file-like object, or Nonestderr (
Union[int,IO[Any],None]) – one ofsubprocess.PIPE,subprocess.DEVNULL,subprocess.STDOUT, a file-like object, or Nonecheck (
bool) – ifTrue, raiseCalledProcessErrorif the process terminates with a return code other than 0cwd (
str|bytes|PathLike[str] |PathLike[bytes] |None) – If notNone, change the working directory to this before running the commandenv (
Mapping[str,str] |None) – if notNone, this mapping replaces the inherited environment variables from the parent processstartupinfo (
Any) – an instance ofsubprocess.STARTUPINFOthat can be used to specify process startup parameters (Windows only)creationflags (
int) – flags that can be used to control the creation of the subprocess (seesubprocess.Popenfor the specifics)start_new_session (
bool) – iftruethe setsid() system call will be made in the child process prior to the execution of the subprocess. (POSIX only)pass_fds (
Sequence[int]) – sequence of file descriptors to keep open between the parent and child processes. (POSIX only)user (
str|int|None) – effective user to run the process as (Python >= 3.9, POSIX only)group (
str|int|None) – effective group to run the process as (Python >= 3.9, POSIX only)extra_groups (
Iterable[str|int] |None) – supplementary groups to set in the subprocess (Python >= 3.9, POSIX only)umask (
int) – if not negative, this umask is applied in the child process before running the given command (Python >= 3.9, POSIX only)
- Return type:
- Returns:
an object representing the completed process
- Raises:
CalledProcessError – if
checkisTrueand the process exits with a nonzero return code
- async anyio.open_process(command, *, stdin=-1, stdout=-1, stderr=-1, cwd=None, env=None, startupinfo=None, creationflags=0, start_new_session=False, pass_fds=(), user=None, group=None, extra_groups=None, umask=-1)
Start an external command in a subprocess.
See also
- Parameters:
command (
str|bytes|PathLike[str] |PathLike[bytes] |Sequence[str|bytes|PathLike[str] |PathLike[bytes]]) – either a string to pass to the shell, or an iterable of strings containing the executable name or path and its argumentsstdin (
Union[int,IO[Any],None]) – one ofsubprocess.PIPE,subprocess.DEVNULL, a file-like object, orNonestdout (
Union[int,IO[Any],None]) – one ofsubprocess.PIPE,subprocess.DEVNULL, a file-like object, orNonestderr (
Union[int,IO[Any],None]) – one ofsubprocess.PIPE,subprocess.DEVNULL,subprocess.STDOUT, a file-like object, orNonecwd (
str|bytes|PathLike[str] |PathLike[bytes] |None) – If notNone, the working directory is changed before executingenv (
Mapping[str,str] |None) – If env is notNone, it must be a mapping that defines the environment variables for the new processcreationflags (
int) – flags that can be used to control the creation of the subprocess (seesubprocess.Popenfor the specifics)startupinfo (
Any) – an instance ofsubprocess.STARTUPINFOthat can be used to specify process startup parameters (Windows only)start_new_session (
bool) – iftruethe setsid() system call will be made in the child process prior to the execution of the subprocess. (POSIX only)pass_fds (
Sequence[int]) – sequence of file descriptors to keep open between the parent and child processes. (POSIX only)user (
str|int|None) – effective user to run the process as (POSIX only)group (
str|int|None) – effective group to run the process as (POSIX only)extra_groups (
Iterable[str|int] |None) – supplementary groups to set in the subprocess (POSIX only)umask (
int) – if not negative, this umask is applied in the child process before running the given command (POSIX only)
- Return type:
- Returns:
an asynchronous process object
- class anyio.abc.Process
Bases:
AsyncResourceAn asynchronous version of
subprocess.Popen.- abstractmethod kill()
Kills the process.
On Windows, this calls
TerminateProcess(). On POSIX systems, this sendsSIGKILLto the process.See also
- Return type:
- abstract property returncode: int | None
The return code of the process. If the process has not yet terminated, this will be
None.
- abstractmethod send_signal(signal)
Send a signal to the subprocess.
See also
- Parameters:
signal (
Signals) – the signal number (e.g.signal.SIGHUP)- Return type:
- abstract property stderr: ByteReceiveStream | None
The stream for the standard error output of the process.
- abstract property stdin: ByteSendStream | None
The stream for the standard input of the process.
- abstract property stdout: ByteReceiveStream | None
The stream for the standard output of the process.
- abstractmethod terminate()
Terminates the process, gracefully if possible.
On Windows, this calls
TerminateProcess(). On POSIX systems, this sendsSIGTERMto the process.See also
- Return type:
Synchronization
- class anyio.Event
Bases:
object- statistics()
Return statistics about the current state of this event.
- Return type:
- class anyio.Lock(*, fast_acquire: bool = False)
Bases:
object- acquire_nowait()
Acquire the lock, without blocking.
- Raises:
WouldBlock – if the operation would block
- Return type:
- statistics()
Return statistics about the current state of this lock.
Added in version 3.0.
- Return type:
- class anyio.Condition(lock=None)
Bases:
object- acquire_nowait()
Acquire the underlying lock, without blocking.
- Raises:
WouldBlock – if the operation would block
- Return type:
- statistics()
Return statistics about the current state of this condition.
Added in version 3.0.
- Return type:
- class anyio.Semaphore(initial_value, *, max_value=None, fast_acquire=False)
Bases:
object- acquire_nowait()
Acquire the underlying lock, without blocking.
- Raises:
WouldBlock – if the operation would block
- Return type:
- statistics()
Return statistics about the current state of this semaphore.
Added in version 3.0.
- Return type:
- class anyio.CapacityLimiter(total_tokens: float)
Bases:
object- async acquire()
Acquire a token for the current task, waiting if necessary for one to become available.
- Return type:
- 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:
- async acquire_on_behalf_of(borrower)
Acquire a token, waiting if necessary for one to become available.
- acquire_on_behalf_of_nowait(borrower)
Acquire a token without waiting for one to become available.
- Parameters:
borrower (
object) – the entity borrowing a token- Raises:
WouldBlock – if there are no tokens available for borrowing
- Return type:
- 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:
- 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:
- statistics()
Return statistics about the current state of this limiter.
Added in version 3.0.
- Return type:
- property total_tokens: float
The total number of tokens available for borrowing.
This is a read-write property. If the total number of tokens is increased, the proportionate number of tasks waiting on this limiter will be granted their tokens.
Changed in version 3.0: The property is now writable.
Changed in version 4.12: The value can now be set to 0.
- class anyio.ResourceGuard(action='using')
Bases:
objectA context manager for ensuring that a resource is only used by a single task at a time.
Entering this context manager while the previous has not exited it yet will trigger
BusyResourceError.- Parameters:
action (
str) – the action to guard against (visible in theBusyResourceErrorwhen triggered, e.g. “Another task is already {action} this resource”)
Added in version 4.1.
- class anyio.ConditionStatistics(tasks_waiting, lock_statistics)
Bases:
object- Variables:
lock_statistics (LockStatistics) – statistics of the underlying
Lock
- class anyio.CapacityLimiterStatistics(borrowed_tokens, total_tokens, borrowers, tasks_waiting)
Bases:
object- Variables:
borrowed_tokens (int) – number of tokens currently borrowed by tasks
total_tokens (float) – total number of available tokens
borrowers (tuple) – tasks or other objects currently holding tokens borrowed from this limiter
tasks_waiting (int) – number of tasks waiting on
acquire()oracquire_on_behalf_of()
Operating system signals
- anyio.open_signal_receiver(*signals)
Start receiving operating system signals.
- Parameters:
signals (
Signals) – signals to receive (e.g.signal.SIGINT)- Return type:
- Returns:
an asynchronous context manager for an asynchronous iterator which yields signal numbers
- Raises:
NoEventLoopError – if no supported asynchronous event loop is running in the current thread
Warning
Windows does not support signals natively so it is best to avoid relying on this in cross-platform applications.
Warning
On asyncio, this permanently replaces any previous signal handler for the given signals, as set via
add_signal_handler().
Asynchronous functools
- anyio.functools.cache(func, /)
A convenient shortcut for
lru_cache()withmaxsize=None.This is the asynchronous equivalent to
functools.cache().- Return type:
- anyio.functools.lru_cache(func=None, /, *, maxsize=128, typed=False, always_checkpoint=False, ttl=None)
An asynchronous version of
functools.lru_cache().If a synchronous function is passed, the standard library
functools.lru_cache()is applied instead.- Parameters:
- Return type:
Note
Caches and locks are managed on a per-event loop basis.
- async anyio.functools.reduce(function, iterable, /, initial=<anyio.functools._InitialMissingType object>)
Asynchronous version of
functools.reduce().- Parameters:
function (
Callable[[TypeVar(T),TypeVar(T)],Awaitable[TypeVar(T)]] |Callable[[TypeVar(T),TypeVar(S)],Awaitable[TypeVar(T)]]) – a coroutine function that takes two arguments: the accumulated value and the next element from the iterableiterable (
Iterable[TypeVar(T)] |Iterable[TypeVar(S)] |AsyncIterable[TypeVar(T)] |AsyncIterable[TypeVar(S)]) – an iterable or async iterableinitial (
Union[TypeVar(T),_InitialMissingType]) – the initial value (if missing, the first element of the iterable is used as the initial value)
- Return type:
TypeVar(T)
Asynchronous itertools
- async anyio.itertools.accumulate(iterable, function=<function _operator_add>, *, initial=None)
- Return type:
AsyncGenerator[TypeVar(T),None]
- async anyio.itertools.batched(iterable, n, *, strict=False)
- Return type:
AsyncGenerator[tuple[TypeVar(T),...],None]
- async anyio.itertools.combinations(iterable, r)
- Return type:
AsyncGenerator[tuple[TypeVar(T),...],None]
- async anyio.itertools.combinations_with_replacement(iterable, r)
- Return type:
AsyncGenerator[tuple[TypeVar(T),...],None]
- async anyio.itertools.compress(data, selectors)
- Return type:
AsyncGenerator[TypeVar(T),None]
- async anyio.itertools.count(start=0, step=1)
- Return type:
- async anyio.itertools.cycle(iterable)
- Return type:
AsyncGenerator[TypeVar(T),None]
- async anyio.itertools.dropwhile(predicate, iterable)
- Return type:
AsyncGenerator[TypeVar(T),None]
- async anyio.itertools.filterfalse(predicate, iterable)
- Return type:
AsyncGenerator[TypeVar(T),None]
- async anyio.itertools.groupby(iterable, key=None)
- async anyio.itertools.islice(iterable, *args)
- Return type:
AsyncGenerator[TypeVar(T),None]
- async anyio.itertools.pairwise(iterable)
- Return type:
AsyncGenerator[tuple[TypeVar(T),TypeVar(T)],None]
- async anyio.itertools.permutations(iterable, r=None)
- Return type:
AsyncGenerator[tuple[TypeVar(T),...],None]
- async anyio.itertools.product(*iterables, repeat=1)
- Return type:
AsyncGenerator[tuple[TypeVar(T),...],None]
- async anyio.itertools.repeat(element, times=None)
- Return type:
AsyncGenerator[TypeVar(T),None]
- async anyio.itertools.starmap(function, iterable)
- Return type:
AsyncGenerator[TypeVar(R),None]
- anyio.itertools.tee(iterable, n=2)
- Return type:
tuple[AsyncIterator[TypeVar(T)],...]
- async anyio.itertools.takewhile(predicate, iterable)
- Return type:
AsyncGenerator[TypeVar(T),None]
Low level operations
- async anyio.lowlevel.checkpoint()
Check for cancellation and allow the scheduler to switch to another task.
Equivalent to (but more efficient than):
await checkpoint_if_cancelled() await cancel_shielded_checkpoint()
Added in version 3.0.
- Return type:
- async anyio.lowlevel.checkpoint_if_cancelled()
Enter a checkpoint if the enclosing cancel scope has been cancelled.
This does not allow the scheduler to switch to a different task.
Added in version 3.0.
- Return type:
- async anyio.lowlevel.cancel_shielded_checkpoint()
Allow the scheduler to switch to another task but without checking for cancellation.
Equivalent to (but potentially more efficient than):
with CancelScope(shield=True): await checkpoint()
Added in version 3.0.
- Return type:
- anyio.lowlevel.current_token()
Return a token object that can be used to call code in the current event loop from another thread.
- Raises:
NoEventLoopError – if no supported asynchronous event loop is running in the current thread
Added in version 4.11.0.
- Return type:
- class anyio.lowlevel.RunVar(name, default=_NoValueSet.NO_VALUE_SET)
Bases:
Generic[T]Like a
ContextVar, except scoped to the running event loop.Can be used as a context manager, Just like
ContextVar, that will reset the variable to its previous value when the context block is exited.- get(default=_NoValueSet.NO_VALUE_SET)
Return the current value of this run variable.
- Parameters:
default (
Union[TypeVar(D),Literal[<_NoValueSet.NO_VALUE_SET: 1>]]) – a fallback value to return if no value has been set- Return type:
- Returns:
the current value, the provided default, or the variable’s own default
- Raises:
LookupError – if no value is set and no default is available
Testing and debugging
- class anyio.TaskInfo(id, parent_id, name, coro)
Bases:
objectRepresents an asynchronous task.
- Variables:
- class anyio.pytest_plugin.FreePortFactory(kind)
Bases:
objectManages port generation based on specified socket kind, ensuring no duplicate ports are generated.
This class provides functionality for generating available free ports on the system. It is initialized with a specific socket kind and can generate ports for given address families while avoiding reuse of previously generated ports.
Users should not instantiate this class directly, but use the
free_tcp_port_factoryandfree_udp_port_factoryfixtures instead. For simple uses cases,free_tcp_portandfree_udp_portcan be used instead.- property kind: SocketKind
The type of socket connection (e.g.,
SOCK_STREAMorSOCK_DGRAM) used to bind for checking port availability
- anyio.get_current_task()
Return the current task.
- Return type:
- Returns:
a representation of the current task
- Raises:
NoEventLoopError – if no supported asynchronous event loop is running in the current thread
- anyio.get_running_tasks()
Return a list of running tasks in the current event loop.
- Return type:
- Returns:
a list of task info objects
- Raises:
NoEventLoopError – if no supported asynchronous event loop is running in the current thread
Exceptions
- exception anyio.BrokenResourceError
Bases:
ExceptionRaised when trying to use a resource that has been rendered unusable due to external causes (e.g. a send stream whose peer has disconnected).
- exception anyio.BrokenWorkerInterpreter(excinfo)
Bases:
ExceptionRaised by
run_sync()if an unexpected exception is raised in the subinterpreter.
- exception anyio.BrokenWorkerProcess
Bases:
ExceptionRaised by
run_sync()if the worker process terminates abruptly or otherwise misbehaves.
- exception anyio.BusyResourceError(action)
Bases:
ExceptionRaised when two tasks are trying to read from or write to the same resource concurrently.
- exception anyio.ClosedResourceError
Bases:
ExceptionRaised when trying to use a resource that has been closed.
- exception anyio.ConnectionFailed
Bases:
OSErrorRaised when a connection attempt fails.
Note
This class inherits from
OSErrorfor backwards compatibility.
- exception anyio.DelimiterNotFound(max_bytes)
Bases:
ExceptionRaised during
receive_until()if the maximum number of bytes has been read without the delimiter being found.
- exception anyio.EndOfStream
Bases:
ExceptionRaised when trying to read from a stream that has been closed from the other end.
- exception anyio.IncompleteRead
Bases:
ExceptionRaised during
receive_exactly()orreceive_until()if the connection is closed before the requested amount of bytes has been read.
- exception anyio.NoEventLoopError
Bases:
RuntimeErrorRaised by several functions that require an event loop to be running in the current thread when there is no running event loop.
This is also raised by
from_thread.run()andfrom_thread.run_sync()if not calling from an AnyIO worker thread, and notokenwas passed.
- exception anyio.RunFinishedError
Bases:
RuntimeErrorRaised by
from_thread.run()andfrom_thread.run_sync()if the event loop associated with the explicitly passed token has already finished.
- exception anyio.TaskFailed
Bases:
ExceptionRaised when awaiting on, or attempting to access the return value of, a
TaskHandlethat raised an exception.
- exception anyio.TaskCancelled
Bases:
TaskFailedRaised when awaiting on, or attempting to access the return value of, a
TaskHandlethat was cancelled.
- exception anyio.TaskNotFinished
Bases:
ExceptionRaised when attempting to access the return value or exception of a
TaskHandlethat is still pending completion.
- exception anyio.TypedAttributeLookupError
Bases:
LookupErrorRaised by
extra()when the given typed attribute is not found and no default value has been given.