What does Python fix?

Alex Martelli aleax at aleax.it
Fri Jan 25 06:05:00 EST 2002


"David Eppstein" <eppstein at ics.uci.edu> wrote in message
news:eppstein-CF37BE.18490024012002 at news.service.uci.edu...
> In article <mailman.1011922844.21491.python-list at python.org>,
>  "Tim Peters" <tim.one at home.com> wrote:
>
> > This is what Smalltalk was striving for, but it failed to achieve a key
> > insight:  nameless code blocks are easier to reuse if they're named
<wink>.
>
> But (unlike the unnamed lambda-forms) named code blocks are unable to
> access the local variables of some other code block.

Not in Python -- a 'named code block' (the body of a local def statement)
and a lambda form have just the same access (or lack thereof) to local
variables of code blocks they're nested in.

I.e., in Python 2.1 (without from __future__) and older neither the
lambda nor the nested def can access those local variables, although
in 2.1 you get a warning about it:

>>> def foo(x):
...   def bar(): return x
...   return bar
...
<stdin>:1: SyntaxWarning: local name 'x' in 'foo' shadows use of 'x' as
global i
n nested scope 'bar'
>>> foo(23)()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in bar
NameError: global name 'x' is not defined
>>> def foo(x):
...   return lambda: x
...
<stdin>:1: SyntaxWarning: local name 'x' in 'foo' shadows use of 'x' as
global i
n nested scope 'lambda'
>>> foo(23)()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in <lambda>
NameError: global name 'x' is not defined
>>>

In Python 2.2, both of these work fine:

>>> def foo(x):
...   def bar(): return x
...   return bar
...
>>> foo(23)()
23
>>> def foo(x):
...   return lambda: x
...
>>> foo(23)()
23
>>>

No difference from this POV between the lambda and the nested def,
in any version of Python.


Alex






More information about the Python-list mailing list