[Python-ideas] JavaScript-Style Object Creation in Python (using a constructor function instead of a class to create objects)

Chris Angelico rosuav at gmail.com
Wed May 17 09:20:56 EDT 2017

On Wed, May 17, 2017 at 11:08 PM, Boris Borcic <bborcic at gmail.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 :)


More information about the Python-ideas mailing list