[Python-3000] The meaning of "global variable"

Ron Adam rrr at ronadam.com
Sun Nov 5 22:16:34 CET 2006


Georg Brandl wrote:
> Ron Adam wrote:
> 
>> I presume you meant:
>>
>>     def f():
>>       x = 42
>>       def g():
>>         def h():
>>           parent x
>>           x = 88
>>
>>
>> The x would be a new local x in function g and have no effect on the x in 
>> function f.  Parent would do exactly what it means in this case, its a reference 
>> to a name in only the parent scope.
> 
> This *is* confusing, even if the word "parent" is a slight hint on what's
> really going on.

Why is it confusing to you, what would you expect to happen here?

     def f():
       def g():
         def h():
           parent x
           x = 42

By not limiting parent to just the parent scope you create exceptions.  The rule 
becomes:


     The keyword (*)nonlocal designates a name will be written to in the
     closest enclosing "parent" scope *except* when a pre-existing matching name
     exists in a scope further up.

To me that is more confusing than always referring to the closest enclosing 
scope without exception.

(*) Nonlocal is better a better term for implicit scope selection.  Parent is 
better suited for the explicit scope selection suggested.  See below.


>> Unless you were to do:
>>
>>     def f():
>>       x = 42
>>       def g():
>>         parent x
>>         def h():
>>           parent x
>>           x = 88
>>
>> Then all references to x would be the local x in function f.
> 
> "So why do I have to declare x in g, if I don't use it there?" This is really
> ugly.
> 
> Georg

It's a choice.

Explicit scope selection: This depends only on the existence of parent 
statements to determine which scope a name will be bound in.  Parent redirects 
an assignment to the parent scope.  Successive parent statements can redirect 
the binding of names to scopes further up.

Implicit scope selection: This depends on the pre-existence of a matching bound 
name in *any* parent scope to determine where write access will be allowed.  If 
no matching name if found write access will be the nearest enclosing scope.

There are more opportunities for silent bugs with the looser implicit scope 
selection.  That was the point I was making.  I'll leave it up to the experts to 
  decide which is better.

Cheers,
    Ron













More information about the Python-3000 mailing list