nest-asyncio2
nest-asyncio2 is a fork of the unmaintained `nest_asyncio` library, designed to patch `asyncio` to allow nested event loops. It addresses compatibility issues with Python 3.12+ and 3.14+ where the original library would fail. The current version is 1.7.2, and it receives updates as needed to maintain compatibility with newer Python versions and fix issues.
Warnings
- breaking The original `nest_asyncio` library is unmaintained and incompatible with Python 3.12+ (e.g., `asyncio.current_task()` and `loop_factory` issues). `nest-asyncio2` is a fork specifically addressing these incompatibilities.
- gotcha `nest-asyncio2.apply()` will warn if `asyncio` is already patched by `nest_asyncio` (on Python 3.12+) or can be configured to raise a `RuntimeError` by setting `error_on_mispatched=True`.
- gotcha On Python 3.12+, patched `asyncio.run()` might create a new event loop if none exists, which could lead to a `ResourceWarning: unclosed event loop` at exit. This warning is often hidden by default.
- gotcha In versions prior to `v1.7.2`, `asyncio.call_soon()` callbacks might not have been properly called during `asyncio.run()` in nested contexts.
Install
-
pip install nest-asyncio2
Imports
- apply
import nest_asyncio2 nest_asyncio2.apply()
Quickstart
import asyncio
import nest_asyncio2
async def inner_coroutine():
print("Inner coroutine running.")
await asyncio.sleep(0.01)
print("Inner coroutine finished.")
async def outer_coroutine():
print("Outer coroutine starting inner loop.")
# This would normally fail with RuntimeError: This event loop is already running
# but nest_asyncio2 allows it.
await asyncio.run(inner_coroutine())
print("Outer coroutine finished inner loop.")
# Apply the patch to allow nested event loops
nest_asyncio2.apply()
# Run the outer coroutine, which itself runs an inner event loop
print("Running outer event loop.")
asyncio.run(outer_coroutine())
print("Program finished.")