how does global work?

Remco Gerlich scarblac-spamtrap at pino.selwerd.nl
Mon May 15 07:56:28 EDT 2000


moonseeker at my-deja.com wrote in comp.lang.python:
> 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...

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 en methods too.

-- 
Remco Gerlich,  scarblac at pino.selwerd.nl
-rwxr-xr-x  1 root  5.89824e37 Oct 22  1990 /usr/bin/emacs [STR]



More information about the Python-list mailing list