Why read-only nested scopes?

Bengt Richter bokr at oz.net
Thu Sep 5 15:54:02 EDT 2002

On 05 Sep 2002 20:46:44 +0200, martin at v.loewis.de (Martin v. Loewis) wrote:

>bokr at oz.net (Bengt Richter) writes:
>> How about introducing an optional "degree of globalness" for the
>> global declaration? E.g.,
>>     x = 1
>>     def foo():
>>       x = 2
>>       def bar():
>>         x = 3
>>         def baz():
>>           global(1) x
>>           x = 4
>> would go outwards 1 nested scope and thus target the x in bar,
>> rebinding it from 3 to 4.
>That would work - although I'd claim that some users will find that
>notation plain ugly.
>It will also have confusing results:
>x = 1
>def foo():
>  print x
>  def bar():
>    global(1) x
>    x = 1
>At the moment, the "print x" in foo prints the global x, since there
>is no assignment to x, and hence there is no local variable foo. With
>the global statement, you declare that there is a local variable
>foo::x. As a result, since there is no assignment to foo::x, this
>would raise an UnboundLocal error.
I Python didn't effectively look ahead of the current line to decide what
scope a symbol belonged to, it wouldn't be a problem. The print x would
find the global x, and if bar were called after print x (and after its
definition, of course), then foo::x would be created, shadowing the global x,
and another print x following that would print the new (indistinguishable above)
value in foo::x.

IMO, that would be more intuitive too. Compare to:

[13:02] C:\pywk\junk>type foo.cpp
#include <cstdio>
int x = 123;
void foo(){
    printf("global x @ %p: %d\n", &x, x);
    int x(x);
    printf(" local x @ %p: %d\n", &x, x);
void main(){

[13:03] C:\pywk\junk>cl foo.cpp
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 12.00.8168 for 80x86
Copyright (C) Microsoft Corp 1984-1998. All rights reserved.

Microsoft (R) Incremental Linker Version 6.00.8168
Copyright (C) Microsoft Corp 1992-1998. All rights reserved.


[13:03] C:\pywk\junk>foo
global x @ 00406030: 123
 local x @ 0012FF74: 123

Bengt Richter

More information about the Python-list mailing list