[Python-Dev] accumulator display syntax

Guido van Rossum guido at python.org
Tue Oct 21 16:06:45 EDT 2003


> > I meant that the compiler should rename it.
> 
> Implementing this might be entertaining.  In particular what happens
> if the iteration variable is a local in the frame anyway?  I presume
> that would inhibit the renaming, but then there's a potentially
> confusing dichotomy as to whether renaming gets done.  Of course
> you could *always* rename, but then code like 
> 
> def f(x):
>     r = [x+1 for x in range(x)]
>     return r, x
> 
> becomes even more incomprehensible (and changes in behaviour).

Here's the rule I'd propose for iterator comprehensions, which list
comprehensions would inherit:

    [<expr1> for <vars> in <expr2>]

The variables in <vars> should always be simple variables, and their
scope only extends to <expr1>.  If there's a variable with the same
name in an outer scope (including the function containing the
comprehension) it is not accessible (at least not by name) in
<expr1>.  <expr2> is not affected.

In comprehensions you won't be able to do some things you can do with
regular for loops:

    a = [1,2]
    for a[0] in range(10): print a

> And what about horrors like
> 
>     [([x for x in range(10)],x) for x in range(10)]
> 
> vs:
> 
>     [([x for x in range(10)],y) for y in range(10)]
> 
> ?
> 
> I suppose you could make a case for throwing out (or warning about)
> all these cases at compile time, but that would require significant
> effort as well (I think).

I think the semantics are crisply defined, users who write these
deserve what they get (confusion and the wrath of their readers).

--Guido van Rossum (home page: http://www.python.org/~guido/)



More information about the Python-Dev mailing list