14

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?

5
  • 1
    hiya, sorry I made you feel this way, I did look at the PEP 492 resource and it was a little terse. I'm kinda new and stupid, just wanted to confirm it. thanks :) Commented Jan 21, 2018 at 2:17
  • 1
    Fair enough. While as a stickler for rules I think your question is off topic for this site, as a person that's been in your general situation, I'm really glad you got the explanation you were looking for. I suppose that means that this will be legitimately useful to future visitors of the site, so close vote retracted. Commented Jan 21, 2018 at 4:41
  • thank you for your understanding! I did a quick search and there doesn't seem to be any comparisons between normal and asynchronous context managers, would be nice if someone could have some code examples :) Commented Jan 22, 2018 at 4:28
  • @MadPhysicist hey friend how have you been? I got a notification for "nice question badge" today. thank you again for giving this question a chance (I guess our discussion aged well). hope everything is well with you and your family during this tumultuous covid period. cheers :P Commented Nov 2, 2021 at 2:58
  • 1
    I suppose it did age fairly well. Good job on getting the badge. All's well here. Hope it's the same for you. Commented Nov 2, 2021 at 3:56

1 Answer 1

15

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.