I sing the praises of lambda, my friend and savior!

Robert Brewer fumanchu at amor.org
Tue Oct 12 02:03:57 EDT 2004


Robert Brewer wrote:
> >All I can say is, "sometimes it's not minimal". Adapters are a great
> >example:
> >
> >xforms = {dejavu.icontains: lambda x, y: x + " Like '%" + y[1:-1] +
> >"%'",
> >          dejavu.icontainedby: icontainedby,
> >          dejavu.istartswith: lambda x, y: x + " Like '" + y[1:-1] +
> >"%'",
> >          dejavu.iendswith: lambda x, y: x + " Like '%" + 
> y[1:-1] + "'",
> >          dejavu.ieq: lambda x, y: x + " = " + y,
> >          dejavu.now: lambda: "Now()",
> >          dejavu.today: lambda: "DateValue(Now())",
> >          dejavu.year: lambda x: "Year(" + x + ")",
> >          }

Jeff Shannon wrote:
> Personally, I'd be likely to solve this particular issue by 
> defining a make_formatter() function:
> 
> def make_formatter(format):
>     def formatter(*args):
>         return format % tuple(args)
>     return formatter
> 
> xforms = {dejavu.icontains: make_formatter("%s Like '%%%s%%'"),
>           dejavu.icontainedby: icontainedby,
>           dejavu.istartswith: make_formatter("%s Like '%s%%'"),
>           dejavu.iendswith: make_formatter("%s Like '%%%s'"),
>           dejavu.ieq: make_formatter("%s = %s"),
>           dejavu.now: make_formatter("Now()"),
>           dejavu.today: make_formatter("DateValue(Now())"),
>           dejavu.year: make_formatter("Year(%s)")
>           }
> 
> # [...]
> xforms[dejavu.icontains](x, y[1:-1])

Yesss..., but now (for an example) you've abstracted the slicing of y
out of the xforms. Notice that the original ieq doesn't slice the tips
off of y like the others do, so now your calling code must "know about"
that difference. So we've simply spread the logic into 3 places
(make_formatter, the original dict, and now the callers) where before it
was "all in one". That makes it more brittle, in this case. Trying to
handle those tiny differences with *more* arguments being passed into
make_formatter will make this an uglier mess quite quickly.

All of which is to say, sometimes lambdas are the most clear, flexible
solution. Those situations are: where parameterization is not expressive
enough, and where full functions are more expressive (and therefore
verbose) than necessary. I agree that that small window between the two
(where lambdas live) can be made arbitrarily small and rare, but it'll
never go away without causing some pain.


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org



More information about the Python-list mailing list