You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3.11.0使用@asyncio.coroutine装饰器报错AttributeError如何解决

解决Python 3.11中asyncio.coroutine不存在的错误

问题原因

Python 3.10已正式移除asyncio.coroutine装饰器,Python 3.11中该属性完全不存在,因此运行依赖此装饰器的旧代码会触发AttributeError。

解决方案

1. 改用现代异步语法(推荐)

直接使用Python 3.5+引入的async def语法定义协程,这是官方推荐的标准写法,无需额外装饰器:

import asyncio

async def test():
    print("Test")

asyncio.run(test())

async def定义的协程可直接被asyncio.run()调用,代码简洁易读,完全符合当前Python异步编程规范。

2. 临时兼容旧代码(不推荐)

如果需要临时兼容仍使用该装饰器的旧代码,可以改用asyncio.coroutines.coroutine(仅作过渡,建议尽快迁移到async def):

import asyncio

@asyncio.coroutines.coroutine
def test():
    print("Test")

asyncio.run(test())

注意事项

官方已明确废弃基于装饰器的协程定义方式,所有新代码都应优先使用async def语法,避免依赖已移除的API。

内容的提问来源于stack exchange,提问作者Super Kai - Kazuya Ito

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 18:20:35