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

Paul Moore p.f.moore at gmail.com
Thu Nov 23 09:21:32 EST 2017


On 23 November 2017 at 13:04, Ivan Levkivskyi <levkivskyi at gmail.com> wrote:
> Let us forget for a moment about other problems and focus on this one: list
> comprehension is currently not equivalent to a for-loop.
> There are two options:
> - Fix this, i.e. make comprehension equivalent to a for-loop even in edge
> cases (Serhiy seems ready to do this)
> - Prohibit all cases when they are not equivalent
>
> I still prefer option one. But I see your point, option two is also an
> acceptable fix.
> Note that there were not so many situations when some code became
> SyntaxError later.
> I don't see why this particular case qualifies for such a radical measure as
> an exception to syntactic rules,
> instead of just fixing it (sorry Nick :-)

My main concern is that comprehension is not equivalent to a for loop
for a specific reason - the scope issue. Has anyone looked back at the
original discussions to confirm *why* a function was used?

My recollection:

>>> i = 1
>>> a = [i for i in (1,2,3)]
>>> print(i)
1

Serihy's approach (and your described expansion) would have print(i)
return NameError.

So - do we actually have a proposal to avoid the implied function that
*doesn't* break this example? I'm pretty sure this was a real-life
issue at the time we switched to the current implementation.

Paul


More information about the Python-Dev mailing list