python runtime_error ai_generated true

RuntimeError: Task <Task pending> got Future <Future pending> attached to a different loop

ID: python/asyncio-future-attached-to-loop

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-10-10First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8 active
3.9 active
3.10 active

Root Cause

A coroutine or task awaits a Future that belongs to a different event loop, often due to mixing loops across threads or using asyncio.gather with tasks from different loops.

generic

中文

协程或任务等待了一个属于不同事件循环的 Future,通常是由于跨线程混合循环或在 asyncio.gather 中使用来自不同循环的任务。

Workarounds

  1. 90% success Ensure all coroutines and futures are created in the same event loop
    loop = asyncio.new_event_loop(); asyncio.set_event_loop(loop); loop.run_until_complete(main())
  2. 95% success Use asyncio.run() to avoid loop conflicts entirely
    async def main(): await asyncio.gather(coro1(), coro2()); asyncio.run(main())

Dead Ends

Common approaches that don't work:

  1. Creating a new loop and setting it globally 60% fail

    The Future is still attached to the original loop; global setting does not migrate it.

  2. Using asyncio.ensure_future instead of create_task 70% fail

    ensure_future also attaches to the current loop; same issue.