Author steven.daprano
Recipients kolia, steven.daprano
Date 2019-07-11.20:59:27
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <>
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?
Date User Action Args
2019-07-11 20:59:27steven.dapranosetrecipients: + steven.daprano, kolia
2019-07-11 20:59:27steven.dapranosetmessageid: <>
2019-07-11 20:59:27steven.dapranolinkissue37568 messages
2019-07-11 20:59:27steven.dapranocreate