python
runtime_error
ai_generated
true
RuntimeError: Task <Task pending name='Task-1' coro=<foo()>> got Future <Future pending> attached to a different loop
ID: python/asyncio-task-got-future-different-loop
80%Fix Rate
87%Confidence
0Evidence
2024-05-02First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.9 | active | — | — | — |
| 3.10 | active | — | — | — |
| 3.11 | active | — | — | — |
| 3.12 | active | — | — | — |
Root Cause
A coroutine created under one event loop is awaited under another loop, so the Future it holds belongs to a different loop than the Task waiting on it.
generic中文
在一个事件循环下创建的协程在另一个循环中被 await,导致其持有的 Future 与等待它的 Task 属于不同的事件循环。
Workarounds
-
90% success
async def main(): # session created inside the loop that will use it async with aiohttp.ClientSession() as session: await session.get(url) asyncio.run(main()) -
85% success
future = asyncio.run_coroutine_threadsafe(coro(), target_loop) result = future.result(timeout=10)
Dead Ends
Common approaches that don't work:
-
75% fail
get_event_loop() can return the same stale loop or raise DeprecationWarning in newer versions; it does not reconcile two loops.
-
90% fail
Sleeping does not migrate a Future between loops; the ownership mismatch remains.