Understanding ‘global’ in Python
In one forum I read, many people do not seem to know how to use the global keyword in Python. The most common misconception is that the declaration global foo will make foo global. That is wrong. global tells Python to use the global definition of foo instead of creating a local definition. Let’s see with an example.
>>> foo = "foo"
>>> def func1():
... foo = "bar"
... print "Inside func1():", foo
...
>>> def func2():
... global foo
... foo = "baz"
... print "Inside func2():", foo
...
>>> print foo
foo
>>> func1()
Inside func1(): bar
>>> print foo
foo
>>> func2()
Inside func2(): baz
>>> print foo
baz
>>>
In func1(), when I assigned the string bar to foo, Python created a new foo, local to func1() which shadowed the original foo. Which is why before and after the function call, the value of foo (the global one) was “foo”.
Inside func2(), I specifically told Python that I wanted to use the global value of foo, not create a new local one like I did in func1(). This is why the value of foo (the global one) is changed when we do print foo after the function call.

Jasmine:
Great insight! That really helped me out.
17 October 2008, 2:45 pm