Global variables in modules/functions

Erik Max Francis max at alcyone.com
Fri Nov 19 19:00:43 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.

Globals aren't common to all modules.  You can think of globals as 
module-specific.  That is, the global n is not shared between your two 
modules.  It will be in one of the modules, and the other module can 
then reference it explicitly.  Something like (untested):

main.py
-------
import change
change.n = 1
change.change_n()
print change.n

change.py
---------
n = 0 # here's the actual global
def change_n():
     global n
     n = 2

-- 
Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   They have rights who dare defend them.
   -- Roger Baldwin



More information about the Python-list mailing list