{"record":{"id":"0c710a3068712edb","repo":"pola-rs/polars","slug":"can-t-patch-loop-of-type-s","errorCode":null,"errorMessage":"Can't patch loop of type %s","messagePattern":"Can't patch loop of type (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/_utils/nest_asyncio.py","lineNumber":392,"sourceCode":"        try:\n            self._set_coroutine_origin_tracking(self._debug)\n            if self._asyncgens is not None:\n                sys.set_asyncgen_hooks(\n                    firstiter=self._asyncgen_firstiter_hook,\n                    finalizer=self._asyncgen_finalizer_hook,\n                )\n            yield\n        finally:\n            self._set_coroutine_origin_tracking(False)\n            if self._asyncgens is not None:\n                sys.set_asyncgen_hooks(*old_agen_hooks)\n\n    def _check_running(self):\n        \"\"\"Do not throw exception if loop is already running.\"\"\"\n        pass\n\n    if not isinstance(loop, asyncio.BaseEventLoop):\n        raise ValueError(\"Can't patch loop of type %s\" % type(loop))\n    if not isinstance(loop._ready, _ReentrantReady):\n        old_ready, loop._ready = loop._ready, _ReentrantReady()\n        while old_ready:\n            loop._ready.append(old_ready.popleft())\n    if hasattr(loop, \"_nest_patched\"):\n        return\n    cls = loop.__class__\n    cls.run_forever = run_forever\n    cls.run_until_complete = run_until_complete\n    cls._run_once = _run_once\n    cls._check_running = _check_running\n    cls._check_runnung = _check_running  # typo in Python 3.7 source\n    cls._num_runs_pending = 1 if loop.is_running() else 0\n    cls._is_proactorloop = os.name == \"nt\" and issubclass(\n        cls, asyncio.ProactorEventLoop\n    )\n    if sys.version_info < (3, 7, 0):\n        cls._set_coroutine_origin_tracking = cls._set_coroutine_wrapper","sourceCodeStart":374,"sourceCodeEnd":410,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/py-polars/src/polars/_utils/nest_asyncio.py#L374-L410","documentation":"nest_asyncio's _patch_loop can only patch instances of asyncio.BaseEventLoop. Polars vendors this module to allow re-entrant event loops; if the object passed (or returned by get_event_loop) is not a real asyncio loop, patching would fail, so a ValueError is raised naming the actual type.","triggerScenarios":"Calling polars async APIs (apply/run) or get_event_loop when the current 'loop' object is not an asyncio.BaseEventLoop — e.g. a uvloop loop, a third-party loop wrapper, None, or a custom event loop policy returning a non-standard object.","commonSituations":"Running under uvloop or gevent-monkey-patched environments, using exotic event loop policies, or calling asyncio-dependent polars functions from contexts where no proper asyncio loop exists (threads, embedded interpreters).","solutions":["Ensure a standard asyncio event loop is active: use asyncio.run(...) or asyncio.new_event_loop() with the default policy.","Uninstall uvloop or switch away from it for the process (uvloop loops are not BaseEventLoop subclasses in newer versions).","Upgrade polars so its vendored nest_asyncio matches your Python/asyncio version.","If you only need sync results, avoid the async entry points (apply/run) entirely."],"exampleFix":"// before\nimport uvloop\nuvloop.install()\ndf.lazy().collect(engine=\"async\")\n// after\nimport asyncio\nasyncio.run(pl.LazyFrame.collect_async(df.lazy()))","handlingStrategy":"type-guard","validationCode":"import asyncio\ndef ensure_patchable_loop(loop):\n    if not isinstance(loop, asyncio.BaseEventLoop):\n        raise TypeError(f\"expected asyncio event loop, got {type(loop)}\")\n    return loop","typeGuard":"def is_asyncio_loop(loop) -> bool:\n    import asyncio\n    return isinstance(loop, asyncio.BaseEventLoop)","tryCatchPattern":"try:\n    result = polars_async_entry(...)\nexcept ValueError as e:\n    if \"Can't patch loop of type\" in str(e):\n        result = asyncio.run(fallback_coro())\n    else:\n        raise","preventionTips":["Avoid uvloop/gevent monkey patching when using polars async helpers.","Always enter async contexts via asyncio.run or a default-policy loop.","Pin polars and Python versions so vendored nest_asyncio matches your runtime.","Test async polars paths in CI under the same loop policy as production."],"tags":["asyncio","event-loop","polars"],"backgroundTag":"invalid-argument-value","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"}