Unbound Local error? How?

Steve Holden steve at holdenweb.com
Tue Jun 27 12:30:28 EDT 2006


Hari Sekhon wrote:
> Bruno Desthuilliers wrote:
> 
>>Hari Sekhon wrote:
>>  
>>
>>>I've got some code as follows:
>>>
>>>import re
>>>re_regexname = re.compile('abc')
>>>
>>>.....
>>>..... various function defs
>>>.....
>>>
>>>def func1():
>>>   ...
>>>   func2()
>>>   ...
>>>
>>>def func2():
>>>   if re_regexname.match('abc'):
>>>      <do something>
>>>
>>>if __name__ == '__main__':
>>>   func1()
>>>
>>>
>>>but this returns the Traceback:
>>>
>>>UnboundLocalError: local variable 're_regexname' referenced before
>>>assignment
>>>    
>>>
>>
>>this is *not* the traceback. This is only the error message. The
>>traceback contains all needed informations (or at least all possible
>>information at this point) to know what happened. But you did not post
>>the traceback. Nor did you post the minimal runnable code snippet
>>producing this error.
>>
>>  
>>
>>>How?
>>>    
>>>
>>
>>How could we know ?
>>
>>
>>  
>>
> 
> sorry, I know it looks like I was being stingy but the traceback was not 
> that helpful, not without seeing more a huge amount more of the code. I 
> was trying to abbreviate.
> 
> Traceback (most recent call last):
>   File "./backup.py", line 649, in ?
>     backup(machine,share)
>   File "./backup.py", line 364, in backup
>     backupdir(source,destination)
>   File "./backup.py", line 398, in backupdir
>     (dirlist,filelist) = getdirlisting( source )
>   File "./backup.py", line 445, in getdirlisting
>     if re_skip_dirs.match(x):
> UnboundLocalError: local variable 're_skip_dirs' referenced before 
> assignment
> 
> This doesn't really show that much, I figured the problem was the following:
> 
> def getdirlisting():
>      re_skip_dirs = re_skip_top_dirs   #Here's the culprit
> 
> where both these regex compiled objects were declared at the top level, 
> it seems that the assignment is trying to use the local variable 
> re_skip_top_dirs which doesn't exist, that's why I'm getting a 
> traceback, commenting out this line it runs fine.
> 
> -h
> 
> 
The error is simply that you are making an assignment *somewhere* inside 
your function body, so the compiler is treating the variable as local, 
masking the module-level global name. Consequently when you try to read 
its value you are told that the local variable has not yet been bound to 
a value.

A "global" statement inside the function body will fix the problem. You 
could also add a keyword argument (never used except to set a default 
for it in the "def" statement).

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Love me, love my blog  http://holdenweb.blogspot.com
Recent Ramblings     http://del.icio.us/steve.holden




More information about the Python-list mailing list