global variables shared across modules

MackS mackstevenson at hotmail.com
Fri Sep 9 19:12:42 EDT 2005


Hello everyone

Consider the following two simple files. The first is my "program", the
other a file holding some global variable definitions and code shared
by this program and  a "twin" program (not shown here):

program1.py:
------------

from shared import *

fun()

print "at top level: " + global_var


shared.py:
----------

global_var = "original value"

def fun():

    global global_var

    global_var = "changed value!"

    print "inside fun(): " + global_var

    return

------

When I run program1.py, I get

inside fun(): changed value!
at top level: original value!

How can I get the changed value to "persist" in such a way that it
isn't reset when control leaves fun()? Why is it even reset in the
first place? After all, the module has already been imported (and the
initialization of global_var executed) *before* fun() runs, right?

Any clarification and help in solving this would be great

Thanks

Mack




More information about the Python-list mailing list