Python 中的async

1,918 阅读1分钟

Python使用async关键字声明的函数其返回值是一个coroutine, 而不再是一个具体的返回值。

传统上,

def add(a: int, b: int) -> int:
    return a + b

调用 add(1, 2), 其返回值为3, type(add(1,2)) 返回值为int, 而经过async修饰过的函数其返回值就不同了.

import asyncio
async def add(a: int, b: int) -> int:
    await asyncio.sleep(1)
    return a + b

调用add(1, 2), 返回值其实是一个corountine, type(add(1,2)) # coroutine, 如果要获取这个coroutine的结果,需要调用await add(1,2), 也就是说add(1,2) 这个coroutine实现了 __awaitable__协议,所以需要采用await add(1,2)的方式才能获取结果, isinstance(add(1,2), Awaitable) # True.

所以, async 是一种生产coroutine对象的简便方式, 获取结果还需要await一下。