UnboundLocalError: local variable '_[1]' referenced before assignment
Gabriel Rossetti
gabriel.rossetti at arimaz.com
Wed Dec 9 09:32:52 EST 2009
Dave Angel wrote:
> 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
>
Hello Dave,
ok, you' re right about not showing enough:
params = [ self.__formatData(paramProcFunc, query, p) for p in params ]
where :
paramProcFunc = "percent2Volume"
def __formatData(self, func, query, data):
return getattr(self._unitDataAbs, func)(self._unitCmdAbs, query,
data)
def percent2Volume(self, absCmds, query, percent):
return query, int(round(percent / 100.0 * absCmds["volCeil"]))
but I still don't see where the problem is and why it works with the
explicit loop and not the list comp.
Thanks,
Gabriel
More information about the Python-list
mailing list