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.
Common errors
-
RuntimeError: This event loop is already running
cause The `asyncio` module by design does not allow an event loop to be nested, meaning you cannot call `asyncio.run()` or `loop.run_until_complete()` if an event loop is already active, which commonly occurs in environments like Jupyter notebooks, web servers, or GUI applications.fixApply `nest-asyncio` at the beginning of your script or notebook to patch `asyncio` and allow nested event loops: ```python import nest_asyncio nest_asyncio.apply() # Now you can run async code even if a loop is already running import asyncio async def main(): print('Hello from async!') asyncio.run(main()) ``` -
RuntimeError: asyncio.run() cannot be called from a running event loop
cause This error is a specific manifestation of the 'event loop already running' problem, occurring when `asyncio.run()` is invoked inside a context where the main event loop is already active, preventing the creation of a new top-level loop.fixImport and apply `nest_asyncio` at the start of your program or notebook cell to enable re-entrant use of `asyncio.run()`: ```python import nest_asyncio nest_asyncio.apply() import asyncio async def my_async_function(): await asyncio.sleep(0.1) return 'Done!' # This will now work without error in environments with an existing loop result = asyncio.run(my_async_function()) print(result) ``` -
ModuleNotFoundError: No module named 'nest_asyncio'
cause The `nest_asyncio` library is not installed in the Python environment currently being used, or the environment where it was installed is not active.fixInstall the library using pip: ```bash pip install nest-asyncio ``` Or, if using Anaconda/Conda: ```bash conda install -c conda-forge nest-asyncio ``` -
AttributeError: module 'asyncio' has no attribute 'run'
cause The `asyncio.run()` function was introduced in Python 3.7. This error occurs when attempting to use `asyncio.run()` in a Python version older than 3.7, even if `nest-asyncio` itself supports Python 3.5+.fixUpgrade your Python interpreter to version 3.7 or higher. If upgrading is not an option, you must use the older `asyncio` loop management methods (e.g., `asyncio.get_event_loop().run_until_complete(coroutine)`) and apply `nest_asyncio` to the loop: ```python import asyncio import nest_asyncio async def old_style_async(): print("Running in old-style loop") loop = asyncio.get_event_loop() nest_asyncio.apply(loop) loop.run_until_complete(old_style_async()) ``` -
ValueError: Can't patch loop of type <type>
cause `nest-asyncio` is designed to patch standard `asyncio` event loops. This error occurs when `nest_asyncio.apply()` is called with or attempts to patch a non-standard event loop implementation, such as `uvloop` or `quamash`, which are not directly supported by `nest-asyncio`.fixEnsure that you are using the default `asyncio` event loop. If you are explicitly setting a third-party loop like `uvloop`, you might need to revert to the default `asyncio` loop for `nest-asyncio` to function correctly, or investigate if the third-party loop offers its own nesting mechanisms or compatibility layers. Example (if using `uvloop`, remove its explicit installation/setting): ```python # If you were doing something like this, remove or comment it out: # import uvloop # uvloop.install() import nest_asyncio nest_asyncio.apply() import asyncio async def my_async_task(): print("Running with patched asyncio loop") asyncio.run(my_async_task()) ```
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)