[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

Re: problem with global var

Fredrik Lundh

1/3/2008 3:17:00 PM

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@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/n...

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>