【Python】async与await用法

async用于修饰函数,将普通函数变为异步函数。

async def t2():
    print(2)

直接调用异步函数不会返回结果,而是返回一个协程对象。
协程需要通过其他方式来驱动,如async.run函数。

await函数只能在异步函数中使用,可以通过该关键字,挂起当前协程,让另一个协程执行完毕,再次执行本协程。

import asyncio
 
async def t2():
    print(2)

async def t1():
    await t2()
    print(1)
 
# execute the asyncio program
asyncio.run(t1())

输出:

2
1

async with

异步上下文管理器和普通的with类似。async with后跟随的对象必需实现__aenter____aexit__函数,异步上下文管理器必需在异步函数中使用。

语法如下:

async with EXPR as VAR:
    BLOCK

在执行BLOCK之前会先执行EXPR__aenter__异步函数,然后将返回值赋值给VARBLOCK执行完毕后,会执行EXPR__aexit__函数。

上述代码等同于以下代码:

mgr = (EXPR)
aexit = type(mgr).__aexit__
aenter = type(mgr).__aenter__(mgr)
exc = True

VAR = await aenter
try:
    BLOCK
except:
    if not await aexit(mgr, *sys.exc_info()):
        raise
else:
    await aexit(mgr, None, None, None)

async for

async for和普通的for类似,async for用于遍历异步迭代器。异步迭代器需要实现__aiter____anext__函数。

语法如下:

async for TARGET in ITER:
    BLOCK
else:
    BLOCK2

TARGET是调用了迭代器__anext__函数的返回值。上述语法等同于以下代码:

iter = (ITER)
iter = type(iter).__aiter__(iter)
running = True
while running:
    try:
        TARGET = await type(iter).__anext__(iter)
    except StopAsyncIteration:
        running = False
    else:
        BLOCK
else:
    BLOCK2
posted @ 2023-11-26 13:29  NotReferenced  阅读(245)  评论(0编辑  收藏  举报