Global variable oddness w/short code example

Geoffrey Mainland mainland at apeiron.net
Mon Jun 2 19:42:23 EDT 2003


I've run into some global variable oddness with Python 2.2.2 (running
under FreeBSD). As I understand it, global variables are global only
within a module. However, as the code below demonstrates, when module A
creates a global and then calls a function in module B which accesses the
new global (via the construct A.theGlobal), the global is not seen. Can
anyone explain the following oddness?

% python A.py
TestA thinks a.globalA is 'this is global A' I think globalB is: 'this is
global B' TestB thinks a.globalB is 'foo' Traceback (most recent call
last):
  File "A.py", line 27, in ?
    B.TestC()
  File "B.py", line 11, in TestC
    print "TestC thinks a.globalC is '%s'" % A.globalC
AttributeError: 'module' object has no attribute 'globalC'

---------- begin A.py ----------
import B

global globalB

globalB = "foo"

def SetGlobalA():
	global globalA
	globalA = "this is global A"

def SetGlobalB():
	global globalB
	globalB = "this is global B"

def SetGlobalC():
	global globalC
	globalC = "this is global C"

if __name__ == "__main__":
	B.TestA()
	
	SetGlobalB()
	print "I think globalB is: '%s'" % globalB B.TestB()
	
	SetGlobalC()
	B.TestC()

---------- end A.py ----------
---------- begin B.py ----------
import A

def TestA():
	A.SetGlobalA()
	print "TestA thinks a.globalA is '%s'" % A.globalA

def TestB():
	print "TestB thinks a.globalB is '%s'" % A.globalB

def TestC():
	print "TestC thinks a.globalC is '%s'" % A.globalC

---------- end B.py ----------




More information about the Python-list mailing list