what is lambda used for in real code?

Alex Martelli aleaxit at yahoo.com
Fri Dec 31 17:48:23 CET 2004


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

> >>(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

Ah, OK -- I see, then you're probably quite right here!

> 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?

Apart from the different possible definitions (which are of course
crucial), I don't see that.  Given the fact that, if you define plural
as an instancemethod, you're not using 'self' anyway, what usage would
break with a staticmethod?  "Doesn't use 'self'" smells more like a
staticmethod to me, even if you always call it on an instance.

> 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

This shows that staticmethod has slightly wider applicability, yes, but
I don't see this as a problem.  IOW, I see no real use cases where it's
important that hasattr(C, 'plural') is false while hasattr(C(),
'plural') is true [I could of course be missing something!].


Alex
  



More information about the Python-list mailing list