scope of function parameters
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sun May 29 14:53:06 EDT 2011
On Mon, 30 May 2011 04:38:26 +1000, Chris Angelico wrote:
> On Mon, May 30, 2011 at 4:01 AM, Chris Rebert <clp2 at rebertia.com> wrote:
>> def foo():
>> print bar
>> bar = 42
>>
>> foo()
>>
>> ===>
>> Traceback (most recent call last):
>> File "<stdin>", line 1, in <module>
>> File "<stdin>", line 2, in foo
>> UnboundLocalError: local variable 'bar' referenced before assignment
>
> Wow
>
> I thought it basically functioned top-down. You get a different error on
> the print line if there's a "bar = 42" *after* it. This could make
> debugging quite confusing.
UnboundLocalError is a subclass of NameError, so it will still be caught
by try...except NameError.
If you're crazy enough to be catching NameError :)
Go back to Python1.5, and there was no UnboundLocalError. It was
introduced because people were confused when they got a NameError after
forgetting to declare something global:
>>> def f():
... print a
... a = a + 1
...
>>> a = 42
>>> f()
Traceback (innermost last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in f
NameError: a
While UnboundLocalError is jargon, and not the easiest error message to
comprehend, at least it confuses in a different way :)
--
Steven
More information about the Python-list
mailing list