[Python-ideas] Tweaking closures and lexical scoping to include the function being defined
Ron Adam
ron3200 at gmail.com
Fri Sep 30 03:07:48 CEST 2011
On Thu, 2011-09-29 at 13:01 -0700, Guido van Rossum wrote:
> On Thu, Sep 29, 2011 at 12:03 PM, Eric Snow <ericsnowcurrently at gmail.com> wrote:
> > The alternative is to leave nonlocal as just a simple statement, but
> > change its behavior when the name is not found inside a containing
> > function scope. Currently that is a syntax error.
>
> For a reason. It would be too easy for a typo to produce the wrong
> interpretation.
But this is exactly how it works now! The behavior of nonlocal doesn't
need to be changed. It already behaves that way with closures. :-)
Cheers,
Ron
(PS... Pleas repost if this doesn't show up on the python-ideas. My
emails aren't getting there. My apologies for duplicates.)
Python 3.2rc2+ (py3k:88358, Feb 6 2011, 08:56:00)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Closure as defaults.
>>> def a(x):
... def b(y):
... return x+y
... return b
...
>>> c = a(5)
>>> c(4)
9
>>> c(5)
10
Closures with nonlocal.
>>> def a(x):
... def b(y):
... nonlocal x
... x = x + y
... return x
... return b
...
>>> c = a(3)
>>> c(1)
4
>>> c(2)
6
>>> c(3)
9
Closure won't allow changes to cells without nonlocal.
>>> def a(x):
... def b(y):
... x = x + y
... return x
... return b
...
>>> c = a(3)
>>> c(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in b
UnboundLocalError: local variable 'x' referenced before assignment
>>>
More information about the Python-ideas
mailing list