Re: lambda construction

Tim Peters (tim@ksr.com)
Wed, 15 Jun 94 00:30:05 -0400

> [bill j]
> ...
> The problem is to take a function 'ofunc' which accepts some unknown
> number of arguments, and wrap it in another function 'wfunc', which
> takes the same number of arguments, but does something to them, then
> calls 'ofunc' on them. I'd like to be able to say something like:
>
> def wrap (ofunc):
> return lambda *args: (process_args(args), apply (ofunc, args))[1]

Yeech! No wonder Guido regrets implementing lambda <wink>.

> The problem is that once I've returned, "ofunc" isn't bound.
[and notes that abusing the default-argument mechanism to bring ofunc
into the lambda's scope can't be done at the same time as using the
"*" vrbl-number-of-arguments mechanism]

class _Wrapper:
def __init__(self, ofunc):
self.func = ofunc

def call(self, *args):
process_args(args)
return apply(self.func, args)

def wrap(ofunc):
return _Wrapper(ofunc).call

does it (i.e., handles an arbitrary # of args, & raises an arg-count-
mismatch TypeError in the same contexts the original function would have
raised it).

BTW, since a variable number of args comes in as a tuple, & tuples are
immutable, you may really want

def call(self, *args):
return apply(self.func, process_args(args))

instead. If "process_args(args)" was shorthand for "I don't really want
a function here -- I intended to fiddle the arguments inline by hand",
then life may be tougher ... although at that point it's doubtful an
obscure lambda one-liner would have been attractive anyway.

sufficient-unto-the-day-are-the-lambdas-thereof-ly y'rs - tim

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