On Wed, May 17, 2017 at 11:08 PM, Boris Borcic email@example.com wrote:
Chris Angelico wrote:
# Python def outer(): x = 0 def inner(): nonlocal x x += 2
Is it better to say "nonlocal" on everything you use than to say "self.x" on each use?
I've not used Python closures since nonlocal came about, but AFAIK you only need to use nonlocal if there's an assignment to the variable in the scope. Maybe an augmented assignment creates the same constraint but logically it shouldn't.
Augmented assignment is still assignment. The rules for the nonlocal keyword are the same as for the global keyword, so you can tinker with that if you want a comparison.
Technically my statement wasn't quite true ("on everything" ignores the fact that *reading* a closed-over variable doesn't require any declaration), but omitting the nonlocal declaration would leave you open to incredibly sneaky bugs where moving code from one method to another changes its semantics. So you'd probably end up wanting some sort of class-level declaration that says "please make these nonlocal in all enclosed scopes" (which you could do with macropy, I'm sure), to avoid the risk of missing one. And at that point, you're really asking for a C++ style of thing where your variables get declared, and someone's going to ask you why you're writing this in Python :)