What does the keyword 'global' really mean

Hans Nowak hans at zephyrfalcon.org
Tue Sep 9 10:58:02 EDT 2003


John Dean wrote:

> Hi
> I have been looking through some Python code and I came across the keyword
> 'global'. I have looked through the docs and two or three Python programming
> books for a full explanation of what 'global' really means. Would I be
> correct in assuming that any variable prefixed with the keyword global would
> allow that variable to be accessible across translation units, in other
> words global is equivalent to the 'C' keyword 'extern' ?

It's really quite simple.  Within a function, assignments are local (by default):

 >>> x = 42
 >>> def f():
	x = 3
	print x
	
 >>> f()
3
 >>> x
42

When executing f(), it creates a local variable x with value 3, and prints it. 
  The global variable x is unaffected.

You can change this behavior by using the 'global' statement:

 >>> def g():
	global x
	x = 6
	print x
	
 >>> g()
6
 >>> x
6

'global x' tells Python that the x in this function is global rather than 
local, so 'x = 6' refers to the global variable x we already created.  (As a 
side note, it may seem like you change an existing variable, but what it 
actually does it rebind the name 'x' that already existed in the global namespace.)

As you can see, the global variable x is overwritten and how has a value of 6.

To make matters a bit more confusing, you don't need 'global' to *access* a 
global variable from within a function, only when you assign to it.  This works:

 >>> def h():
	print x
	
 >>> h()
6

There's no local variable x this time, but 'x' obviously refers to the global one.

> Also, does Python have the equivalent of the 'C' keyword 'static'?

No.  There are (clumsy) ways to fake it, but you'll probably be better off 
writing code in a Pythonic way, rather than trying to emulate a C style.

HTH,

-- 
Hans (hans at zephyrfalcon.org)
http://zephyrfalcon.org/







More information about the Python-list mailing list