Re: Use of global

Guido.van.Rossum@cwi.nl
Sat, 01 Apr 1995 01:36:55 +0200

> Why does this generate a NameError?
>
> >>> global gvar
> >>> def f():
> ... gvar = 'xxx'
> ...
> >>> def main():
> ... print gvar
> ...
> >>> main()
> Traceback (innermost last):
> File "<stdin>", line 1, in ?
> File "<stdin>", line 2, in main
> NameError: evar

You must use the "global" statement *inside* each function that
*assigns* a value to the variable. In your case:

def f():
global gvar
gvar = 'xxx'

def main():
print gvar

main()

--Guido van Rossum, CWI, Amsterdam <mailto:Guido.van.Rossum@cwi.nl>
<http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>