Re: Use of global

Steven D. Majewski (sdm7g@virginia.edu)
Fri, 31 Mar 1995 18:41:27 -0500 (EST)

On Fri, 31 Mar 1995, Mike Tibbs wrote:

> This is a newbie question, but anyway:
>
> 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
>

I think you need the global declaration to be inside 'f' :

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

The global outside 'f' is declaring it to be of global scope
IN the global scope. Where it needs to be disambiguated is that
the 'gvar' inside of 'f' is global and not local.

This may be a bit confusing if you are expecting the same sort
of syntax and semantics of a C 'extern'

( A global is not required in main(), since 'gvar' is not assigned
a value, there is no local 'gvar' , so it must be global. )

However, even with that change, you still have to call 'f()' before
you call 'main()' , or you will get a name error. Even if you
leave a 'global gvar' in the outer scope, that does not create
and bind the name gvar.

---| Steven D. Majewski (804-982-0831) <sdm7g@Virginia.EDU> |---
---| Computer Systems Engineer University of Virginia |---
---| Department of Molecular Physiology and Biological Physics |---
---| Box 449 Health Science Center Charlottesville,VA 22908 |---