{"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/df599052daf96e7a9cc30a3b0c6bd25d6947e3c0/py-polars/src/polars/_utils/nest_asyncio.py#L374-L410","documentation":"To run async drivers synchronously, polars patches the current event loop with vendored nest_asyncio, which requires an asyncio.BaseEventLoop subclass (it replaces run_forever/run_until_complete/_run_once and swaps _ready). C-implemented loops such as uvloop.Loop do not derive from BaseEventLoop, so apply() raises this ValueError naming the loop type.","triggerScenarios":"pl.read_database(...) while uvloop is the active loop — installed explicitly via uvloop.install()/asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) or by a web framework (uvicorn, sanic) hosting the code that then calls polars.","commonSituations":"Async web services (uvloop is the default in many) that also call pl.read_database inline; test harnesses that install uvloop globally for speed.","solutions":["Use a synchronous database driver/connection for read_database in that process","Run the read in a subprocess or worker with the default policy: asyncio.set_event_loop_policy(asyncio.DefaultEventLoopPolicy())","Await the async connector yourself and build the DataFrame (pl.from_arrow), avoiding the loop patch entirely"],"exampleFix":"# before\nuvloop.install()                       # app installed uvloop\ndf = pl.read_database(qry, connection=conn)  # ValueError: can't patch\n\n# after\ndf = pl.read_database(qry, connection=sync_conn)  # sync driver path","handlingStrategy":"type-guard","validationCode":"import asyncio\n\nloop = asyncio.get_event_loop()\nif not isinstance(loop, asyncio.BaseEventLoop):\n    raise RuntimeError(f\"cannot use async drivers with {type(loop).__name__}; use a sync driver\")","typeGuard":"import asyncio\n\ndef is_patchable_loop() -> bool:\n    try:\n        return isinstance(asyncio.get_event_loop(), asyncio.BaseEventLoop)\n    except RuntimeError:\n        return True  # no running loop; a fresh default loop will be used","tryCatchPattern":null,"preventionTips":["Do not install uvloop in processes that call pl.read_database with async connectors","Reset with asyncio.set_event_loop_policy(asyncio.DefaultEventLoopPolicy()) before such reads","Prefer sync database drivers in uvloop-based services"],"tags":["python","polars","asyncio","uvloop","database","event-loop","valueerror"],"backgroundTag":null,"analyzedSha":"df599052daf96e7a9cc30a3b0c6bd25d6947e3c0","analyzedAt":"2026-08-16T12:10:03.978Z","schemaVersion":2},"datasetVersion":"2026-08-16T13:17:31.715Z"}