laycat
laycat

Reputation: 5597

python3.6, difference between async with and await

newbie developer coming from python 3.4 here.

my naive understanding is only to use the keyword async with when I see that the coroutine is a context manager?

Upvotes: 14

Views: 6466

Answers (1)

a spaghetto
a spaghetto

Reputation: 1142

From PEP 492:

A new statement for asynchronous context managers is proposed:

async with EXPR as VAR:
    BLOCK

which is semantically equivalent to:

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

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

So yes -- it yields into the coroutine returned from the __aenter__ method of the given context manager, runs your block once it returns, then yields into the __aexit__ coroutine.

Upvotes: 15

Related Questions