if not global -- then what?

Gary Herron gherron at islandtraining.com
Sat Feb 20 21:00:32 CET 2010

egasimus wrote:
> Hi, newbie here. I've read on using the 'global' keyword being
> discouraged; then what is the preferred way to have something, for
> example a class containing program settings, accessible from
> everywhere, in a program spanning multiple files?

Define your "global" in a module (a .py file) and import that wherever 
you need it:

gvar = 123       # A Global (like) value

import mod
... mod.gvar ...                # To access the value
... mod.gvar = 456 ...      #To change the value

Using the "global" keyword has nothing to do with this.  And in fact 
Python does not even have global variables in the sense you may be thinking.

If you wish to provide a function in mode.py that sets the value then 
this would fail

def SetGvar(v):
  gvar = v

because the gvar inside the function is local to that function.   This 
is the proper place to use the "global" keyword. 

gvar = 123
def SetGvar(v):
    global gvar   # Makes gvar refer to the (global) module level gvar
    gvar = v

Gary Herron

More information about the Python-list mailing list