[Python-Dev] Tricky way of of creating a generator via a comprehension expression

Nick Coghlan ncoghlan at gmail.com
Thu Nov 23 05:55:42 EST 2017


On 23 November 2017 at 18:11, Greg Ewing <greg.ewing at canterbury.ac.nz>
wrote:

> Ivan Levkivskyi wrote:
>
>> "People sometimes want to refactor for-loops containing `yield` into a
>> comprehension but that doesn't work (particularly because of the hidden
>> function scope) - lets make it a SyntaxError"
>>
>
> Personally I'd be fine with removing the implicit function
> scope from comprehensions and allowing yield in them, since
> the semantics of that are clear.
>

People keep saying this, but seriously, those semantics aren't clear at all
once you actually start trying to implement it.

Yes, they're obvious in simple cases, but it isn't the simple cases that
are the problem.

Instead, things start getting hard once you're dealing with:

- unpacking to multiple variable names
- nested loops in the comprehension
- lexical closures inside the comprehension (e.g. lambda expressions,
comprehensions inside comprehensions)

Hence the approach we ended up going with for
https://bugs.python.org/issue1660500, which was to use a real function
scope that already handled all of those potential problems in a well
defined way.

Technically we *could* define new answers to all of those situations, but
then we're stuck explaining to everyone what those new behaviours actually
are, and I think that will actually be harder than the status quo, where we
only have to explain why these implicit scopes act much the same way that
"lambda: await expr" and "lambda: yield expr" do.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20171123/aef9bf99/attachment.html>


More information about the Python-Dev mailing list