if not global -- then what?

Gary Herron gherron at islandtraining.com
Sat Feb 20 15:00:32 EST 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:

mod.py:
gvar = 123       # A Global (like) value


main.py:
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

mod.py:
gvar=123
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. 

mode.py:
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