block scope?

Paddy paddy3118 at googlemail.com
Sun Apr 8 06:36:42 EDT 2007


On Apr 7, 4:48 am, James Stroud <jstr... at mbi.ucla.edu> wrote:
> Neal Becker wrote:
> > One thing I sometimes miss, which is common in some other languages (c++),
> > is idea of block scope.  It would be useful to have variables that did not
> > outlive their block, primarily to avoid name clashes.  This also leads to
> > more readable code.  I wonder if this has been discussed?
>
> Probably, with good code, block scope would be overkill, except that I
> would welcome list comprehensions to have a new scope:
>
> py> i
> ------------------------------------------------------------
> Traceback (most recent call last):
>    File "<ipython console>", line 1, in <module>
> <type 'exceptions.NameError'>: name 'i' is not defined
>
> py> [i for i in xrange(4)]
> [0, 1, 2, 3]
> py> i  # hoping for NameError
> 3

Yep, i think that we need consistent scope rules for
listexps and genexps. Isn't it coming in 3.0?

If it is, then maybe it will be back-ported to
Python 2.6.

In Python 2.5 we have the following:

>>> [k for k in (j for j in range(5))]
[0, 1, 2, 3, 4]
>>> k
4
>>> j
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
NameError: name 'j' is not defined
>>>

- Paddy.




More information about the Python-list mailing list