D
dkeeney
I have a newby type question on how global variables work between
modules.
I have a module test2.py that defines a global variable as well as two
functions to operate on that variable. A script test1.py 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, test2.py
------------------------------------
glbl = 25
def inc_glbl():
global glbl
glbl += 1
def get_glbl():
global glbl
return glbl
------------------------------------
and here is the test script, test1.py
-------------------------------------
from test2 import glbl, inc_glbl, get_glbl
print 'glbl orig ', glbl
inc_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
c:\projects\pitcher_model>test1.py
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
David
modules.
I have a module test2.py that defines a global variable as well as two
functions to operate on that variable. A script test1.py 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, test2.py
------------------------------------
glbl = 25
def inc_glbl():
global glbl
glbl += 1
def get_glbl():
global glbl
return glbl
------------------------------------
and here is the test script, test1.py
-------------------------------------
from test2 import glbl, inc_glbl, get_glbl
print 'glbl orig ', glbl
inc_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
c:\projects\pitcher_model>test1.py
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
David