Sub topic 10
When a plain attribute is better
This chapter assumes you can define classes, write __init__, use the @ decorator syntax, and raise and catch exceptions. You should also know how @property getters and setters work from earlier chapters.
Start with a plain attribute
Python lets you read and assign instance attributes directly. A property is worth adding only when it does something a plain attribute cannot. Because a property uses the same obj.name syntax as a plain attribute, you can add one later without changing any calling code. That makes it safe to start simple.
class User:
def __init__(self, name):
self.name = name
u = User("Ada")
u.name = "Grace"
print(u.name) # GraceBoilerplate that does nothing
A common mistake is to copy the getter/setter habit from other languages. This property adds no validation, no computation, and no restriction:
class User:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = valueIt behaves exactly like self.name = name. It costs more lines, more indirection, and a slower attribute lookup. Remove it.
Reasons to use a property
Use a property when you need at least one of these:
- Validation or normalization when a value is assigned.
- A read-only attribute.
- A value computed from other attributes, so it never goes stale.
- A way to change how an attribute is stored while keeping the public name.
If none applies, keep the plain attribute.
class Temperature:
def __init__(self, degrees):
self.degrees = degrees # first version: plain attributeIf you later need validation, rename the storage to _degrees and add a property named degrees. Callers still write t.degrees = 30.
Costs and limits of properties
Properties are not free:
- Each access runs a function call, so it is slower than a plain attribute read.
- A getter that does heavy work surprises callers who expect attribute access to be cheap. Use
cached_propertyor a method for expensive work. - A getter or setter with side effects, such as network calls or file writes, hides that cost behind attribute syntax. A method such as
save()is clearer. - Properties live on the class, not the instance. You cannot add one to a single object.
import time
class Report:
@property
def data(self):
time.sleep(2) # looks like an attribute, behaves like a slow call
return [1, 2, 3]A method named load_data() tells the reader that work happens.
Choosing quickly
| Need | Best choice |
|---|---|
| Store a value, no rules | Plain attribute |
| Reject invalid values | Property with setter |
| Value must not change from outside | Read-only property |
| Derived from other attributes | Computed property |
| Derived and expensive, computed once | `cached_property` |
| Action with side effects or cost | Method |
Common errors
- Writing a property whose getter and setter only pass the value through.
- Giving a property a side effect that callers do not expect.
- Doing expensive work in a getter that is read inside a loop.
Exercise
A class has a property title with a getter returning self._title and a setter doing self._title = value. Nothing else uses _title. What should you do, and why can you do it without changing code that uses the class?
Show answer
Replace the property with a plain attribute self.title = title in __init__. The property adds no validation or computation, and callers use the same obj.title syntax either way, so their code keeps working. If you need rules later, you can add a property again.
Exercise
A property report reads a large file from disk every time it is accessed. Name two better options.
Show answer
Use functools.cached_property if the file should be read once per instance. Use a method such as load_report() if the cost should be visible to callers or the file may change between reads.