Steven D'Aprano <steve+pyt...@pearwood.info> added the comment:

The behaviour and error message is correct, and your interpretation is 
incorrect. You are not assigning to a closure variable on line 4; you are 
printing an unbound local variable on line 3, precisely as the error message 
says. That may not match your *intention*, but Python doesn't do what we want 
it to do, only what we tell it to do :-)

Like global variables, nonlocals (closures) are NOT defined by "does this name 
match a name in the surrounding scope?". Rather, *local* variables are defined 
by assignment: any assignment in the body of the function defines a local, 
unless otherwise declared as nonlocal or global.


> Instead, the error should point to line 4 and report an illegal assignment to 
> a read-only closure variable.

That can't happen without a huge and backwards-incompatible change to Python 
semantics. (Possibly in Python 5000?)

The only reason I'm not closing this as "Not a bug" is in case someone would 
like to suggest an improvement to error message. Perhaps:

UnboundLocalError: local variable 'a' referenced before assignment -- did you 
forget a nonlocal or global declaration?

----------
nosy: +steven.daprano

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue37568>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to