Frej Connolly
Frej Connolly

Reputation: 1434

Should Python's property() be used as a decorator or saved to a variable?

Which is the preferred way to use the Python built-in function property()? As a decorator or saved to a variable?

Here's an example saving property() to a variable color.

class Train(object):
    def __init__(self, color='black'):
        self._color = color

    def get_color(self):
        return self._color

    def set_color(self, color):
        self._color = color

    def del_color(self):
        del self._color
    color = property(get_color, set_color, del_color)

Here's the same example but using decorators instead.

class Train(object):
    def __init__(self, color='black'):
        self._color = color

    @property
    def color(self):
        return self._color

    @color.setter
    def color(self, color):
        self._color = color

    @color.deleter
    def color(self):
        del self._color

I've found that some like using the decorator syntax for read-only properties. For example.

class Train(object):
    def __init__(self, color='black'):
        self._color = color

    @property
    def color(self):
        return self._color

But the same functionality can also be achieved when saving to a variable.

class Train(object):
    def __init__(self, color='black'):
        self._color = color

    def get_color(self):
        return self._color
    color = property(get_color)

Two ways for the same functionality makes me confused since PEP20 declares

There should be one-- and preferably only one --obvious way to do it.

Upvotes: 1

Views: 271

Answers (1)

tom
tom

Reputation: 19153

Functionally, the two ways of doing this are equivalent. The decorator syntax is just syntactic sugar.

@some_decorator
def some_func():
    ...

...is equivalent to...

def some_func():
    ....
some_func = some_decorator(some_func)

The decorator syntax makes your code more cleaner (the non-decorator syntax means you have to type "some_func" three times!) and your intent more obvious, so I'd say definitely use the decorator syntax.

Upvotes: 3

Related Questions