Sub topic 2
What Encapsulation Means in Python
What this chapter assumes
You should be able to define a class with __init__ and methods, and read and write instance attributes. You should also know how to raise and catch exceptions. Decorators are not needed yet. This chapter sets up the idea that the later chapters on naming conventions, name mangling, and @property build on.
Encapsulation is about contracts, not locks
Encapsulation means bundling data with the code that works on it, and exposing a deliberate public interface while keeping the implementation free to change. It gives you two things:
- Protected invariants. An invariant is a condition that must always hold for an object to be valid, such as "a bank balance is never negative".
- Freedom to change internals. Callers depend only on the public interface. You can store data differently later without breaking them.
Many languages enforce this with keywords like private. Python does not. Any code can read or write any attribute of any object. You can see this by inspecting an instance:
class Account:
def __init__(self, balance):
self.balance = balance
acct = Account(100)
print(vars(acct)) # {'balance': 100}
acct.balance = -5000 # nothing stops this
acct.note = "extra" # new attributes can be added too
print(vars(acct)) # {'balance': -5000, 'note': 'extra'}vars(acct) returns the instance's __dict__, the dictionary where the attributes live. Nothing guards it. Python's position, often summarized as "we are all consenting adults here", is that the language trusts programmers to respect a stated boundary instead of enforcing one.
So in Python encapsulation is mostly a matter of design and convention. A few tools make the convention clear and, where you want it, enforce rules at the points where values change.
Why direct access is still the default
The previous chapter showed that plain attributes are the normal starting point. That is not careless. In Python, obj.x can later be turned into a method call without changing a single caller, as the properties chapters will show. Because of this, you do not need to wrap every attribute in get_x() and set_x() methods "just in case", as is common in Java.
Encapsulation therefore becomes a decision you make per attribute:
- Does any rule apply to this value? If not, keep it a plain public attribute.
- Is the value an internal detail that callers should not depend on? Mark it as internal.
- Must the value stay consistent with other data? Control how it changes.
The tools Python gives you
Python offers three mechanisms. Each one gets its own chapter, so this table is only a map.
| Mechanism | What it does | Enforced? |
|---|---|---|
| Single leading underscore (`_balance`) | Tells readers the name is internal | No, convention only |
| Double leading underscore (`__balance`) | Renames the attribute to avoid clashes in subclasses | Partly. It rewrites the name but does not block access |
| `@property` | Runs your code when an attribute is read, assigned, or deleted | Yes, for the rules you write |
The first two communicate intent. Only @property (and, underneath it, descriptors) can run validation. Notice that none of them truly hides data. Real protection comes from code that checks values, and from an interface that makes the safe path the easy path.
The dashed arrow is the part Python leaves open. A caller can reach the internal state, but doing so means they have stepped outside the contract.
A worked example: protecting an invariant
Here is a version of Account that protects its invariant that the balance never goes negative. It marks the stored value as internal and funnels all changes through methods that check the rules:
class Account:
def __init__(self, balance=0):
if balance < 0:
raise ValueError("opening balance cannot be negative")
self._balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("deposit must be positive")
self._balance += amount
def withdraw(self, amount):
if amount <= 0:
raise ValueError("withdrawal must be positive")
if amount > self._balance:
raise ValueError("insufficient funds")
self._balance -= amount
def balance(self):
return self._balance
acct = Account(100)
acct.deposit(50)
acct.withdraw(30)
print(acct.balance()) # 120
try:
acct.withdraw(500)
except ValueError as exc:
print(exc) # insufficient fundsThis design has three parts:
- The leading underscore on
_balancesays "this is the implementation, use the methods". - Every code path that changes the balance checks the rules first.
- The public methods (
deposit,withdraw,balance) describe what the object does, not how it stores data.
The class could now switch to storing cents as an integer, or keep a list of transactions and compute the total. Callers would not notice.
The design is still not locked. acct._balance = -1 works. That is the trade-off: Python makes the contract explicit and lets you break it knowingly, for example in a debugger, in tests, or in a quick script.
In a later chapter you will replace the balance() method with a read-only property, so callers write acct.balance. The encapsulation stays the same and only the call syntax improves.
Edge case: leaking mutable internals
A leading underscore does not protect you if you hand out the internal object itself. This is the most common way encapsulation is accidentally broken:
class Playlist:
def __init__(self):
self._tracks = []
def add(self, title):
if not title:
raise ValueError("title cannot be empty")
self._tracks.append(title)
def tracks(self):
return self._tracks
p = Playlist()
p.add("Song A")
p.tracks().append("") # bypasses add() and its check
print(p.tracks()) # ['Song A', '']tracks() returned the same list object that the class uses internally, so the caller could modify it freely. The fix is to return a copy or an immutable view:
class Playlist:
def __init__(self):
self._tracks = []
def add(self, title):
if not title:
raise ValueError("title cannot be empty")
self._tracks.append(title)
def tracks(self):
return tuple(self._tracks) # a snapshot, not the live list
p = Playlist()
p.add("Song A")
snapshot = p.tracks()
print(snapshot) # ('Song A',)
try:
snapshot.append("x")
except AttributeError:
print("tuples cannot be appended to")
print(p.tracks()) # ('Song A',)The same issue appears in the other direction. If __init__ stores a list that the caller passed in, the caller still holds a reference and can change it later. Copy the argument with list(tracks) if you need to own it.
Common mistakes
- Writing getters and setters for everything.
get_name()andset_name()that only read and write a plain attribute add code and no safety. Start with a plain attribute and add a property if a rule appears. - Treating the underscore as enforcement.
_nameis a request. Tools like linters may warn about outside use, but the interpreter does not stop it. - Believing double underscores make data private. They trigger name mangling, which is aimed at avoiding accidental name clashes in subclasses. The name-mangling chapter shows the renamed attribute is still reachable.
- Validating in only some paths. If
__init__assigns directly but a method validates, invalid objects can still be built. Every way into the object must go through the same rule. The setter chapters cover how to do this once. - Returning live mutable objects. As shown above, return copies or immutable types.
Summary of the working model
- Python encapsulation is a contract that is kept by convention and by validating code, not by access modifiers.
- Plain public attributes are the default, because they can be upgraded to properties later without changing callers.
- Mark implementation details with a leading underscore, and funnel changes through code that enforces invariants.
- Do not leak mutable internals, since that bypasses your checks.
Exercise
A class stores self._items = [] and has a method items() that returns self._items. Its add() method rejects duplicates. Explain how a caller can still add a duplicate, and give a one-line change to items() that closes the hole.
Show answer
A caller can write obj.items().append("x") twice. The method returns the live internal list, so append runs on it directly and add() and its duplicate check are never involved. Changing items() to return tuple(self._items) (or list(self._items) for a copy) hands out a snapshot instead, so changes to it do not affect the object's state.
Exercise
In the second Account example, a script runs acct._balance = -10 and then print(acct.balance()). What is printed, and what does this show about encapsulation in Python?
Show answer
It prints -10. The underscore is only a convention, so Python allows the assignment and the invariant is broken. This shows that the protection depends on callers respecting the public interface. Python does not enforce it.