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

Marilyn Davis marilyn at deliberate.com
Sun Jun 27 23:29:57 EDT 2004


On Sun, 27 Jun 2004, Bob Gailer wrote:

> At 05:54 PM 6/27/2004, Marilyn Davis wrote:
> >I ran across this warning:
> >
> >#!/usr/bin/env python2.3
> >VAR = 'xxx'
> >if __name__ == '__main__':
> >     global VAR
> >     VAR = 'yyy'
> >---
> >OUTPUT:
> >./var.py:0: SyntaxWarning: name 'VAR' is assigned to before global declaration
> >----
> >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'
> >if __name__ == '__main__':
> >     set_var()
> 
> Global is normally used within a function definition to allow it to assign 
> to names defined outside the function (as in your 2nd example). In your 
> first example global is outside any function definition, and therefore not 
> meaningful, as well as giving a SyntaxWarning.

You are so right!  I was thinking that I needed it in any indentation.

But a test showed that I could do

if __name__ == '__main__':
    var = 'YYY'

Great.  It all makes sense now.  Thank you.

Marilyn

> [snip]
> 
> Bob Gailer
> bgailer at alum.rpi.edu
> 303 442 2625 home
> 720 938 2625 cell 
> 
> 

-- 




More information about the Tutor mailing list