[Python-Dev] Improve error message "UnboundLocalError: local variable referenced before assignment"
R. David Murray
rdmurray at bitdance.com
Wed Nov 7 15:20:19 CET 2012
On Wed, 07 Nov 2012 14:57:57 +0100, Ulrich Eckhardt <ulrich.eckhardt at dominolaser.com> wrote:
> Am 31.10.2012 23:15, schrieb Steven D'Aprano:
> > On 01/11/12 06:57, anatoly techtonik wrote:
> > [...]
> >> UnboundLocalError: local variable 'FONT_NAMES' referenced before
> >> assignment
> >> I wonder if this message can be improved with a
> >> pointer to the concept on when global variables become local?
> > If you have a suggestion for an improved message, please tell us.
> I'll take a shot, since I was also bitten by this when trying to learn
> Python. The important point is that some code earlier or later in that
> function does an assignment, so this location should be referenced in
> the error.
> How about:
> "UnboundLocalError: Local variable 'FONT_NAMES' (created on
> line 11) referenced before assignment."
> What I don't really like is the term "created". Maybe "implicitly
> created on line 11"? Or "implied by line 11"? Or how about "Local
> variable FONT_NAMES (implied by line 11) doesn't refer to an object", to
> avoid the multiple interpretations of the term "assignment"?
The problem is that when Python executes the statement that raises the
error it has no idea where the assignment was done. All it knows is that
the variable is local. Keeping track of the location of every assignment
that makes a variable local and writing it in to the .pyc file is a very
non-trivial change to how the Python bytecode compiler works, I think, and
probably not worth the overhead in order to improve this error message.
(And note that raising an error at compile time would change Python's
More information about the Python-Dev