nest-asyncio2

1.7.2 · active · verified Sun Apr 12

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

Install

Imports

Quickstart

This example demonstrates how to use `nest_asyncio2.apply()` to enable nested `asyncio.run()` calls. Without the patch, the inner `asyncio.run()` call would raise a `RuntimeError` because an event loop is already running.

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.")

view raw JSON →