Rebinding variable, despite global statement

Brian Leair telcom_sage at yahoo.com
Mon Aug 2 22:46:19 EDT 2004


I am using "from MyModule import *", (yes, yes, I know)

MyModule has a variable "g_my_var" at the "global" scope.

In the code that performs the import, I have a function that has the
statement
"global g_my_var". Despite this, when I try to assign to g_my_var it
appears I am rebound to a different object.
Beyond philosophical arguments about not using a "global" variable, is
there a real reason why I can't assign to the global "g_my_var". I'm
using python 2.3.2.

One workaround is to place getter/setters in MyModule, but I was still
surprised by this behavior. 




----------------------- MyModule.py -----------------------------
g_my_var = 142

def UtilityFunction ():
	print "Inside UtilityFunction", g_my_var
	print "Inside UtilityFunction Id is", id (g_my_var)
	return

----------------------- MyProgram.py -----------------------------
from MyModule import *

def ProgramFunction ():
	global g_my_var
	UtilityFunction ()
	print "In ProgramFunction", g_my_var
	print "In ProgramFunction Id is", id (g_my_var)
	print "Now assigning a value of 42 in ProgramFunction."
	g_my_var = 42
	print "After assignment, in ProgramFunction", g_my_var
	print "After assignment, in ProgramFunction Id is", id (g_my_var)
	UtilityFunction ()
	return

print "Excuting Main Program"
UtilityFunction ()
ProgramFunction ()

=============== Output ======================
Excuting Main Program
Inside UtilityFunction 142
Inside UtilityFunction Id is 7625912
Inside UtilityFunction 142
Inside UtilityFunction Id is 7625912
In ProgramFunction 142
In ProgramFunction Id is 7625912
Now assigning a value of 42 in ProgramFunction.
After assignment, in ProgramFunction 42
After assignment, in ProgramFunction Id is 8008553
Inside UtilityFunction 142
Inside UtilityFunction Id is 7625912



More information about the Python-list mailing list