global variable, ok for string, bad for int

Peter Hansen peter at engcorp.com
Thu Jan 20 23:39:19 EST 2005


francisl wrote:
> I have a problem when I declare global variable.
> If it is string, dict, array or tuple, everything goes fine, but with 
> int, I get an "used before declaration" error.
> 
> here a sample :
> vardict = {'un':1, 'deux':2}
> 
> def print_value():
>     print vardict['un']
> ######### ok, that works
> 
> --------------------
> #!/bin/python
> varint = 1
> 
> def print_value():
>     print varint
> ######### ok, that failed

Please *always* post tracebacks, the actual traceback cut and
pasted with the mouse from your session, when you are asking
for help with errors like this.  There is nothing called
a "used before declaration" error...  Was what you actually got
an "UnboundLocalError: local variable 'varint' referenced
before assignment", or something else?  Don't retype: cut and paste.

Also, please post only the actual code you are running,
reduced to the simplest form which still reproduces the
problem.  The above code runs perfectly well, even if you
add the missing call to print_value() at the end of the module.

-Peter



More information about the Python-list mailing list