Re: lambda construction

Tim Peters (
Wed, 22 Jun 94 02:05:48 -0400

> > > def wrap (ofunc):
> > > return lambda *args: (process_args(args), apply (ofunc, args))[1]

> > [guido]
> > Actually, ofunc is *never* bound inside that lambda! If you were to
> > call it inside wrap it would also fail. Python is not Lisp!

> [ken]
> I take that to mean the following ... should not happen:
> >>> def wrap(ofunc):
> ... return ofunc('hello from wrap... ')
> >>> def enwrapt(argh):
> ... return argh + 'goodbye from enwrapt'
> >>> wrap(enwrapt)
> 'hello from wrap... goodbye from enwrapt'
> >>>
> I suspect i'm being dense. Where am i going astray?

The simplicity of Python's scoping trips up everyone at first glance, but
you already wrote up the answer in your fact sheet <wink>: the search
order is [local, global, builtin], and everything follows from that, +
that "lambda" is syntactic sugar for a one-line def.


def wrap (ofunc):
return lambda *args: (process_args(args), apply (ofunc, args))[1]

is equivalent to

def wrap (ofunc):
def temp(*args): return (process_args(args), apply (ofunc, args))[1]
return temp

ofunc is not in "temp"'s local ns ("args" is the _only_ name in temp's
local ns), so it's not in the lambda's local ns, so "ofunc is *never*
bound inside that lambda!" is correct (assuming "ofunc" isn't in the
global or builtin namespaces).

Guido's "If you were to call it inside wrap it would also fail" was
ambiguous; by "it" he meant the lambda, not ofunc. Calling ofunc inside
wrap works fine (because a function's formal arguments are in the
function's local ns).

nesting-is-for-the-birds?-ly y'rs - tim

Tim Peters
not speaking for Kendall Square Research Corp