[Python-3000] end scope of iteration variables after loop

Alex Martelli aleaxit at gmail.com
Fri Apr 18 17:57:35 CEST 2008


On Fri, Apr 18, 2008 at 8:29 AM, Richard Thomas
<R.W.Thomas.02 at cantab.net> wrote:
> I like that loop variables end up still in scope, as demonstrated so
>  far on this list it is quite useful, but only when there is a break
>  somewhere. The one that confuses me, therefore, is the dummy variables
>  in a generator expression leaking into the scope defining that
>  expression. Hence:
>
>  x = 0
>  L = [f(x) for x in range(2)]
>  assert x == 1

There is no genexp here -- this is a list comprehension.  Generator
expressions do NOT leak their control variable; LCs were originally
designed to leak (to mimic a for loop's semantics exactly) and thus
had to remain that way throughout 2.* -- BUT that's changed in 3.0
(download and try the alpha!), where LCs don't "leak" any more.

>  This is not particularly intuitive as the for loop in a generator
>  expression can never break; generator expressions feel more "closed".

They are and always have been; list comprehensions also become that
way in 3.* (can't change in 2.* for obvious reasons of backwards
compatibility).


Alex


More information about the Python-3000 mailing list