global variables shared across modules

M

MackS

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
 
P

Patrick Maupin

MackS said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,812
Latest member
GracielaWa

Latest Threads

Top