how does global work?

Thomas Wouters thomas at xs4all.net
Mon May 15 08:12:50 EDT 2000


On Mon, May 15, 2000 at 10:15:29AM +0000, moonseeker at my-deja.com wrote:

> How does the statement 'global' works?
> I can't figure out how to use it correct.
> I have read the Python reference but it didn't clear my mind...

It's really very simple ;) 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.)

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list