pola-rs/polars · error · RuntimeError

asyncio is already patched by nest_asyncio

Error message

asyncio is already patched by nest_asyncio

What it means

RuntimeError raised by _patch_asyncio: asyncio already carries the _nest_patched marker from a previous (or external) patch, and error_on_mispatched requested strict behavior, so re-patching is refused rather than silently double-patching task/future classes.

Source

Thrown at py-polars/src/polars/_utils/nest_asyncio.py:204

            if new_event_loop:
                # Avoid ResourceWarning: unclosed event loop
                loop.close()


def _patch_asyncio(*, error_on_mispatched: bool = False):
    """Patch asyncio module to use pure Python tasks and futures."""

    def _get_event_loop(stacklevel=3):
        loop = events._get_running_loop()
        if loop is None:
            loop = events.get_event_loop_policy().get_event_loop()
        return loop

    # Use module level _current_tasks, all_tasks and patch run method.
    if hasattr(asyncio, "_nest_patched"):
        if not hasattr(asyncio, "_nest_asyncio2"):
            if error_on_mispatched:
                raise RuntimeError("asyncio is already patched by nest_asyncio")
            elif sys.version_info >= (3, 12, 0):
                import warnings

                warnings.warn(
                    "asyncio is already patched by nest_asyncio. You may encounter bugs related to asyncio"
                )
        return

    # Using _PyTask on Python 3.14+ will break current_task() (and all_tasks(),
    # _swap_current_task())
    # Even we replace it with _py_current_task(), it only works with _PyTask, but
    # the external loop is probably using _CTask.
    # https://github.com/python/cpython/pull/129899
    if sys.version_info >= (3, 6, 0) and sys.version_info < (3, 14, 0):
        asyncio.Task = asyncio.tasks._CTask = asyncio.tasks.Task = asyncio.tasks._PyTask
        asyncio.Future = asyncio.futures._CFuture = asyncio.futures.Future = (
            asyncio.futures._PyFuture
        )

View on GitHub (pinned to 9b5d73fd00)

Solutions

  1. Do not apply nest_asyncio twice; apply it once at startup.

Example fix

nest_asyncio.apply()  # once only
Defensive patterns

Strategy: validation

When it happens

Trigger: Applying nest_asyncio to an already patched event loop.

Common situations: See trigger scenarios.


AI-assisted analysis of pola-rs/polars@9b5d73fd00 (2026-08-19). Data as JSON: /api/errors/a3ab9a87f22e1133. Report an issue: GitHub.