跳到内容

asyncio-dangling-task (RUF006)

作用

检查未存储返回结果引用的 asyncio.create_taskasyncio.ensure_future 调用。

为什么这不好?

根据 asyncio 文档,事件循环仅保留对任务的弱引用。如果 asyncio.create_taskasyncio.ensure_future 返回的任务未存储在变量、集合或以其他方式引用,则可能随时被垃圾回收。这可能导致意外和不一致的行为,因为您的任务可能会或可能不会运行完成。

示例

import asyncio

for i in range(10):
    # This creates a weak reference to the task, which may be garbage
    # collected at any time.
    asyncio.create_task(some_coro(param=i))

建议改为

import asyncio

background_tasks = set()

for i in range(10):
    task = asyncio.create_task(some_coro(param=i))

    # Add task to the set. This creates a strong reference.
    background_tasks.add(task)

    # To prevent keeping references to finished tasks forever,
    # make each task remove its own reference from the set after
    # completion:
    task.add_done_callback(background_tasks.discard)

参考