nest-asyncio Library
nest-asyncio is a Python library that patches the `asyncio` module to allow nested event loops. This addresses the `RuntimeError: This event loop is already running` issue encountered in environments like web servers, GUI applications, and Jupyter notebooks where an event loop is already active. It is currently at version 1.6.0 and maintains a stable release cadence.
Warnings
- breaking Python 3.14+ breaks the `nest-asyncio` workaround. Due to significant changes in `asyncio`'s implementation, the library can no longer safely monkey-patch it, meaning automatic async-to-sync conversion often fails. Users must explicitly use `await` with async methods in environments like Jupyter notebooks.
- gotcha Using `nest-asyncio` can lead to a `ResourceWarning: unclosed event loop at exit` on Python 3.12+ if the patched `asyncio.run()` creates a new event loop and doesn't explicitly close it. This warning is often hidden by default.
- gotcha `nest-asyncio` is designed to patch `asyncio` event loops only. It generally does not provide compatibility or patching for alternative event loop implementations like `uvloop` or `quamash`.
- gotcha Nesting `asyncio.run()` calls after applying `nest-asyncio` can potentially lead to 'starvation' of tasks scheduled outside the nested run if the inner loop occupies too much execution time. This happens because nested runs do not automatically yield time to outer tasks.
- gotcha Some frameworks, like Prefect, advise against using `nest-asyncio` and provide their own async utilities (e.g., `run_coro_as_sync`) to bridge async and sync code, explicitly warning that `nest-asyncio` can cause hard-to-debug issues like deadlocks, broken cancellations, and inconsistent behavior.
Install
-
pip install nest-asyncio
Imports
- apply
import nest_asyncio nest_asyncio.apply()
Quickstart
import asyncio
import nest_asyncio
# Apply the patch to allow nested event loops
nest_asyncio.apply()
async def my_async_function():
await asyncio.sleep(0.1)
return "Hello, Nested World!"
# This works even in environments with existing event loops
result = asyncio.run(my_async_function())
print(result)