Preferred way of defining properties in Python: property decorator or lambda?

parxier picture parxier · Mar 9, 2010 · Viewed 25.7k times · Source

Which is the preferred way of defining class properties in Python and why? Is it Ok to use both in one class?

@property
def total(self):
    return self.field_1 + self.field_2

or

total = property(lambda self: self.field_1 + self.field_2)

Answer

Toni Ruža picture Toni Ruža · Mar 9, 2010

For read-only properties I use the decorator, else I usually do something like this:

class Bla(object):
    def sneaky():
        def fget(self):
            return self._sneaky
        def fset(self, value):
            self._sneaky = value
        return locals()
    sneaky = property(**sneaky())

update:

Recent versions of python enhanced the decorator approach:

class Bla(object):
    @property
    def elegant(self):
        return self._elegant

    @elegant.setter
    def elegant(self, value):
        self._elegant = value