What is the purpose of a property's @getter decorator?

Can anyone explain the purpose of the @property.getter decorator?

class Foo(object):

    # Create a property (with a getter)
    @property
    def answer(self):
        return 41

    # Change the getter
    @answer.getter
    def answer(self):
        return 42

I suppose that it’s sort of cool that this works, but what is the use case for this capability?

It’s mostly for symmetry with setter and deleter. Typically, you create the getter by decorating the appropriate method with property itself, but you could conceivably define an “empty” property and define its getter explicitly, just as you do with setter and deleter.

For example,

class Foo:
    p = property()

    @p.getter
    def p(self):
        return self._p

    @p.setter
    def p(self, v):
        self._p = v

which is the same as

class Foo:
    def _getter(self):
        return self._p

    def _setter(self, v):
        self._p = v

    p = property(_getter, _setter)
    del _getter, _setter

which is most commonly is written as

class Foo:
    @property
    def p(self):
        return self._p

    @p.setter
    def p(self, v):
        self._p = v

It could also be used if you want to change the getter of an existing property for some reason. Like any other method commonly used as a decorator, you can call it explicitly.

3 Likes