This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author steven.daprano
Recipients kolia, steven.daprano
Date 2019-07-11.20:59:27
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1562878767.92.0.784794779342.issue37568@roundup.psfhosted.org>
In-reply-to
Content
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?
History
Date User Action Args
2019-07-11 20:59:27steven.dapranosetrecipients: + steven.daprano, kolia
2019-07-11 20:59:27steven.dapranosetmessageid: <1562878767.92.0.784794779342.issue37568@roundup.psfhosted.org>
2019-07-11 20:59:27steven.dapranolinkissue37568 messages
2019-07-11 20:59:27steven.dapranocreate