{"record":{"id":"a3ab9a87f22e1133","repo":"pola-rs/polars","slug":"asyncio-is-already-patched-by-nest-asyncio","errorCode":null,"errorMessage":"asyncio is already patched by nest_asyncio","messagePattern":"asyncio is already patched by nest_asyncio","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/_utils/nest_asyncio.py","lineNumber":204,"sourceCode":"            if new_event_loop:\n                # Avoid ResourceWarning: unclosed event loop\n                loop.close()\n\n\ndef _patch_asyncio(*, error_on_mispatched: bool = False):\n    \"\"\"Patch asyncio module to use pure Python tasks and futures.\"\"\"\n\n    def _get_event_loop(stacklevel=3):\n        loop = events._get_running_loop()\n        if loop is None:\n            loop = events.get_event_loop_policy().get_event_loop()\n        return loop\n\n    # Use module level _current_tasks, all_tasks and patch run method.\n    if hasattr(asyncio, \"_nest_patched\"):\n        if not hasattr(asyncio, \"_nest_asyncio2\"):\n            if error_on_mispatched:\n                raise RuntimeError(\"asyncio is already patched by nest_asyncio\")\n            elif sys.version_info >= (3, 12, 0):\n                import warnings\n\n                warnings.warn(\n                    \"asyncio is already patched by nest_asyncio. You may encounter bugs related to asyncio\"\n                )\n        return\n\n    # Using _PyTask on Python 3.14+ will break current_task() (and all_tasks(),\n    # _swap_current_task())\n    # Even we replace it with _py_current_task(), it only works with _PyTask, but\n    # the external loop is probably using _CTask.\n    # https://github.com/python/cpython/pull/129899\n    if sys.version_info >= (3, 6, 0) and sys.version_info < (3, 14, 0):\n        asyncio.Task = asyncio.tasks._CTask = asyncio.tasks.Task = asyncio.tasks._PyTask\n        asyncio.Future = asyncio.futures._CFuture = asyncio.futures.Future = (\n            asyncio.futures._PyFuture\n        )","sourceCodeStart":186,"sourceCodeEnd":222,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/py-polars/src/polars/_utils/nest_asyncio.py#L186-L222","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Guard the patch: only call `nest_asyncio.apply()` if `not hasattr(asyncio, '_nest_patched')`.","Find and remove the duplicate patching library, or apply nest_asyncio once at process startup before other libraries.","On Python >= 3.12 prefer native `await`/`asyncio.run` in the notebook and skip nest_asyncio entirely."],"exampleFix":"// before\nimport nest_asyncio\nnest_asyncio.apply()  # RuntimeError if already patched\n// after\nimport asyncio, nest_asyncio\nif not hasattr(asyncio, '_nest_patched'):\n    nest_asyncio.apply()","handlingStrategy":"type-guard","validationCode":"import asyncio\nif not hasattr(asyncio, \"_nest_patched\"):\n    nest_asyncio.apply()","typeGuard":"def asyncio_already_patched() -> bool:\n    return hasattr(asyncio, \"_nest_patched\")","tryCatchPattern":"try:\n    nest_asyncio.apply()\nexcept RuntimeError as e:\n    if \"already patched by nest_asyncio\" not in str(e):\n        raise","preventionTips":["Apply nest_asyncio exactly once, at process startup.","Check `hasattr(asyncio, '_nest_patched')` before patching.","On Python 3.12+, prefer native top-level await over nest_asyncio."],"tags":["polars","asyncio","nest-asyncio","double-patch"],"backgroundTag":"invalid-state-transition","analyzedSha":"fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e","analyzedAt":"2026-09-18T22:14:11.667Z","contentChangedAt":"2026-09-18T22:14:11.667Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}