what is lambda used for in real code?

Alex Martelli aleaxit at yahoo.com
Fri Dec 31 02:38:24 EST 2004


Steven Bethard <steven.bethard at gmail.com> wrote:

> (2) lambda a: a.lower()
> My first thought here was to use str.lower instead of the lambda, but of
> course that doesn't work if 'a' is a unicode object:

Right, but string.lower works (after an 'import string').  More
generally, maybe it would be nice to have a way to say "call a method on
x" without x's type being checked, just like attrgetter says "fetch an
attribute on x" -- say s/thing like:

def methodcaller(method_name, *a, **k):
    def callit(x):
        return getattr(x, method_name)(*a, **k)
    callit.__name__ = method_name
    return callit


> (3)  self.plural = lambda n: int(n != 1)
> Note that this is *almost* writable with def syntax.  If only we could do:
>      def self.plural(n):
>          int(n != 1)

Not sure about the context, but maybe we could use, at class-level:
    @staticmethod
    def plural(n):
        return int(n != 1)


> (4) objs.sort(lambda a, b: cmp(getattr(a, 'lineno', 0),
>                                 getattr(b, 'lineno', 0)))
> My first intuition here was to try something like:
>      objs.sort(key=operator.attrgetter('lineno'))
> but this doesn't work because then we don't get the default value of 0
> if the attribute doesn't exist.  I wonder if operator.attrgetter should
> take an optional "default" parameter like getattr does:

The optional default parameter sounds like a good idea to me.


Even though a good number of lambda uses may be avoidable or removable
by such means, I think there's just slightly too much variety -- in some
cases, a def with a name will have to be best (just as it would even
today if, say, an if/else had to be part of the logic -- simulations of
ternary operators being rarely clearest and most solid).


Alex



More information about the Python-list mailing list