[Python-Dev] nonlocal x = value

Stefan Behnel stefan_ml at behnel.de
Sat Dec 25 11:59:36 CET 2010

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.

But still, this is just a special case. If the variable is changed more 
than once, you'd end up with one assignment with nonlocal and one without. 
This just adds to the growing list of code inconsistencies presented in 
this thread.

> As for global x = value being disallowed, I have been annoyed at times with
> that, so that sounds like a good argument to change both.
> Requiring the parentheses for tuple creation sounds like a good compromise
> for resolving the ambiguity, consistent with similar limitations of the
> generator expression syntax.

Why introduce such a pitfall for coders here? "Require" doesn't mean the 
parser can enforce it. If it's not there, it just means something else, so 
it's up to the coder to get it right. The exact same kind of situation that 
was fixed for the except syntax in Python 3.


More information about the Python-Dev mailing list