problem with global var

Fredrik Lundh fredrik at pythonware.com
Thu Jan 3 10:16:42 EST 2008


Bruno Ferreira wrote:

> When I execute the program _without_ the lines 10 and 11:
> 
> 10     if len(topsquid) > 50:
> 11         topsquid = topsquid[0:50]
> 
> it runs perfectly.
> 
> But if I execute the program _with_ those lines, this exception is thrown:
> 
> bruno at ts:~$ python topsquid.py
> Traceback (most recent call last):
>   File "topsquid.py", line 20, in <module>
>     add_sorted (linefields)
>   File "topsquid.py", line 6, in add_sorted
>     if int(list[4]) > int(topsquid[i][4]):
> UnboundLocalError: local variable 'topsquid' referenced before assignment

Python uses static analysis to determine if a variable is local to a 
function; somewhat simplified, if you assign to the variable inside the 
function, *all* uses of that variable inside the function will be 
considered local.  for the full story, see:

     http://docs.python.org/ref/naming.html

to fix this, you can insert a "global" declaration at the top of the

     def add_sorted (list):
         global topsquid # mark topsquid as global in this function
         ...

in this case, you can also avoid the local assignment by modifying the 
list in place;

     if len(topsquid) > 50:
         topsquid[:] = topsquid[0:50]

or, as a one-liner:

     del topsquid[50:]

</F>




More information about the Python-list mailing list