How setters/getters work
Have you used getters and setters in Python? The motivation for these decorators is to expose public access while protecting attributes from invalid updates. This is a well-known technique that improves maintainability by drawing a boundary between internal state and external callers.
These work like this:
class User:
def __init__(self):
self._age = 0
@property
def age(self):
return self._age
@age.setter
def age(self, value):
if value < 0:
raise ValueError
self._age = value
print(user.age) # 0
user.age = 10
print(user.age) # 10
However, we can still access the raw value like:
user._age
Even if we use getters/setters to protect a private field, we can still access it. Why?
Python chooses convention over restriction
Python aims to be simple and easy to read and write for solving real problems. The language was created by Guido van Rossum at CWI with an emphasis on readability and ease of use. The goal was to let researchers focus on their work rather than wrestling with a language.
For background, see Guido's bio and the Zen of Python:
- https://en.wikipedia.org/wiki/Guido_van_Rossum
- https://peps.python.org/pep-0020/
To keep Python simple, it avoids heavy restrictions. The implicit, convention-based private/public access style comes from this. So Python assumes:
- You know what you’re doing
- If you break invariants, that’s on you
- The language should not fight the programmer
This idea is often summarized in the Perl mantra:
“We’re all consenting adults here.”
So we should know the private/public conventions in our own systems and control them ourselves. If we misuse them and cause bugs, that's on us.
Should You Use Getters and Setters in Python?
You need to judge this properly on your own.
There's a tradeoff between development speed and maintainability.
If you're a researcher running quick experiments and the code will live only a few months, you might skip getters/setters for speed. If you're a developer building a web system to maintain for years, you should use them for maintainability.
Appendix: deeper discussion on when to use getters/setters:
- https://realpython.com/python-getter-setter/
Conclusion
Should You Use Getters and Setters in Python?
You're an adult; you know what you're doing, so you need to decide on your own.
I'm joking. It depends on your code's lifetime. If you want to maintain your code longer (maybe over years), maintainability matters, so you want to use getters/setters. If its lifetime is short, you can skip them (but you still need to understand the risk).