What is UnboundLocalError for?

Tim Peters tim_one at email.msn.com
Wed Jul 12 19:04:49 EDT 2000


[Alex]
> (Python 2.0 question.)
>
> I was wondering what situations the UnboundLocalError exception is
> intended to be thrown in.

When a local name is referenced but has not been bound to a value.  In other
words, it's an unbound local error <wink>.  Note that UnboundLocalError is a
subclass of NameError, because it's a more specific form of NameError, so
old code expecting to catch NameError exceptions will still catch
UnboundLocalError exceptions.  In 1.5.2 and before, NameError was thrown
regardless of whether the offending name was local or global.  So
UnboundLocalError gives more information.

> I encountered it when I made a mistake like this:
>
> >>> f()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "<stdin>", line 1, in f
> UnboundLocalError: l
> >>>

So your function f (which you have not shown us) refers to a local name "l"
which you didn't give a value before referencing it.  It's impossible for us
to guess what you put in the body of f; here's one possibility:

>>> def f():
...     l = l + 1   # local "l" referenced on the right before definition
...     return l
...
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in f
UnboundLocalError: l
>>>

> This was much more confusing to me than a simple NameError, which is
> what python 1.5 throws for the same mistake.  Perhaps I'm biased,
> though.

Sounds more like it's simply not exactly what you were used to before
<wink>.






More information about the Python-list mailing list