what is lambda used for in real code?
Steven Bethard
steven.bethard at gmail.com
Fri Dec 31 11:22:13 EST 2004
Alex Martelli wrote:
> 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
Yeah, that's exactly the kind of thing I was looking for. Very nice!
>>(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)
The context was within the _parse method of GNUTranslations. Basically,
this method uses the fp passed in and a bunch of conditionals to
determine how to define the plural method. So I don't think it can be
done at the class level. Also, doesn't the assignment:
self.plural = lambda n: int(n != 1)
make this more like (at class level):
def plural(self, n):
return int(n != 1)
that is, isn't this an instance method, not a staticmethod?
py> class C(object):
... def __init__(self):
... self.plural = lambda n: int(n != 1)
...
py> c = C()
py> c.__class__.plural(1)
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
AttributeError: type object 'C' has no attribute 'plural'
py> c.plural(1)
0
> 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
Yup, that was my feeling. I was only able to rewrite as an expression
about 50% of the lambdas that I found. However, I (personally) don't
have much of a problem with adding a def in most of the other cases.
The only ones that make me a little nervous are examples like:
inspect.py: def formatargspec(args, varargs=None, varkw=None,
...
formatvarargs=lambda name: '*' + name,
formatvarkw=lambda name: '**' + name,
formatvalue=lambda value: '=' + repr(value),
where the lambdas are declaring functions as keyword arguments in a def.
I'm not sure how much I like adding to the module multiple function
defs that are really intended to be accessed only within formatargspec.
Still, were lambda to go away in Python 3000, it certainly wouldn't be
the end of the world. ;-)
Steve
More information about the Python-list
mailing list