block scope?
Alex Martelli
aleax at mac.com
Sat Apr 7 13:04:32 EDT 2007
Neal Becker <ndbecker2 at gmail.com> wrote:
...
> > i = 5
> > for my i in xrange(4):
> > if i: # skips first when i is 0
> > my i = 100
> > if i:
> > print i # of course 100
> > break
> > print i # i is between 0 & 3 here
> > print i # i is 5 here
> >
> >
> > Doesn't leave a particularly bad taste in one's mouth, I guess (except
> > for the intended abuse).
> >
> > James
>
> Yes, the above is pretty much what I had in mind. +1.
I prefer Java's approach (14.4.2 in the JLS 2nd edition): forbid "inner"
blocks from shadowing variables in "outer" ones. I quote:
"""
If a declaration of an identifier as a local variable of the same
method, constructor, or initializer block appears within the scope of a
parameter or local variable of the same name, a compile-time error
occurs.
Thus the following example does not compile:
class Test {
public static void main(String[] args) {
int i;
for (int i = 0; i < 10; i++)
System.out.println(i);
}
}
This restriction helps to detect some otherwise very obscure bugs.
"""
I entirely agree with the JLS here, having fought just such bugs in C++
and other languages that lack the restriction in question. I just wish
Python had adopted the same restriction regarding nested functions, when
proper lexical scoping was introduced -- I argued for it at the time,
but backwards compatibility blocked its introduction. There are
definitely NOT many Java-specific language characteristics that I like,
but this one is a winner!-) [[but, I disagree with the lack in Java of
a similar restriction against shadowing between instance variables and
local variables, and the weak rationale for that in the JLS:-)]].
Alex
More information about the Python-list
mailing list