Global variables in modules/functions

Scott David Daniels Scott.Daniels at Acm.Org
Fri Nov 19 19:09:06 EST 2004


Aaron Deskins wrote:
> I'm trying to write program with a main.py and several functions 
> distributed in auxiliary *.py files. I've looked through the archives on 
> the 'global' keyword, but I'm still not sure how to get this right. I 
> want to be able to have some variables that can be accessed/changed by 
> many modules/functions.
The easiest way to do this is to create a module named "globals", and
have any modules wanting to work like:

import globals
...
def change_n():
     globals.n = 2

Here's an example.
____________
main.py
____________
import globals, change
globals.n = 1
change.change_n()
print globals.n
____________
change.py
____________
import globals
def change_n():
     globals.n = 2

There are ways to force python into doing what you want, but they are
fraught with peril.

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list