[Python-Dev] nonlocal x = value

Raymond Hettinger raymond.hettinger at gmail.com
Mon Dec 27 10:43:33 CET 2010


On Dec 25, 2010, at 2:59 AM, Stefan Behnel wrote:

> Hrvoje Niksic, 24.12.2010 09:45:
>> On 12/23/2010 10:03 PM, Laurens Van Houtven wrote:
>>> On Thu, Dec 23, 2010 at 9:51 PM, Georg Brandl wrote:
>>>> Yes and no -- there may not be an ambiguity to the parser, but still to
>>>> the human. Except if you disallow the syntax in any case, requiring
>>>> people to write
>>>> 
>>>> nonlocal x = (3, y)
>>>> 
>>>> which is then again inconsistent with ordinary assignment statements.
>>> 
>>> Right -- but (and hence the confusion) I was arguing for not mixing
>>> global/nonlocal with assignment at all, and instead having nonlocal
>>> and global only take one or more names. That would (obviously) remove
>>> any such ambiguity ;-)
>> 
>> I would like to offer the opposing viewpoint: nonlocal x = value is a
>> useful shortcut because nonlocal is used in closure callbacks where
>> brevity matters.
> 
> I doubt that it really matters so much that one line more kills readability. It's still a relatively rare use case after all.
> 
> 
>> The reason nonlocal is introduced is to change the
>> variable, so it makes sense that the two can be done in the same line of
>> code.

FWIW, I'm entirely opposed to doing an assignment in a nonlocal definition.

* It is easily mis-parsed by human (as shown by Georg's examples).
* It looks very much like an initialization of a local variable in many languages,
  but it is not -- the variable has already been initialized in another scope.
* It is not clear how to extend it to multiple variables (which we already allow).
* It is entirely unnecessary.  Just add a real assignment on the following line:
         local x
         x = 3, y
* We've had global declarations for a very long time and never needed
   (or wanted) an assignment for it:
        global x = 3, y
* The purported use case is rare (at best).  Special cases aren't worth breaking the rules.
   And the purported goal (saving one line) isn't much of a payoff.
* The language moratorium is ending but the aversion to non-essential 
   micro-syntax changes persists.
* And, Georg doesn't like it :-)


Raymond


More information about the Python-Dev mailing list