[Python-Dev] more timely detection of unbound locals

R. David Murray rdmurray at bitdance.com
Tue May 10 19:31:04 CEST 2011

On Wed, 11 May 2011 00:59:08 +1000, Nick Coghlan <ncoghlan at gmail.com> wrote:
> On Tue, May 10, 2011 at 11:11 PM, R. David Murray <rdmurray at bitdance.com> w=
> rote:
> > How about:
> >
> > "reference to variable 'y' precedes an assignment that makes it a local
> > variable"
> For comparison, the error messages I was able to elicit from 2.7 were
> as follows:
> # Module level
> NameError: name 'bob' is not defined
> # Function level reference to implicit global
> NameError: global name 'bob' is not defined
> # Early reference to local
> UnboundLocalError: local variable 'bob' referenced before assignment
> # Early reference from closure
> NameError: free variable 'bob' referenced before assignment in enclosing sc=
> ope
> Personally, I would just add "in current scope" to the existing error
> message for the unbound local case (and potentially collapse the
> exception hierarchy a bit by setting UnboundLocalError = NameError).

I don't think adding that phrase would add any clarity, myself.
The mental disconnect comes from the fact that the UnboundLocal error
message is emitted for the reference, but it is not immediately obvious
*why* the variable is considered local.  My rephrasing emphasizes that it
is the assignment statement that led to that classification and therefore
the error.  This disconnect doesn't apply in the global cases.  It applies
less strongly in the free variable case because there is visibly another
scope involved (that is, the triggering assignment isn't in the same
scope as the reference producing the error message).

R. David Murray           http://www.bitdance.com

More information about the Python-Dev mailing list