[Tutor] :0: SyntaxWarning: name 'VAR' is assigned to before globaldeclaration

Alan Gauld alan.gauld at blueyonder.co.uk
Mon Jun 28 13:22:24 EDT 2004

> #!/usr/bin/env python2.3
> VAR = 'xxx'
> if __name__ == '__main__':
>     global VAR
>     VAR = 'yyy'

Here there is only one scope, module or global scope. Therefore
there is no need for the global statement because the vVAR will
allways be the same one as defined previously.

> ./var.py:0: SyntaxWarning: name 'VAR' is assigned to before global

And this is true, within the file scope you have already created VAR
it is too late trying to tell Python to look somewhere else. (Even
there is nowhere else it could look in this case!)

> But, a little twiddle quiets the warning, and I have no idea why:
> #!/usr/bin/env python2.3
> VAR = 'xxx'
> def set_var():
>     global VAR
>     VAR = 'yyy'

Thats a huge twiddle. You have now created a function which defines
a new scope or namespace. So the VAR in there will by default be a
local VAR unless you use global, as you have done.

If you did this you'd get the same error as before:

def set_var():
    VAR = 'yyy'
    global VAR

Because that's an equivalent error.

> Can anyone explain what is happening?

Try reading the "What's in a name?" topic in my online tutor
for more info and examples.

Alan G
Author of the Learn to Program web tutor

More information about the Tutor mailing list