pola-rs/polars · error · RuntimeError

asyncio is already patched by nest_asyncio

Error message

asyncio is already patched by nest_asyncio

What it means

In polars' bundled nest_asyncio, `_patch_asyncio` detects the module-level `_nest_patched` marker on asyncio. If present and a second patch is attempted without the `nest_asyncio2` escape hatch, it raises RuntimeError (when `error_on_mispatched` is set) because patching twice corrupts the loop's run implementation.

Solutions

  1. Guard the patch: only call `nest_asyncio.apply()` if `not hasattr(asyncio, '_nest_patched')`.
  2. Find and remove the duplicate patching library, or apply nest_asyncio once at process startup before other libraries.
  3. On Python >= 3.12 prefer native `await`/`asyncio.run` in the notebook and skip nest_asyncio entirely.

Example fix

// before
import nest_asyncio
nest_asyncio.apply()  # RuntimeError if already patched
// after
import asyncio, nest_asyncio
if not hasattr(asyncio, '_nest_patched'):
    nest_asyncio.apply()
Defensive patterns

Strategy: type-guard

Validate before calling

import asyncio
if not hasattr(asyncio, "_nest_patched"):
    nest_asyncio.apply()

Type guard

def asyncio_already_patched() -> bool:
    return hasattr(asyncio, "_nest_patched")

Try / catch

try:
    nest_asyncio.apply()
except RuntimeError as e:
    if "already patched by nest_asyncio" not in str(e):
        raise

Prevention

When it happens

Trigger: Calling `nest_asyncio.apply()` (used by e.g. `pl.show_graph` in notebooks) after another library already applied nest_asyncio to asyncio, or calling `apply()` twice in one process.

Common situations: Jupyter environments where both polars and another plotting/async library patch asyncio; mixing nest_asyncio with already-patched asyncio on Python 3.12+ where it warns instead.

Understand the failure class

Background: "Invalid state transition" errors: "status must be X, actually Y", "already rejected/charging/uninstalled", "cannot ... while running" — what they mean when a library rejects your call — this error's family across 31 libraries.

Related errors


AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18). Data as JSON: /api/errors/a3ab9a87f22e1133. Report an issue: GitHub.

Appendix: 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 fe841f959e)