python
type_error
ai_generated
true
类型错误:期望一个协程,但得到 <class 'str'>
TypeError: a coroutine was expected, got <class 'str'>
ID: python/asyncio-sync-primitive-type-error
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.
解决方案
-
95% 成功率 Ensure the function is defined as async and called correctly
async def my_coro(): return 'result' await asyncio.gather(my_coro()) -
90% 成功率 Use asyncio.iscoroutine() to check before passing
if asyncio.iscoroutine(obj): await asyncio.gather(obj) else: # handle non-coroutine
无效尝试
常见但无效的做法:
-
Wrapping the object in a list
70% 失败
The function still expects coroutines, not a list of strings.
-
Using asyncio.ensure_future() on the object
60% 失败
ensure_future() expects a coroutine or future, not a string.