在Python 3.11.0中出现了错误:"AttributeError: module 'asyncio' has no attribute 'coroutine'."

8
当我在Python 3.11.0上使用@asyncio.coroutine装饰器运行下面的代码时:
import asyncio

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

asyncio.run(test())

我遇到了以下错误:

AttributeError: module 'asyncio' has no attribute 'coroutine'. Did you mean: 'coroutines'?

我发现在一些代码中使用了@asyncio.coroutine装饰器,这是我通过谷歌搜索得知的。
那么,我该如何解决这个错误呢?
1个回答

10

基于生成器的协程包含了@asyncio.coroutine装饰器,自Python 3.11开始将其删除,因此asyncio模块不再具有@asyncio.coroutine装饰器,如下所示错误信息:

注意:基于生成器的协程支持已弃用,并已在Python 3.11中删除。

因此,您需要在def之前使用async关键字,如下所示:

import asyncio

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

asyncio.run(test()) # Test

然后,您可以解决这个错误:

Test

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接