Theoretical question about Lambda

Terry Reedy tjreedy at udel.edu
Sun May 5 01:38:09 EDT 2002


"Bengt Richter" <bokr at oz.net> wrote in message
news:ab1sf9$mt8$0 at 216.39.172.122...
> On Thu, 02 May 2002 21:05:45 GMT, Alex Martelli <aleax at aleax.it>
wrote:
> In the meantime, to clarify the semantics, I wonder whether this
> is the truly desired behavior of lambda:

As I understand Python....

The behavior of lambda is essentially the behavior of an equivalent
def.

>  >>> fa = lambda x:x+k

This is +- equivalent to

def fa(x): return x+k

'x+k' is effectively quoted by either 'def' or 'lambda' and is not
evaluated until the function is called.  At this point, the existence
or not of a binding to k is irrelevant.  I would be surprised and
upset if otherwise.

>  >>> k='b'
>  >>> fb = (lambda y: lambda x:x+y)(k)

Since you here use k in a call rather than a definition, it now must
exist.
This is +- equivalent to

def _(y):
    def __(x): return x+y
    return __
fb = _(k)

Again, 'x+y' is evaluated when fb is called, not when it is defined.

fb('fb->')

Without nested scoping as introduced in 2.1, this raises 'NameError:
y' unless y is globally defined, which it is not in your example.
(Yes, I tested this.)  With nested scoping, the intermediate namespace
(the outer local namespace) with y == k == whatever is bundled with
the returned inner function for use is satisfying the name lookups.
(I do not know whether the inner mechanics of lambdas are exactly the
same here, but I believe the effect is the same.)

> I.e., what is the rationale for not creating a closure when a global
> binding exists at the time of lambda evaluation?

The definition-time processing of function bodies pays no attention to
the contents of enclosing scopes since nothing is evaluated until call
time.  To do otherwise would be a major change.  Would you have the
function definition raise an error if the global binding does not
exists at that time?

I hope I have made something clearer.

Terry J. Reedy






More information about the Python-list mailing list