[Python-Dev] Improve error message "UnboundLocalError: local variable referenced before assignment"

Steven D'Aprano steve at pearwood.info
Wed Oct 31 23:15:57 CET 2012


On 01/11/12 06:57, anatoly techtonik wrote:

[...]
> UnboundLocalError: local variable 'FONT_NAMES' referenced before assignment
>
>
> As you may see there is inconsistency between handling of line 6 -
> "if len(DEBUG):" and line 8 - "if len(FONT_NAMES):". This is very magical
> and hard to troubleshoot.

I wouldn't call it an inconsistency, because the rules for deciding whether
something is treated as local or global is consistently applied to all
functions and variables. I would use the word "difference" instead -- there
is a difference between line 6 and line 8 because there is a difference
between DEBUG (global) and FONT_NAMES (local).

As to whether this is "magical" behaviour, I suppose in some sense it is,
but if so, it is more like a light sprinkling of pixie dust rather than
full-blown dark voodoo magic.


> 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. Or raise
an issue on the bug tracker.



-- 
Steven


More information about the Python-Dev mailing list