Message347706
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:27 | steven.daprano | set | recipients:
+ steven.daprano, kolia |
2019-07-11 20:59:27 | steven.daprano | set | messageid: <1562878767.92.0.784794779342.issue37568@roundup.psfhosted.org> |
2019-07-11 20:59:27 | steven.daprano | link | issue37568 messages |
2019-07-11 20:59:27 | steven.daprano | create | |
|