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

Nick Coghlan ncoghlan at gmail.com
Sat Nov 4 04:23:03 CET 2006


Greg Ewing wrote:
> I don't see what's so important about treating the
> module namespace differently from other lexically
> enclosing scopes for the purpose of resolving names.
> Especially only for *assignment* to names.
> 
> For read access, we seem to get on just fine without
> any keywords to give us a hint what level to look
> in. What's different about assignment that we
> suddenly feel such a need for them?

Because read access doesn't have any non-local effects, but write access does. 
In most cases, it doesn't matter all that much which namespace a value came 
from, but where you are putting it can matter a great deal in terms of its 
visibility and lifecycle.

  1. Assigning to x when x is a local variable:
      - only this function and enclosed functions can see the change
      - 'x' will now be found in locals() in this function
      - reference lasts until end of current function execution

  2. Assigning to x when x is a global variable:
      - all code in this module can see the change
      - every user of the module can see the change (as a module attribute)
      - 'x' will now be found in globals() in this module
      - reference lasts until module dictionary is cleared

Currently, these are the only 2 possible cases. The PEP proposes adding a 3rd 
case:

  3. Assigning to x when x is a closure variable:
      - the enclosing function and all enclosed functions can see the change
      - will not cause 'x' to appear in either globals() or locals()
      - reference lasts until function object is destroyed

The 3rd case is significantly different from the 2nd in terms of both the 
visibility of any changes (particularly the points about whether or not 
changes are going to be visible as module attributes and entries in globals()) 
and the lifecycle of the reference (whether it is released along with the 
function object or the module dictionary).

Obscuring these differences by re-using the keyword global to denote write 
access to closure variables as well as global variables wouldn't be doing 
anyone any favours.

Cheers,
Nick.

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


More information about the Python-3000 mailing list