Saturday, 4 September 2021

Why do we need `async for` and `async with`?

What's the point of introducing async for and async with? I know there are PEPs for these statements, but they are clearly intended for language designers, not average users like me. A high-level rationale supplemented with examples would be greatly appreciated.

I did some research myself and found this answer:

The async for and async with statements are needed because you would break the yield from/await chain with the bare for and with statements.

The author didn't give an example of how the chain might be broken though, so I'm still confused. Furthermore, I notice that Python has async for and async with, but not async while and async try ... except. This sounds strange because for and with just syntax sugars for while and try ... except respectively. I mean, wouldn't async versions of the latter statements allow more flexibility, given that they are the building blocks of the former?

There is another answer discussing async for, but it only covers what it is not for, and didn't say much about what it is for.

As a bonus, are async for and async with syntax sugars? If they are, what are their verbose equivalent forms?



from Why do we need `async for` and `async with`?

No comments:

Post a Comment