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

Terry Reedy tjreedy at udel.edu
Wed Dec 9 11:55:00 EST 2009


Gabriel Rossetti wrote:
>> Gabriel Rossetti wrote:

>>> 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.

In 3.0, list comps were changed to not 'leak' the iteration variables.
To do this, they are compiled to a function run in a separate namespace.
It appears the new code was backported to 2.6 with an extra fix to 
continue leaking the iteration variable for back compatibility. I 
presume there is or was intended to be a switch to to get 3.x behavior 
for code being ported.

As others have said, the error is from that internal function, and 
should never appear. Hence, you may have found a corner-case bug that 
otherwise passed the current tests.

Suggestions.
1) Run with 3.1 and see if you get the same error. In not, problem is in 
difference between 3.1 and 2.6 listcomp code. Report to tracker.
2) Simplify the code and see if you still get the error. I would try 
removing the '__' from the method name, or using a data attribute 
instead of a method, or a method with no parameters.

Unless someone here otherwise pins the error on you, report on the tracker.

Terry Jan Reedy

> I tried the following and it works :
>>>
>>> r = []
>>> for p in params:
>>>    r.append(self.__formatData(paramProcFunc, query, p))
>>> params = r

In 2.5, list comps were rewritten like this.

>>>
>>> Does anyone understand what is going on here?

> 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