By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,428 Members | 1,340 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,428 IT Pros & Developers. It's quick & easy.

global variables shared across modules

P: n/a
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

Sep 9 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a

MackS wrote:
print "inside fun(): " + global_var .... 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


It _does_ persist and it _isn't_ reset. Try:

import shared
print shared.global_var

at the end of your program, and you will see that you have bound the
identifier global_var in your main program to the same immutable object
that the identifier global_var in shared was bound to, and then you
_changed_ the identifier global_var in shared to point to a different
object.

Sep 9 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.