python type_error ai_generated true

类型错误:期望一个协程,但得到 <class 'str'>

TypeError: a coroutine was expected, got <class 'str'>

ID: python/asyncio-sync-primitive-type-error

其他格式: JSON · Markdown 中文 · English
80%修复率
87%置信度
0证据数
2025-10-05首次发现

版本兼容性

版本状态引入弃用备注
3.8 active
3.9 active

根因分析

将非协程对象(例如字符串)传递给期望协程的 asyncio 函数,如 asyncio.wait() 或 asyncio.gather()。

English

A non-coroutine object (e.g., a string) is passed to asyncio functions like asyncio.wait() or asyncio.gather() that expect coroutines.

generic

解决方案

  1. 95% 成功率 Ensure the function is defined as async and called correctly
    async def my_coro():
        return 'result'
    await asyncio.gather(my_coro())
  2. 90% 成功率 Use asyncio.iscoroutine() to check before passing
    if asyncio.iscoroutine(obj):
        await asyncio.gather(obj)
    else:
        # handle non-coroutine

无效尝试

常见但无效的做法:

  1. Wrapping the object in a list 70% 失败

    The function still expects coroutines, not a list of strings.

  2. Using asyncio.ensure_future() on the object 60% 失败

    ensure_future() expects a coroutine or future, not a string.