block scope?

Steve Holden steve at holdenweb.com
Sat Apr 7 17:23:13 EDT 2007


Alex Martelli wrote:
> 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:-)]].
> 
What do you think the chances are of this being accepted for Python 3.0? 
It is indeed about the most rational approach, though of course it does 
cause problems with dynamic namespaces.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb     http://del.icio.us/steve.holden
Recent Ramblings       http://holdenweb.blogspot.com




More information about the Python-list mailing list