[Python-Dev] replacing 'global'

Nick Coghlan ncoghlan at iinet.net.au
Tue Oct 28 06:19:31 EST 2003


The current situation:

Rebinding a variable at module scope:

 >>> def f():
       global x
       x = 1
 >>> f()
 >>> print x
1

If I try to write "global x.y" inside the function, Idle spits the dummy (and 
rightly so). I can rebind x.y quite happily, since I am only referencing x, and 
the lookup rules find the scope I need.

I don't see any reason for 'global <var> in <scope>' or syntactic sugar for 
nonlocal binding (i.e. ":=" ) to accept anything that the current global does not.

Similarly, consider the following from Idle:
 >>> def f():
	x += 1
	
 >>> x = 1
 >>> f()

Traceback (most recent call last):
   File "<pyshell#12>", line 1, in -toplevel-
     f()
   File "<pyshell#10>", line 2, in f
     x += 1
UnboundLocalError: local variable 'x' referenced before assignment

Augmented assignment does not currently automatically invoke a "global" 
definition now, so why should that change no matter the outcome of this discussion?


Guido's suggestion of "nonlocal" for a variant of global that searches 
intervening namespaces first seems nice - the term "non-local variable" 
certainly strikes me as the most freqently used way of referring to variables 
from containing scopes in this thread.

 >>> def f():
       def g():
         nonlocal x
         x = 1
       g()
       print x
 >>> f()
1

If 'nonlocal' was allowed only to _rebind_ variables, rather than create them at 
some other scope (probably advisable since 'nonlocal' merely says, 'somewhere 
other than here', which means there is no obvious suggestion for where to create 
the new variable - I could argue for either "module scope" or "nearest enclosing 
scope"). Defining it this way also allows catching problems at compile time 
instead of runtime (YMMV on whether that's a good thing or not)

At this point, Just's "rebinding variable from outer scope only" assignment 
operator "x := 1" might seem like nice syntactic sugar for "nonlocal x; x =1" 
(it wouldn't require a new keyword, either)

Is there really any need to allow anything more then replicating the search 
order for variable _reference_? Code which nests sufficient scopes that a simple 
'inside-out' search is not sufficient would just seem sorely in need of a 
redesign to me. . .

Regards,
Nick.

-- 
Nick Coghlan           |              Brisbane, Australia
ICQ#: 68854767         |               ncoghlan at email.com
Mobile: 0409 573 268   |   http://www.talkinboutstuff.net
"Let go your prejudices,
               lest they limit your thoughts and actions."




More information about the Python-Dev mailing list