[Python-ideas] nonlocal functions

Bruce Leban bruce at leapyear.org
Thu Oct 22 17:57:15 CEST 2009

On Wed, Oct 21, 2009 at 8:47 AM, Masklinn <masklinn at masklinn.net> wrote:
>... I do think `let` fits the Zen better than
> nothing/`global`/`nonlocal`:
> instead of 3 different forms depending on the exact

First, I hardly think introducing a 'let' keyword as you suggest is
pythonic. It's adding new syntax of a different flavor than the current
syntax and breaking existing code.

Why is it a different flavor? Because apparently you didn't notice that
global and nonlocal are statements in their own right, not modifications of
an assignment statement. So you're suggesting:

    global one
    nonlocal two
    let three = value

It's also a different flavor because global says what it means, nonlocal
says what it means and let says nothing about what it means.

And breaking existing code without a damn good reason? I don't see that
It seems a bit inconsistent to me that global/nonlocal act differently with
respect to reading and writing variables. That's a far worse problem than
you're trying to solve. (See below.) But changing that would break a lot of
code. So we live with it.

My proposal (whether or not it's a good idea) wouldn't break any existing
code. The new syntax proposed is currently invalid so can't appear in
existing programs. It would add a new local statement that is only
recognized in contexts that don't exist right now (and therefore can't break
existing programs).

The truth is that global and nonlocal add cognitive load to the person
reading your code because they can't just read the one line to see what it's
doing. This increases the burden on the developer to be clear in what
they're writing. If my proposal allows us to decrease cognitive load on the
reader, then it might be worth considering.

As an aside, if instead of using the global/nonlocal statement we wrote:

   global.one = nonlocal.two

Then the reader knows exactly what's global at the time it gets read. But I
don't see that happening anytime soon given the preference for TOOWTDI and
taking out the global/nonlocal statements would break too much code. And :-)
we'd have to figure out what this statement means:

    foo = bar + global.bar + nonlocal.bar

--- Bruce

>>> def f():
 def g():
i = 5

>>> f()

>>> def f2():
def g():
i = 5

>>> f2()
Traceback (most recent call last):
  File "<pyshell#35>", line 1, in <module>
  File "<pyshell#34>", line 5, in f2
NameError: global name 'i' is not defined

>>> def f3():
i = None
def g():
nonlocal i
 i = 5

>>> f3()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20091022/b5dd01f6/attachment.html>

More information about the Python-ideas mailing list