UnboundLocalError: local variable '_[1]' referenced before assignment

Dave Angel davea at ieee.org
Wed Dec 9 08:58:23 EST 2009


Gabriel Rossetti wrote:
> <div class="moz-text-flowed" style="font-family: -moz-fixed">Hello 
> everyone,
>
> I get this error on python 2.6.1 on mac os x 10.6 :
>
> UnboundLocalError: local variable '_[1]' referenced before assignment
>
> here's the code that raises this:
>
> params = [ self.__formatData(paramProcFunc, query, p) for p in params ]
>
> what I don't get is that it worked on mac os x 10.5 (python 2.5.x) but 
> it no longer works. I tried the following and it works :
>
> r = []
> for p in params:
>    r.append(self.__formatData(paramProcFunc, query, p))
> params = r
>
> Does anyone understand what is going on here?
>
> Thank you,
> Gabriel
>
> </div>
>
Clearly you're not supplying enough context.  The UnboundLocalError is 
only raised inside a function (or method), and you only show one line of 
that function.

And in the second example, it's even worse, since you imply it's 
top-level code by carefully unindenting everything.

My *guess* is that you have a global variable params, which you're 
looping on.  And then you assign a local variable by the same name.  If 
you have an assignment anywhere in the function, that name is considered 
a local, and if you reference it before you assign it, it'll generate 
this error.

Three possible fixes, depending on why you're doing this.

1) pass the params in to the function as an argument
2) use a different name for the local thing you're building
3) use a global statement to force the compiler to use the global one 
and not create a local.  (probably a bad idea)

DaveA




More information about the Python-list mailing list