Q: Why does this work???

jepler at unpythonic.net jepler at unpythonic.net
Sun Jul 14 21:53:48 EDT 2002


You need only declare a variable "global" when you assign to it in a
function scope.  Example:

    def f():
	print x
The compiler can see that x is not assigned a value inside f, so for 'print
x' to be meaningful, it must refer to the global x.

    def g():
	x = 3
	print x
The compiler can see that x is assigned a value inside g, so it makes x a
local variable.

    def h():
	global x
	x = 3
	print x
Here, the 'global' statement makes x refer to a global name, even though
there is an assignment seen in the function's body.

The key here is that
    x[0] = 3
is not an assignment to x.  This is the same as
    x.__setitem__(0, 3)
and mutates (changes) the thing that x names, it does not make x name a new
thing.

Jeff





More information about the Python-list mailing list