“AttributeError:模块‘asyncio’没有属性‘coroutine’。” 在Python 3.11.0中

12 python asynchronous python-3.x python-decorators python-asyncio

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

import asyncio

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

asyncio.run(test())
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

AttributeError:模块“asyncio”没有属性“coroutine”。您的意思是:“协程”吗?

据我谷歌搜索,我发现@asyncio.coroutine装饰器用于某些代码。

那么,我该如何解决这个错误呢?

小智 12

自Python 3.11起,包含@asyncio.coroutine装饰器的基于生成器的协程已被删除,因此模块没有装饰器,如错误所示:asyncio@asyncio.coroutine

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

因此,您需要使用beforeasync关键字def,如下所示:

import asyncio

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

asyncio.run(test()) # Test
Run Code Online (Sandbox Code Playgroud)

然后,您可以解决该错误:

Test
Run Code Online (Sandbox Code Playgroud)