local variable referenced before assignment

Pete Bartonly none at try.invalid
Thu Oct 25 17:56:11 CEST 2007


A.T.Hofkamp wrote:
> On 2007-10-25, Pete Bartonly <none at try.invalid> wrote:
>> Quick question, probably quite a simple matter. Take the follow start of 
>> a method:
>>
>>
>> def review(filesNeedingReview):
>>
>>      for item in filesNeedingReview:
>>          (tightestOwner, logMsg) = item
>>
>>          if (logMsg != None):
>>              for logInfo in logMsg.changed_paths:
>>
>>
>> This generates the error:
>>
>>    UnboundLocalError: local variable 'logMsg' referenced before assignment
> 
> This should work, are you sure you didn't make a typo in one of the names?

Nope, the above is verbatim. This is why I'm so confused. It should 
work! I'm editing in emacs, and the indents are tab chars. I've 
re-indented the indents using 'tab' key - same result.

The entire error output is this:

Traceback (most recent call last):
   File "checkCode.py", line 602, in ?
     analyseFiles(tempDir)
   File "checkCode.py", line 448, in analyseFiles
     analyseFilesInARepos(startDir, f)
   File "checkCode.py", line 590, in analyseFilesInARepos
     makeReport(projName, filesNeedingReview, filesFailedReview)
   File "checkCode.py", line 422, in makeReport
     for logInfo in logMsg.changed_paths:
UnboundLocalError: local variable 'logMsg' referenced before assignment

I'm rather stuck at what to try next!

thanks.
Pete







> 
> Another way to make this fail would be when the if-condition is outside
> the loop (is the indentation correct in your code?).
> 
> A short demontration:
>>>> def r(fnr):
> ...   for item in fnr:
> ...     w,m = item
> ...     if m == 2:
> ...       print w
> ...
>>>> fnr = [(1,2), (3,4)]
>>>> r(fnr)
> 1
> 
> With respect to compactness and style, you can move your multi-assignment
> statement in the for loop, as in
> 
> for tightestOwner, logMsg in filesNeedingReview:
> 
> Also, brackets around conditions (in the if) are not needed, and comparing
> against None is usually done with 'is' or 'is not' instead of '==' or '!='.
> The result is then
> 
> if logMsg is not None:
> 
> 
>> I thought I'd assigned it in the "(tightestOwner, logMsg) = item" line - 
>> so in the python interpreter complaining about the fact this assignment 
>> might not go well?
> 
> No, you'd get an error at that point in that case.
> 
> 
> Sincerely,
> Albert



More information about the Python-list mailing list