Re: Lambda binding solved by lateral thinking?

Tim Peters (tim@ksr.com)
Thu, 03 Mar 94 01:17:31 EST

> [guido, suggesting a default-argument mechanism as a way to sneak
> values into a nested def's scope without changing the scope rules]
> ...
> def make_incrementor(incr):
> def incrementor(x, incr=incr):
> return x + incr
> return incrementor

> [steve]
> ...
> Well, not exactly what I was trying for:

I believe that's right -- & not what I was trying for either. But I
think it's _better_ than what I was trying for, because it adds a lot of
power with a little extra syntax, and I suspect the implementation is
both finite & clear (to Guido <grin>).

> If you're saying what I read you as saying, you could also override the
> default in the function call:
>
> >>> f = make_incrementor( 4 )
> >>> f(1)
> 5
> >>> f(1, incr=1)
> 2

I believe he's suggesting (Guido, scream where I'm wrong) _just_ a
default-argument mechanism (more-or-less exactly like C++'s), not a
(more elaborate) keyword-argument mechanism.

So
f(1,incr=1)
would be a syntax error (assignment statement used where expression
expected). But
f(1,1)
would indeed print 2.

Damnable insecurity or admirable flexibility? Viewing the _real_ thrust
as adding default argument values for their own sake, I think the latter
is clearly correct. From the sneak-values-into-a-nested-scope view it's
muddier, but I still tend toward calling it a feature.

> ...
> ( As a fix for the local binding problem, I like it.
> I haven't thought thru the implication of the above yet. )

For the most common simple-lambda applications, I think the most common
usage error (caused either by confusion or optical illusion) will yield
a runtime error by happy (but almost reliable) accident. E.g.,

def search(oblist, attr):
hits = filter( lambda ob,attr=attr: hasattr(ob,attr),
oblist, attr ) # final 'attr' not needed

will gripe because _filter_ is passed the wrong number of arguments. And
the same kind of mistake in "map" will yield a "argument to map must be a
sequence" error. And we already know for sure that forgetting to use the
default-argument syntax will usually yield a NameError.

In fancier contexts I doubt this kind of luck will hold, though.

still-liking-it-a-lot-ly y'rs - tim

Tim Peters tim@ksr.com
not speaking for Kendall Square Research Corp