pypi / anyio
anyio
What changed in anyio 4, from its official release notes, upgrade guides and advisories. Sources checked 2026-11-30.
19 breaking3 security1 deprecations32 new APIs and options9 performance15 behavior and defaults93 fixes and other
See which of these apply to your code, ranked, in your agent:
npx @unstale/cli initanyio 4172 changes
Breaking changes 19
NaN deadlines are now rejected on both backends instead of silently disabling timeouts on asyncio.
On asyncio, a native Task.cancel() delivered alongside scope cancellation is no longer swallowed, leaving the host task with a pending cancellation.
On the asyncio backend, UDP socket sends now wait until the datagram has been passed to the operating system.
Negative delays, including negative infinity, now raise ValueError consistently across backends.
Rollover no longer moves the current file position to the end of the file.
After a cancelled send loses an encrypted record, further use now raises BrokenResourceError rather than sending records the peer cannot decrypt.
Now raises ValueError for an empty stem with a non-empty suffix instead of silently producing an incorrect path.
Raises ValueError when max_bytes is not a positive integer.
Support for Python 3.9 was dropped.
Functions that raised the private NoCurrentAsyncBackend exception now raise the public NoEventLoopError exception.
AnyIO adds get_available_backends() for discovering available backends.
sniffio is no longer a direct dependency of AnyIO.
Now accepts only one argument, matching the deprecation of multiple arguments in Python 3.12.
The asyncio backend's policy option was changed to loop_factory to accommodate asyncio.Runner.
AnyIO's own ExceptionGroup class was replaced with the PEP 654 BaseExceptionGroup and ExceptionGroup; exceptions raised from task groups are now nested in an exception group.
The plugin now runs all tests and fixtures in the same task, allowing fixtures to set context variables for tests and other fixtures.
Support for Python 3.7 was dropped.
Task groups now always hit a yield point on exit and raise a single cancellation exception when an outer cancel scope is cancelled; non-cancellation exceptions are not raised in that case.
The minimum supported version of trio is now v0.22.
Security 3
anyio.open_process() and run_process() now pass the extra_groups argument correctly.
Matches internationalized host names against peer certificates using IDNA 2008 instead of IDNA 2003.
No longer deadlocks when the worker writes enough data to fill the undrained stderr pipe.
Deprecations 1
The item_type argument is deprecated; use create_memory_object_stream[T_Item]() to indicate the stream item type. The argument remains available but raises a deprecation warning and does not affect static types.
New APIs and options 32
Adds asynchronous calling into an event loop, with optional abandonment on cancellation.
Adds a utility function to simplify common asynchronous mapping patterns.
Adds a pytest command-line alternative to the anyio_mode ini setting.
Adds a synchronization primitive that lets tasks wait for a value or exception from another task.
Supports the standard library's newer follow_symlinks keyword on Python 3.12 and later.
Supports the standard library's newer follow_symlinks keyword on Python 3.13 and later.
Supports the standard library's newer follow_symlinks keyword on Python 3.13 and later.
Supports the standard library's newer follow_symlinks keyword on Python 3.13 and later.
Supports the standard library's newer follow_symlinks keyword on Python 3.13 and later.
Supports the standard library's newer newline keyword on Python 3.13 and later.
Adds a utility function to simplify common asynchronous completion-order patterns.
Accepts reason context that is included when TimeoutError is raised; the parameter also applies to fail_at.
Adds an absolute-deadline counterpart to fail_after.
Adds a utility function to simplify common asynchronous gathering patterns.
Adds an absolute-deadline counterpart to move_on_after.
Delegates nonblocking sends to the underlying ObjectSendStream when supported.
An asynchronous implementation of the itertools module is now available.
Async path and file I/O functions and classes now accept custom capacity limiters.
connect_tcp() can bind to a specific local port before connecting.
TaskGroup now has cancel() as a shortcut for cancelling its cancel scope.
Task groups now provide create_task(), returning a TaskHandle for easier asyncio migration.
TaskGroup.start() can return a TaskHandle containing the start value in start_value.
The lru_cache wrapper now accepts a ttl parameter.
anyio.Path.glob() and anyio.Path.rglob() now support path-like objects.
anyio.Path.glob() accepts the case_sensitive parameter.
anyio.Path.glob() accepts the recurse_symlinks parameter.
AnyIO adds an asynchronous implementation of the functools module.
Added the anyio.Path.is_junction() method.
Added the anyio.Path.walk() method.
Added a property that tells users if the cancel scope suppressed a cancellation exception.
Added a function to create connected UNIX datagram sockets.
Added a function to create UNIX datagram sockets.
Performance 9
Reduces unnecessary CPU spin when delivering cancellation on asyncio under certain nesting conditions.
CancelScope and its subclasses now define __slots__ with __weakref__.
CapacityLimiter and its subclasses now define __slots__ with __weakref__.
Condition and its subclasses now define __slots__ with __weakref__.
Event and its subclasses now define __slots__ with __weakref__.
Lock and its subclasses now define __slots__ with __weakref__.
ResourceGuard and its subclasses now define __slots__ with __weakref__.
Semaphore and its subclasses now define __slots__ with __weakref__.
Removed an unnecessary extra waiting cycle on asyncio when the event was not yet set.
Behavior and default changes 15
Supports SOCK_SEQPACKET sockets.
Default task names now match analogous start_soon and start tasks in more situations, including the module name.
The callable annotation now requires a callable returning a coroutine-like object instead of an arbitrary awaitable.
Path methods returning path objects now preserve subclass types by returning Self.
write_bytes() now accepts any ReadableBuffer, including bytearray and memoryview.
anyio.run() now supports callables returning arbitrary awaitables at runtime on all backends.
Errors for unavailable known backends now suggest the install command.
start_soon() now returns a TaskHandle.
The callable annotation now requires a callable returning a coroutine-like object instead of an arbitrary awaitable.
The callable annotation now requires a callable returning a coroutine-like object instead of an arbitrary awaitable.
File I/O stream annotations now accept IO[bytes] instead of only BinaryIO.
Public AnyIO submodules now define __all__ declarations, affecting wildcard imports and public-name introspection.
RunVar can now be used as a context manager.
A CapacityLimiter can now have a token count of zero.
On the asyncio backend, run now uses asyncio.Runner or a back-ported version on Python versions older than 3.11.
Fixes and other changes 93
On asyncio UNIX socket listeners, accept no longer hangs or leaves the listener registered when another task closes it.
Socket close operations now checkpoint and raise cancellation inside a cancelled scope on affected backends and socket types.
Closing asyncio TCP socket listeners now checkpoints, preventing a listening socket leak if cancellation occurs while another task waits in accept().
Concurrent calls on asyncio socket streams now wait until the underlying socket is closed.
Importing with loaders that do not provide __file__, such as PyOxidizer, now falls back to eager imports instead of raising TypeError.
Consumes the first start items even when stop is less than or equal to start.
Does not acquire or consume unused input iterables when repeat=0.
Closing an AsyncFile is now shielded against cancellation.
No longer crashes with InvalidStateError when a returned future is cancelled as its callable completes.
A failed first attempt to start its blocking portal no longer leaves the provider permanently failing on subsequent use.
Exceptions raised in its with block are now passed to the wrapped start_blocking_portal() context manager.
Empty messages from a wrapped object stream no longer produce empty bytes; the stream waits for data or raises EndOfStream.
After explicit closure, raises ClosedResourceError instead of returning buffered data.
On asyncio, cancellation during the cancel-shielded checkpoint after a non-blocking acquisition no longer releases the wrong borrower.
Works when the underlying lock was acquired directly rather than through the condition.
A connected socket is no longer leaked when an enclosing cancel scope is cancelled before the connection task group exits.
The requested local port is no longer ignored when local_host is omitted.
Avoids occasional failures creating listeners on an ephemeral port when IPv6 dual-stack is unavailable or a specific local hostname is given.
The requested local port is no longer ignored when local_host is omitted.
Files are no longer left open when cancelled during context manager exit.
Files are no longer left open, including with unflushed writes, when cancelled during context manager exit.
On asyncio, calls from callbacks scheduled via
loop.call_soon_threadsafe()now raise a clear error instead of an opaque TypeError.The pytest plugin now runs parametrized Hypothesis async tests on each backend.
No longer raises NoEventLoopError when the lock was created outside a running event loop.
Closing a stream now wakes tasks blocked in send() or receive() on that stream.
The fast-acquire behavior is retained when a semaphore is instantiated outside a running event loop.
Asyncio TCP and UDP sends no longer return normally when data is discarded after the socket closes or the TCP connection is lost.
On asyncio, a send no longer hands data to a paused transport after a previous send was cancelled.
Writes no longer roll over to disk when max_size is zero, the default.
Cancellation during rollover no longer loses buffered contents.
Cancelled asyncio TCP receives no longer leave transport reads enabled and allow incoming data to accumulate while the application is not receiving.
Cancellation during creation no longer leaves a directory behind while its context manager is retained.
Cleanup no longer reacts prematurely to cancellation when the host task is already cancelled, so cleanup is not skipped.
Incomplete characters at end-of-file are no longer silently discarded; the configured decoding error handler is applied.
BOM-emitting encodings no longer emit a byte order mark on every item after the first.
On asyncio, cancelled queued work no longer prevents worker threads from returning to the idle pool for reuse or pruning.
Sockets no longer remain open when initialization fails or is cancelled.
Subclassing an existing TypedAttributeSet subclass that contains type annotations no longer raises TypeError.
Closing a UDP socket no longer hangs when a datagram send is still in flight.
No longer silently truncates messages on short socket writes.
Direct access to anyio.* submodules now works from the main package without importing those submodules first.
Pytest auto mode detection now recognizes the mode from either the ini setting or command-line option.
Stops anyio.run from leaking or delaying collection of the event loop and root task.
Fixes a race that could raise RuntimeError when the event loop closed before a worker result was scheduled.
Prevents the asyncio backend from over-granting tokens when total_tokens increases while the limiter is over-subscribed.
Prevents asyncio task groups from leaking unawaited coroutines when a custom task constructor fails.
Fixes Python 3.14 free-threading issues affecting start_blocking_portal and to_thread.run_sync context behavior.
Removes use of the deprecated pytest alias that caused warnings on pytest 9.2 and startup crashes when warnings were errors.
Prevents readinto from reading twice before rollover, which previously overwrote buffers and advanced the file position twice.
Prevents readinto1 from reading twice before rollover, which previously overwrote buffers and advanced the file position twice.
Aligns Trio and asyncio cancellation behavior, started values, and CancelledError handling when startup is cancelled.
Fixes missing parts of the default task name for tasks started with TaskGroup.start on Trio.
Ensures cleanup runs in a shielded cancel scope when the host task is cancelled while exiting the context manager.
Prevents asyncio.InvalidStateError when closing concurrently with a just-cancelled receive or send operation.
Accepts positive infinity consistently when instantiated outside an event loop.
Raises anyio.WouldBlock consistently on the trio backend when no tokens are available.
No longer over-grants tokens during the window before a notified waiter resumes on asyncio.
CapacityLimiter.total_tokens now accepts 0 when the limiter is instantiated outside an event loop, matching documented behavior.
Teardown no longer fails on asyncio when an async test raises an outcome exception such as pytest.skip(), pytest.xfail(), or pytest.fail().
Cancelled waiters no longer cause asyncio Lock deadlocks during release.
backend_options now reach trio.run() when using the Trio backend.
Cancelled waiters no longer cause asyncio Semaphore deadlocks during release.
Tasks started through a BlockingPortal can now be cancelled after the portal has stopped.
Passing arguments to lru_cache no longer loses type information.
AnyIO now supports running on Python 3.15.
AF_UNIX listening sockets are no longer incorrectly returned as TCP listeners.
to_process workers now import __main__ when entrypoint scripts lack a .py suffix, including console_script entrypoints.
On asyncio, aclose() now waits until the underlying socket file descriptor is released.
The pytest plugin now runs tests marked programmatically through pytest_collection_modifyitems.
Fixed compatibility with Python 3.15 pathlib changes.
Asyncio SocketStream errors now preserve the original exception as their cause.
Asyncio cancellation exceptions no longer leak from exception groups containing non-cancellation exceptions.
A notification is now passed on when cancellation occurs after the task already received it.
Still-running pooled processes are now terminated during process pool shutdown.
Using func as a parameter name no longer raises TypeError with the pytest plugin.
Fixed lru_cache so it works with instance methods.
Cancelling a Future returned by BlockingPortal.start_task_soon() now reliably cancels the async function.
The asyncio backend avoids a rare RuntimeError while shutting down the process pool.
On asyncio, Process.stdin.send() now raises ClosedResourceError and BrokenResourceError in the relevant closed or broken cases.
On asyncio, Process.stdin.send() now checkpoints before writing data.
The pytest plugin no longer breaks compatibility with pytest 6.1.2 and older.
Fixed processes becoming unusable in the process pool when idle processes are pruned during to_process.run_sync(), preventing increased memory consumption.
Tasks started from a BlockingPortal now notify synchronous listeners such as concurrent.futures.wait() when cancelled.
On asyncio, cancellation suppression now checks the cancellation count as well as the cancel message, addressing cases where third-party libraries replace the original CancelledError.
Use create_memory_object_stream[T_Item]() to indicate the item type handled by the stream; type checking should no longer fail for uninstantiable item types.
Fixed an unwarranted TimeoutError when the cancel scope was cancelled before its deadline.
Fixed sniffio not being set on asyncio, including failures when calling sniffio-dependent functions from threads running trio or curio.
Fixed sniffio not being set on asyncio, including failures when calling sniffio-dependent functions.
Fixed an asyncio cancellation case that could leave the receiving task in a cancelled state after an item was queued but before it was received.
Support for Python 3.12 was added.
The type annotation now accepts any awaitables.
Fixed asyncio TaskGroup.start() not responding to cancellation from outside.
Worked around a CPython bug that caused asyncio to log "NoneType: None" instead of the handshake error.