nest-asyncio Library

raw JSON →
1.6.0 verified Tue May 12 auth: no python install: verified quickstart: verified

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.

pip install nest-asyncio
error 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.
fix
Apply nest-asyncio at the beginning of your script or notebook to patch asyncio and allow nested event loops:
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())
error 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.
fix
Import and apply nest_asyncio at the start of your program or notebook cell to enable re-entrant use of asyncio.run():
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)
error 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.
fix
Install the library using pip:
pip install nest-asyncio
Or, if using Anaconda/Conda:
conda install -c conda-forge nest-asyncio
error 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+.
fix
Upgrade 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:
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())
error 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`.
fix
Ensure 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):
# 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())
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.
fix On Python 3.14+, use `await` with async methods (e.g., `await obj.async_method()`) instead of relying on `nest-asyncio`'s patching for automatic conversion.
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.
fix While often ignorable as the loop is reused, be aware of this warning. For critical applications, ensure proper event loop management, or consider explicit loop closing if not relying on reuse (though this often defeats `nest-asyncio`'s purpose).
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`.
fix Ensure you are using `asyncio`'s default event loop when `nest-asyncio` is applied. If you require other loop implementations, `nest-asyncio` may not be the solution.
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.
fix Avoid long-running or CPU-bound operations within nested `asyncio.run()` calls. If significant work is needed, consider restructuring your async code to avoid deep nesting or using thread pools for blocking operations.
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.
fix When working with frameworks that have their own async integration mechanisms, prefer using their recommended patterns over `nest-asyncio` to ensure compatibility and stability.
python os / libc status wheel install import disk
3.10 alpine (musl) - - 0.12s 17.8M
3.10 slim (glibc) - - 0.09s 18M
3.11 alpine (musl) - - 0.21s 19.6M
3.11 slim (glibc) - - 0.20s 20M
3.12 alpine (musl) - - 0.50s 11.5M
3.12 slim (glibc) - - 0.43s 12M
3.13 alpine (musl) - - 0.43s 11.1M
3.13 slim (glibc) - - 0.49s 12M
3.9 alpine (musl) - - 0.13s 17.3M
3.9 slim (glibc) - - 0.11s 18M

This quickstart demonstrates how to apply the `nest-asyncio` patch and then run an `asyncio` coroutine using `asyncio.run()`, even if an event loop is already running.

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)