[Python-Dev] more timely detection of unbound locals

Steven D'Aprano steve at pearwood.info
Mon May 9 16:45:09 CEST 2011


Eli Bendersky wrote:
> Hi all,
> 
> It's a known Python gotcha (*) that the following code:
> 
> x = 5
> def foo():
>     print(x)
>     x = 1
>     print(x)
> foo()
> 
> Will throw:
> 
>        UnboundLocalError: local variable 'x' referenced before assignment

I think part of the problem is that UnboundLocalError is a jargon name, 
while it's predecessor NameError (used up to Python 1.5) is far more 
intuitively obvious.


> On the usage of 'x' in the *first* print. Recently, while reading the
> zillionth question on StackOverflow on some variation of this case, I
> started thinking whether this behavior is desired or just an implementation
> artifact.
[...]
> Would it not be worth to make Python's behavior more expected in this case,
> at the cost of some implementation complexity? What are the cons to making
> such a change? At least judging by the amount of people getting confused by
> it, maybe it's in line with the zen of Python to behave more explicitly
> here.

I think you are making an unwarranted assumption about what is "more 
expected". I presume you are thinking that the expected behaviour is 
that foo() should:

print global x (5)
assign 1 to local x
print local x (1)

If we implemented this change, there would be no more questions about 
UnboundLocalError, but instead there would be lots of questions like 
"why is it that globals revert to their old value after I change them in 
a function?".




-- 
Steven



More information about the Python-Dev mailing list