[Python-Dev] more timely detection of unbound locals
Stefan Behnel
stefan_ml at behnel.de
Mon May 9 15:27:09 CEST 2011
Eli Bendersky, 09.05.2011 14:56:
> 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
>
> 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.
Well, basically any compiler these days can detect that a variable is being
used before assignment, or at least that this is possibly the case,
depending on prior branching.
ISTM that your suggestion is to let x refer to the outer x up to the
assignment and to the inner x from that point on. IMHO, that's much worse
than the current behaviour and potentially impractical due to conditional
assignments.
However, it's also a semantic change to reject code with unbound locals at
compile time, as the specific code in question may actually be unreachable
at runtime. This makes me think that it would be best to discuss this on
the python-ideas list first.
If nothing else, I'd like to see a discussion on this behaviour being an
implementation detail of CPython or a feature of the Python language.
Stefan
More information about the Python-Dev
mailing list