Monday, June 27, 2011

Python global variables

Some things in python are weird, especially when considering global variables. Let's take the following code where we define two global variables (string and dict) and change their value inside the function.
dictionaryVar = {'A':"original"}
stringVar = "original"
globalStringVar = "original"

def aFunction():
    global globalStringVar
    dictionaryVar['A']="changed"
    stringVar = "changed"
    globalStringVar="changed"
    return dictionaryVar, stringVar, globalStringVar

print "Output of the function is:"
a = aFunction()
print "Dictionary   : ",
print a[0]
print "String       : "+a[1]
print "Global String: "+a[2]
print "\nGlobal variables are now: "
print "Dictionary   : ",
print dictionaryVar
print "String       : "+stringVar
print "Global String: "+globalStringVar
And now when running the code we see the following output (Python 2.6.6) we see the following:
$ python tmp/foo.py 
Output of the function is:
Dictionary   :  {'A': 'changed'}
String       : changed
Global String: changed

Global variables are now: 
Dictionary   :  {'A': 'changed'}
String       : original
Global String: changed
So the conclusion is:
  • Global strings changed in a function are returned correctly, and not changed outside the scope of the function. (expected)
  • Global dictionaries changed in a function are returned correctly, but they are also changed outside the scope of the function. (not expected)
  • Global strings, declared as global (in the function), changed in a function are returned correctly, and are also changed outside the scope of the function. (expected)