Declare a variable global

Peter Otten __peter__ at web.de
Mon Feb 19 13:03:11 EST 2007


yinglcs at gmail.com wrote:

> On Feb 19, 11:09 am, Jean-Paul Calderone <exar... at divmod.com> wrote:
>> On 19 Feb 2007 09:04:19 -0800, "ying... at gmail.com" <ying... at gmail.com>
>> wrote:
>>
>> >Hi,
>>
>> >I have the following code:
>>
>> >colorIndex = 0;
>>
>> >def test():
>> >     print colorIndex;
>>
>> >This won't work.
>>
>> Are you sure?
>>
>>     exarkun at charm:~$ cat foo.py
>>     colorIndex = 0
>>
>>     def test():
>>         print colorIndex
>>
>>     test()
>>     exarkun at charm:~$ python foo.py
>>     0
>>     exarkun at charm:~$
>>
>> The global keyword lets you rebind a variable from the module scope.  It
>> doesn't have much to do with accessing the current value of a variable.
>>
>> Jean-Paul
> 
> Thanks. Then I don't understand why I get this error in line 98:
> 
>  Traceback (most recent call last):
>   File "./gensvg.py", line 109, in ?
>     outdata, minX, minY, maxX, maxY = getText(data);
>   File "./gensvg.py", line 98, in getText
>     print colorIndex;
> UnboundLocalError: local variable 'colorIndex' referenced before
> assignment

When there is an assignment python assumes that the variable is in the local
scope (unless you explicitly declare it as global):

>>> v = 42
>>> def f():
...     print v
...
>>> f()
42
>>> def g():
...     print v
...     v = "won't get here anyway"
...
>>> g()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in g
UnboundLocalError: local variable 'v' referenced before assignment
>>> def h():
...     global v
...     print v
...     v = "for all the world to see"
...
>>> h()
42
>>> v
'for all the world to see'

Peter



More information about the Python-list mailing list