[Python-Dev] Tricky way of of creating a generator via a comprehension expression (original) (raw)

Chris Angelico rosuav at gmail.com
Thu Nov 23 09:25:15 EST 2017


On Fri, Nov 24, 2017 at 1:21 AM, Paul Moore <p.f.moore at gmail.com> wrote:

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.

A while back I had a POC patch that made "with EXPR as NAME:" create a new subscope with NAME in it, such that the variable actually disappeared at the end of the 'with' block. Should I try to track that down and adapt the technique to comprehensions? The subscope shadows names exactly the way a nested function does, but it's all within the same function.

ChrisA



More information about the Python-Dev mailing list