Sub topic 10
When a Plain Attribute Is Better
This chapter assumes you can define classes, write __init__, use @property with a getter and setter, and raise and catch exceptions. The earlier chapters showed what properties can do. This one covers when you should not use them.
Plain attributes are the default
In Python, obj.name is a normal way to read data from an object. It is not an encapsulation failure. Python lets you change how an attribute works later, without changing the code that uses it. That is the main reason to start plain.
Compare these two classes:
class PointWithAccessors:
def __init__(self, x, y):
self._x = x
self._y = y
def get_x(self):
return self._x
def set_x(self, value):
self._x = value
def get_y(self):
return self._y
def set_y(self, value):
self._y = value
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(1, 2)
p.x = 10
print(p.x, p.y) # 10 2The first class adds ten lines and no behavior. Callers must write p.set_x(10) instead of p.x = 10. Accessor methods like these come from languages where changing a public field to a method breaks every caller, so they add the methods up front. Python does not have that problem.
Upgrading later without breaking callers
Suppose Product ships with a plain price attribute. Months later you need to reject negative prices. You replace the attribute with a property of the same name:
# Version 1
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
# Version 2: same public interface, now validated
class Product:
def __init__(self, name, price):
self.name = name
self.price = price # now runs the setter
@property
def price(self):
return self._price
@price.setter
def price(self, value):
if value < 0:
raise ValueError("price cannot be negative")
self._price = value
item = Product("pen", 2.5)
item.price = 3.0
print(item.price) # 3.0Code that reads or writes item.price runs unchanged. Because this upgrade is cheap, you lose nothing by waiting until a rule actually exists.
What a property costs
A property is not free. Each one adds the following:
- Code to read and maintain. A validated attribute takes about eight lines instead of one.
- A slower access path. Reading a property calls a function, which is slower than reading a value from the instance's
__dict__. For most programs this is irrelevant. In a hot loop over millions of objects it can matter. - Hidden work.
obj.valuelooks like a lookup. If it hits a database, callers cannot tell from the syntax. - A second name to keep in sync. The public name
priceand the storage name_pricemust stay consistent, and a typo in either causes a bug.
Use a property when the benefit is larger than these costs.
Cases where a plain attribute is the better choice
The property only passes the value through
This is the most common mistake:
class User:
def __init__(self, email):
self._email = email
@property
def email(self):
return self._email
@email.setter
def email(self, value):
self._email = valueThe getter and setter add no rule. This class behaves exactly like one with self.email = email, but it is longer and slower. Remove the property.
The attribute is just data
If a class mainly holds values, a dataclass gives you the constructor, repr, and equality with no accessors at all:
from dataclasses import dataclass
@dataclass
class Config:
host: str
port: int = 8080
cfg = Config("localhost")
cfg.port = 9000
print(cfg) # Config(host='localhost', port=9000)If you need one validation rule in a dataclass, you can add __post_init__ to check the values once at construction, or add a property for just that field.
Computing the value is expensive or has side effects
Attribute access should feel cheap and repeatable. If reading report.summary takes half a second, or reading it sends a network request, callers will not expect that. They may read it in a loop or in a debugger watch window.
Choose one of these instead:
- A method such as
report.compute_summary(). The parentheses signal that work happens. functools.cached_property, when the value is expensive but computed only once per instance and does not change.
class Report:
def __init__(self, rows):
self.rows = rows
def compute_summary(self):
# Parentheses at the call site tell the reader this may take time.
return sum(self.rows)
r = Report([1, 2, 3])
print(r.compute_summary()) # 6Reading the attribute changes state
A getter that increments a counter, consumes an item from a queue, or writes a log entry surprises callers. Reading twice should give the same answer unless something else changed the object. If an operation changes state, make it a method with a verb name such as pop_next().
The setter would need arguments
A property setter takes exactly one value. If the operation needs a second input, such as a unit, a currency, or a flag, use a method: account.set_balance(100, currency="EUR"). Forcing this through assignment creates an awkward design.
The value can fail in surprising ways
Assignment is expected to succeed. A setter that raises is fine for validation, as with ValueError for a negative price. A setter that may raise a ConnectionError or TimeoutError is a poor fit, because obj.x = 1 does not look like an operation that can fail on the network. Put I/O behind methods.
When a property is the right choice
The reverse also holds. Reach for a property in these cases:
| Situation | Why a property fits |
|---|---|
| A rule must hold on every assignment (a range, a type, a non-empty string) | The setter enforces it at one place |
| A value should be read-only after construction | A getter with no setter blocks assignment |
| A value is derived from other attributes and must not go stale | A computed property recalculates on each read |
| You are renaming or changing storage but must keep the old name working | The property forwards to the new storage |
| You want to deprecate an attribute and emit a warning | The getter can call `warnings.warn` |
Note that the last two rows describe a plain attribute that already existed and needed to change. That is the case in which a property pays for itself.
A decision flow
A short worked review
Consider this class and decide what to change:
class Order:
def __init__(self, order_id, items):
self._order_id = order_id
self._items = items
@property
def order_id(self):
return self._order_id
@property
def items(self):
return self._items
@items.setter
def items(self, value):
self._items = value
@property
def total(self):
return sum(price for _, price in self._items)Review each property in turn:
order_idis a read-only property that guards an identifier. This is a reasonable use, because it signals the id should not change. Keep it. A plain attribute would also be acceptable if your team does not care about accidental reassignment.itemshas a pass-through getter and setter. Replace it withself.items = items.totalis derived fromitems, so it must reflect the current list. Keep it as a property, as long as the list stays small. For very large orders, switch to a method.
The revised class:
class Order:
def __init__(self, order_id, items):
self._order_id = order_id
self.items = items
@property
def order_id(self):
return self._order_id
@property
def total(self):
return sum(price for _, price in self.items)
order = Order("A-1", [("pen", 2), ("book", 10)])
print(order.total) # 12
order.items.append(("lamp", 20))
print(order.total) # 32Summary of the rule
Start with a plain attribute. Add a property when a concrete need appears, such as a rule to enforce, a value to derive, or a name to keep stable. If the work is slow, has side effects, or needs extra arguments, use a method.
Exercise
A class has @property def name(self): return self._name and a setter def name(self, value): self._name = value, with no other logic. What should you do, and why does doing it not break existing callers?
Show answer
Replace the property with a plain self.name = name in __init__. The getter and setter add no behavior, only cost. Callers already use obj.name and obj.name = value, and a plain attribute supports the same syntax, so nothing changes for them. If a rule is needed later, you can add a property with the same name.
Exercise
A property named latest_price calls a web API each time it is read. Give two problems with this design and one alternative.
Show answer
Reading an attribute looks cheap and safe, so callers may read it repeatedly in a loop, which makes many network calls. The read can also fail with a network error that callers do not expect from attribute access. Use a method such as fetch_latest_price(), which signals that work happens. If a stable value is acceptable, cached_property fits only when the result never needs refreshing.