what is lambda used for in real code?

Diez B. Roggisch deetsNOSPAM at web.de
Fri Dec 31 14:57:24 CET 2004


> So, those are my thoughts on how lambdas are "really" used.  If others
> out there have real-life code that uses lambdas in interesting ways,
> feel free to share them here!

I use them in conjunction with metaclasses and properties:

    def _s_item(self, item):
        """ saw::active """
        self.__item = item
        self.set_state()
        self.indexWidget.setText("%i" % item.index)
        created = item.created
        dt = QDateTime(QDate(created.year, created.month, created.day),
                        QTime(created.hour, created.minute,created.second))
        self.createdWidget.setDateTime(dt)
        self.set_text()
        self.set_list_items(self.history, item.history)
        self.set_list_items(self.trainlog, item.train_log)
        self.set_classification_result()

        self.adjust_header_sizes()

    def _g_item(self):
        return self.__item

    # the lambda is needed for late-binding so that metaclass-wrapping will
    # be in effect.
    item = property(_g_item, lambda self, v: self._s_item(v))


The doc string of _s_item contains a token the metaclass is aware of and
creates a wrapper around _s_item. That works nice on methods, but I found
that properties got bound to their functions _before_ the metaclass kicks
in, so the property wasn't called in the wrapped version, resulting in
errors. So I introduced the lambda that makes the method call "lazy". Of
course  I could have introduced a 

def _s_item_unwrapped(self, v):
    self._s_item(v)

and used that in  the property - but as there are lambdas, I use them :)

And the second def here is not more explanatory, as one has to graps the
internal details of python properties to understand why that extra hoop is
introduced in the first place.
-- 
Regards,

Diez B. Roggisch



More information about the Python-list mailing list