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

Nick Coghlan ncoghlan at gmail.com
Mon Nov 6 10:22:25 CET 2006


Georg Brandl wrote:
> Marcin 'Qrczak' Kowalczyk wrote:
>> The rule should be:
>>
>> The keyword 'nonlocal' causes the lookup to be performed as if there
>> were no assignments to that variable in the scope containing the
>> 'nonlocal' declaration.
> 
> Plus, if there's no binding in an enclosing scope, an error is raised.
> 
> (Which brings up the assymetry to today's global again, but is that really
> a problem?)

I'd narrow the requirement such that module globals don't count - if you 
declare a variable nonlocal it *must* be initialised in an enclosing function 
scope or you will get a syntax error similar to this one:

 >>> def f():
...   x = 1
...   del x
...   def g():
...     return x
...   return g
...
SyntaxError: can not delete variable 'x' referenced in nested scope

Here, the compiler knows that g() references back to 'x' and hence considers 
the attempt to delete 'x' nonsensical. Attempting to reference 'nonlocal x' 
when x isn't a closure variable is also nonsensical - if you want a local 
variable then remove the declaration, if you want a global then declare x as a 
global.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://www.boredomandlaziness.org


More information about the Python-3000 mailing list