Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 253
laycat Avatar asked Jan 21 '18 01:01

laycat


1 Answers

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.

like image 83
a spaghetto Avatar answered Sep 24 '22 13:09

a spaghetto