Entry
How does the statement 'global' work?
Mar 31st, 2009 11:34
Scott Mandarich, unknown unknown, Remco Gerlich, Thomas Wouters
Answer1:
Inside functions, if you assign to a variable, it is assumed to be
local
to the function. If you want to assign to a global (module namespace)
variable, you'll have to tell Python that it's a global first.
ie,
x = 4
def spam():
x = 5
spam()
Doesn't change the module's x. But
x = 4
def spam()
global x
x = 5
spam()
does.
If, inside a function, you only use the variable and never assign to
it,
it can't be a local variable, so Python assumes you mean a global.
This doesn't only hold for functions, but classes and methods too.
Answer2:
Python has two namespaces it uses for name lookups: the 'local'
namespace and the 'global' namespace (you could call it the 'search
path'.) The local namespace is the function or class you are in, the
global namespace is the namespace of the module. If you are not in a
function or class, the local namespace is the global namespace.
However, *assigning* to a variable does not use this search path !
Instead, if you assign, you always assign in the local namespace. So,
for instance:
X = None
def FillX(x):
X = x
would not work, because the X you assign to, is the *local* X, not the
global one. This wouldn't even generate an error, by the way. Even more
confusing is it if you read from and assign to 'X' in the same
function:
X = None
def FillX(x):
if not X:
X = x
In Python 1.5.2, this generates a NameError:
Traceback (innermost last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in FillX
NameError: X
and in Python 1.6, an UnboundLocalError:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in FillX
UnboundLocalError: X
It generates this strange error because the 'X' name exists in the
local
namespace, but at the time of the test on X, it isn't filled in yet.
The
interpreter knows it should be there, but can't find it at the time of
execution.
And this is what the 'global' keyword is for. It says 'this name is
global, *even if* it gets assigned to. You only need it when you are
assigning to globals, not when you are mutating them (appending to
lists, adding to dictionaries, etc.)
http://www.golfgolfcourses.com/index.php?q=Wisconsin