pola-rs/polars · error · ValueError
Can't patch loop of type
Error message
Can't patch loop of type %s
What it means
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.
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.
Example fix
// before import uvloop uvloop.install() df.lazy().collect(engine="async") // after import asyncio asyncio.run(pl.LazyFrame.collect_async(df.lazy()))
Defensive patterns
Strategy: type-guard
Validate before calling
import asyncio
def ensure_patchable_loop(loop):
if not isinstance(loop, asyncio.BaseEventLoop):
raise TypeError(f"expected asyncio event loop, got {type(loop)}")
return loop Type guard
def is_asyncio_loop(loop) -> bool:
import asyncio
return isinstance(loop, asyncio.BaseEventLoop) Try / catch
try:
result = polars_async_entry(...)
except ValueError as e:
if "Can't patch loop of type" in str(e):
result = asyncio.run(fallback_coro())
else:
raise Prevention
- 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.
When it happens
Trigger: 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.
Common situations: 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).
Understand the failure class
Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.
Related errors
- Event loop stopped before Future completed.
- asyncio is already patched by nest_asyncio
- {0}
- a more recent version of `fastexcel` is required for…
- a more recent version of `fastexcel` is required for…
AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18).
Data as JSON: /api/errors/0c710a3068712edb.
Report an issue: GitHub.
Appendix: source
Thrown at py-polars/src/polars/_utils/nest_asyncio.py:392
try:
self._set_coroutine_origin_tracking(self._debug)
if self._asyncgens is not None:
sys.set_asyncgen_hooks(
firstiter=self._asyncgen_firstiter_hook,
finalizer=self._asyncgen_finalizer_hook,
)
yield
finally:
self._set_coroutine_origin_tracking(False)
if self._asyncgens is not None:
sys.set_asyncgen_hooks(*old_agen_hooks)
def _check_running(self):
"""Do not throw exception if loop is already running."""
pass
if not isinstance(loop, asyncio.BaseEventLoop):
raise ValueError("Can't patch loop of type %s" % type(loop))
if not isinstance(loop._ready, _ReentrantReady):
old_ready, loop._ready = loop._ready, _ReentrantReady()
while old_ready:
loop._ready.append(old_ready.popleft())
if hasattr(loop, "_nest_patched"):
return
cls = loop.__class__
cls.run_forever = run_forever
cls.run_until_complete = run_until_complete
cls._run_once = _run_once
cls._check_running = _check_running
cls._check_runnung = _check_running # typo in Python 3.7 source
cls._num_runs_pending = 1 if loop.is_running() else 0
cls._is_proactorloop = os.name == "nt" and issubclass(
cls, asyncio.ProactorEventLoop
)
if sys.version_info < (3, 7, 0):
cls._set_coroutine_origin_tracking = cls._set_coroutine_wrapperView on GitHub (pinned to fe841f959e)