3

I have been learning about @property decorators that replace getters and setters. A lot of people seems to prefer using @property over getters and setters.

Regardless of which is desirable, are they even needed most of the times? I feel that it is unnecessary or overkill to have @property for all internal variables especially when the variables are as simple as below. Shouldn't simple things be left simple if they work?

class Ex():
    def __init__(self, value):
        self.__x = value

    @property
    def x(self):
        return self.__x
    @x.setter
    def x(self, value):
        self.__x = value

I also don't think @property provides extra security (if at all needed) as people with intention can still access the variable. (._Ex__x)

Why should I use @property (when validation and future changes are not expected) and when should I not use them?

Seung
  • 763
  • 1
  • 7
  • 19
  • Yes, definitely don't use a property here. It's pointless. Properties give you encapsulation without boilerplate. – juanpa.arrivillaga Mar 09 '19 at 21:45
  • If you don't need validation or mutability, use a [**`namedtuple`**](https://docs.python.org/3/library/collections.html#collections.namedtuple). – Peter Wood Mar 09 '19 at 21:47
  • @ThierryLathuille Thank you. I have read it before posting the question, but my question is probably summarised well with "Regardless of which is desirable, are they even needed most of the times?". – Seung Mar 09 '19 at 21:47
  • The linked duplicate is not asking the same question; it asks whether to use properties or getters/setters. This question asks when to use properties vs simple variables. – Jonathon Reinhart Mar 09 '19 at 21:51
  • Note, you probably shouldn't be using double-underscore name-mangling. That's for preventing collisions in subclasses, not for making some "private". Python doesn't have private variables. Double-underscore name mangling really has nothing to do with properties – juanpa.arrivillaga Mar 09 '19 at 21:51

1 Answers1

4

PEP 8, Style Guide for Python Code says:

For simple public data attributes, it is best to expose just the attribute name, without complicated accessor/mutator methods.

A property with no additional logic, as you've shown, provides no advantages over using a simple attribute.

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328