[Python-Dev] Generator objects and list comprehensions?

Craig Rodrigues rodrigc at freebsd.org
Sun Jan 29 19:14:12 EST 2017


On Thu, Jan 26, 2017 at 4:09 AM, Ivan Levkivskyi <levkivskyi at gmail.com>
wrote:

>
>
> Concerning list/set/dict comprehensions, I am much more in favor of making
> comprehensions simply equivalent to for-loops (more or less like you
> proposed using yield from). The only reason to introduce auxiliary function
> scope was to prevent the loop variables from leaking outside comprehensions.
> Formally, this is indeed backward incompatible, but I doubt many people
> depend on the current counter-intuitive behavior.
>
> Concerning generator expressions, probably it is indeed better to simply
> prohibit yield inside them.
>
>
Thank you to everyone who responded to my post and provided excellent
analysis.

For Python, I don't know what the best way to proceed is:

OPTION 1
========

Make a SyntaxError:  [(yield 1) for x in range(10)]
and update the documentation to explain that this is an invalid construct.

This would have certainly helped me identify the source of the problem as I
tried porting buildbot 0.9 to Python 3.

However, while not very common, there is Python 2.x code that uses that.
I found these cases in the buildbot code which I changed so as to work on
Python 2 and 3:

https://github.com/buildbot/buildbot/pull/2661
https://github.com/buildbot/buildbot/pull/2673


 OPTION 2
=========
Make this return a list on Python 3, like in Python 2:  [
(yield 1) for x in range(10)]

As pointed out by others on the this mailing list, there are some
problems associated with that.  I don't know if there are many Python 2
codebases out there
with this construct, but it would be nice to have one less Python 2 -> 3
porting gotcha.


I'm OK with either approach.  Leaving things the way they are in Python 3
is no good, IMHO.
--
Craig
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20170129/da3909bd/attachment.html>


More information about the Python-Dev mailing list