Global variables and modules

dkeeney at dkeeney at
Fri Dec 24 06:43:40 CET 2004

I have a newby type question on how global variables work between

I have a module that defines a global variable as well as two
functions to operate on that variable.  A script imports the
three names and prints out values of the global between operations, and
the results aren't what I expected.

Here is the module,
glbl = 25

def inc_glbl():
global glbl
glbl += 1

def get_glbl():
global glbl
return glbl

and here is the test script,

from test2 import glbl, inc_glbl, get_glbl

print 'glbl orig      ', glbl

print 'glbl postinc   ', glbl

new = get_glbl()
print 'glbl from func ', new
I would expect the three values to be ( 25, 26, 26 ), but what I get is
glbl orig       25
glbl postinc    25
glbl from func  26

It seems that the references to 'glbl' are seeing a local copy, rather
than the original.  This is not what the literature says should be
happening.  I am looking for a way to share data between modules.  Can
you advise me on my error?  I am using Python 2.3.2 from ActiveState,
on Windows XP Pro.

Thank you

More information about the Python-list mailing list