Encapsulation
Encapsulation in Python
"An object should hide its internal representation and expose only its interface. Whoever gets the object gets the ability to use it, not to poke around inside." — Bertrand Meyer, Object-Oriented Software Construction (1988), the Information Hiding principle (paraphrased)
Core idea
The object owns its state and decides how that state can change. The outside world interacts with the object only through its public interface. That is what keeps the invariants (consistency rules) safe.
Why it matters
| Without encapsulation | With encapsulation |
|---|---|
Someone writes account.balance = -1000 and bypasses validation |
account.withdraw(1000) checks the invariant |
| Internal representation leaks out, you cannot change it | You can rewrite the internals as long as the public interface stays the same |
| The error shows up far from the cause | The error is raised at the point of change |
| The object becomes "a struct plus a pile of functions" | The object becomes a self-directed actor |
Levels of "privacy" in Python
Python does not have real private (unlike Java or C#). Instead it has conventions and light technical barriers.
1. Public: name
class Point:
def __init__(self, x, y):
self.x = x # public field
self.y = y
Anyone can read and write point.x. This is part of the class contract. Renaming it later is a breaking change.
2. "Internal" by convention: _name
class Account:
def __init__(self):
self._balance = 0 # convention: "do not touch from outside"
One underscore is a signal to another developer: "this is an implementation detail, I do not guarantee compatibility." Python does not block anything. You can physically read or set account._balance, but the reviewer will tell you not to.
💡 PEP 8: a single underscore is the standard Python convention for "non-public". It is enough in 95% of cases.
3. Name mangling: __name (two leading underscores, no trailing ones)
class Account:
def __init__(self):
self.__balance = 0 # the name will be "mangled"
acc = Account()
acc.__balance # ❌ AttributeError
acc._Account__balance # ✅ works — Python "renamed" the attribute
This is not for privacy, it is for avoiding name clashes in inheritance:
class A:
def __init__(self):
self.__x = 1 # becomes _A__x
class B(A):
def __init__(self):
super().__init__()
self.__x = 2 # becomes _B__x — does NOT overwrite A.__x
Without __, the subclass would accidentally overwrite the parent's variable. With __, the names are different.
Rule: use __name only when you actually expect a clash in subclasses. In 99% of cases _name is enough.
4. "Magic" dunder methods: __name__
Not "private", just a special name reserved by Python for protocols: __init__, __str__, __eq__, and so on. Underscores on both sides mean Python owns this name.
@property — the main tool for encapsulation in Python
In Java or C# you would write getBalance() / setBalance(). In Python you use @property. The advantage: the interface looks like a plain field, but there is logic behind it.
Basic example
class Temperature:
def __init__(self, celsius: float = 0.0):
self._celsius = celsius
@property
def celsius(self) -> float:
return self._celsius
@celsius.setter
def celsius(self, value: float) -> None:
if value < -273.15:
raise ValueError(f"below absolute zero: {value}")
self._celsius = value
@property
def fahrenheit(self) -> float: # computed property
return self._celsius * 9 / 5 + 32
Usage:
t = Temperature(25)
print(t.celsius) # 25
print(t.fahrenheit) # 77.0 — computed on the fly
t.celsius = -300 # ❌ ValueError: below absolute zero
What matters here
- It looks like a field from outside, but reads and writes go through a method. The invariant (
>= -273.15) is guaranteed to hold. fahrenheitis a computed property: a derived value that is not stored, it is computed. Changingcelsiusautomatically reflects infahrenheit. A whole class of sync bugs disappears.- You can start with a plain field and later add validation through
@property. The callers do not change. That is the flexibility encapsulation gives you.
Read-only property
If you do not define a setter, the attribute becomes read-only:
class Circle:
def __init__(self, radius: float):
self._radius = radius
@property
def area(self) -> float:
return 3.14159 * self._radius ** 2
c = Circle(5)
c.area # 78.54
c.area = 100 # ❌ AttributeError: can't set attribute
@dataclass — when a class is "a struct with validation"
Python 3.7+ has a decorator that auto-generates __init__, __repr__, __eq__, and friends. For "data carrier" classes it is a must-have.
Without @dataclass
class Point:
def __init__(self, x: float, y: float):
self.x = x
self.y = y
def __repr__(self):
return f"Point(x={self.x}, y={self.y})"
def __eq__(self, other):
if not isinstance(other, Point):
return NotImplemented
return self.x == other.x and self.y == other.y
def __hash__(self):
return hash((self.x, self.y))
With @dataclass — the same in four lines
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: float
y: float
Flags worth knowing:
frozen=True— the object is immutable, fields cannot be changed after creation. Generates__hash__automatically. This is immutability, not encapsulation — a frozen dataclass with public fields hides nothing, it just freezes the state.slots=True(Python 3.10+) — fixes the set of attributes, saves memory, blocks adding new fields dynamically.kw_only=True— positional arguments are forbidden, name them. Removes the "pile of unnamed floats in the constructor" problem.
__post_init__ for validation
@dataclass(frozen=True)
class Money:
amount: float
currency: str
def __post_init__(self):
if self.amount < 0:
raise ValueError(f"negative amount: {self.amount}")
if len(self.currency) != 3:
raise ValueError(f"currency must be ISO 4217 (3 letters): {self.currency!r}")
This is fail-fast inside the constructor. The object is created valid, or it is not created at all.
Protecting mutable state: defensive copies
The sneakiest leak of internal state is returning a reference to a mutable collection.
❌ Leak
class ShoppingCart:
def __init__(self):
self._items = []
def get_items(self):
return self._items # returns the INTERNAL list
cart = ShoppingCart()
items = cart.get_items()
items.append("evil_item") # modified the cart's internal state, bypassing everything
✅ Defended
class ShoppingCart:
def __init__(self):
self._items: list[str] = []
def add(self, item: str) -> None:
if not item:
raise ValueError("item cannot be empty")
self._items.append(item)
@property
def items(self) -> tuple[str, ...]:
return tuple(self._items) # immutable copy
Options:
- Return
tuple(self._items)— an immutable copy. - Return
self._items.copy()— a new mutable copy (changes to it do not affect the original). - Return
MappingProxyType(self._dict)— a read-only view of a dict.
Rule: never return a reference to an internal mutable container.
Anti-patterns
1. Getter / setter on everything
class Person:
def __init__(self, name, age):
self._name = name
self._age = age
def get_name(self): return self._name
def set_name(self, v): self._name = v
def get_age(self): return self._age
def set_age(self, v): self._age = v
If you have no invariants, this is just Person(name, age) without setters. It is not "good OOP", it is boilerplate. Add @property only when there is logic (validation, computation, notification).
@dataclass
class Person:
name: str
age: int
2. "Encapsulation" equals _ in front of everything
class Foo:
def __init__(self):
self._x = 0
self._y = 0
self._z = 0
# and they are all read and written directly
If foo._x = 10 is still allowed, this is just decorated public. Either make x public, or protect the invariant with a property.
3. Exposing mutable state
class Config:
def __init__(self):
self.settings = {"theme": "dark"} # public mutable dict
Anyone can do config.settings.clear(). The fix: MappingProxyType, or return a copy through @property.
4. Property with side effects
@property
def total(self):
self._save_to_db() # ❌ reading an attribute writes to the DB?!
return self._total
A property should read like a field, no side effects. If there is a side effect, it is a method, not a property.
When encapsulation is not needed
- Pure data classes without invariants (
Point,Money, DTOs) — public fields plusfrozen=Trueis enough. - Internal utility structures inside one module — no need to hide everything.
- Prototypes and scripts — do not bury behind property something used once.
Principle: encapsulation has a cost (boilerplate). Pay it only where there is an invariant to protect.
Rules of thumb
- Single underscore for "non-public" is the standard.
__only for clash avoidance in subclasses. @propertyinstead of getter/setter. Pythonic.- Computed property instead of "store plus keep in sync" removes a class of bugs.
@dataclass(frozen=True)for DTOs and value objects.__post_init__for validation in a dataclass.- Never return a reference to internal mutable state. Return a copy or an immutable view.
- Do not write getters and setters "just because". Only when there is an invariant or a computation.
One-line summary
The object owns its state. The outside world talks to it through the interface, it does not poke around inside.