[pypy-dev] RFC: draft idea for making for loops automatically close iterators

Nathaniel Smith njs at pobox.com
Mon Oct 24 03:24:42 EDT 2016


On Sun, Oct 23, 2016 at 11:42 PM, Armin Rigo <armin.rigo at gmail.com> wrote:
> Hi,
>
> On 24 October 2016 at 06:03, hubo <hubo at jiedaibao.com> wrote:
>> long time, which is what PyPy is for. Files may not be the most critical
>> problem, the real problem is LOCK - when you use with on a lock, there are
>> chances that it never unlocks.
>
> Bah.  I would say that it makes the whole "with" statement pointless
> in case you're using "await" somewhere inside it.  In my own honest
> opinion it should not be permitted to do that at all---like, it should
> be a SyntaxError to use "await" inside a "with".  (This opinion is
> based on a very vague understanding of async/await in the first place,
> so please take it with a grain of salt.)

Interesting historical tidbit: until PEP 342, it actually was a syntax
error to yield inside try, or at least inside try/finally.

Actually relevant modern answer: 'await' inside 'with' turns out to be
OK, because async functions are always run by some supervisor (like an
event loop), and so the solution is that the supervisor guarantees as
part of its semantics that it will always run async functions to
completion. (You're right that this isn't obvious though -- it took
very confused thread on the async-sig mailing list to recognize the
problem and solution.) Since event loops are already rocket science
and you only need one of them, requiring them to take some care here
isn't a big deal.

The problem with (async) generators is that everyone who uses them
also has to make some similar guarantee (i.e., they must be run to
completion, either by exhausting them or calling .close()), but they
get used all over the place in random user code, and it's not
reasonable to ask users to figure this out every time they write a
'for' loop.

-n

-- 
Nathaniel J. Smith -- https://vorpus.org


More information about the pypy-dev mailing list