Sub topic 7
Adding a setter with validation
This chapter assumes you can define classes and __init__, use the @ decorator syntax, and raise and catch exceptions. It also assumes you have seen a read-only @property getter, which the previous chapter covered. Here you add the other half: a setter, so that assignment to a public-looking attribute runs your code.
Why a setter
A plain attribute accepts anything. If item.price = -5 should be an error, a plain attribute can't say so. You could add set_price() and get_price() methods, but every caller would then have to change from item.price = 5 to item.set_price(5).
A property setter avoids that. Callers keep writing item.price = 5. Python routes the assignment to your function, and the function can check the value, convert it, or reject it.
The basic shape
A setter is a second function with the same name as the getter. You decorate it with @name.setter.
class Product:
def __init__(self, price):
self._price = price
@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
p = Product(10)
p.price = 12.5
print(p.price) # 12.5
try:
p.price = -1
except ValueError as exc:
print(exc) # price cannot be negative
print(p.price) # 12.5, the rejected value was not storedFour rules explain this code.
- The getter must come first.
@price.setterlooks up the existing namepricein the class body, so it has to exist already. - The setter function has the same name as the property. Each
def pricerebinds the namepricein the class body to a new property object that includes the setter. - The value is stored under a different name, here
_price. The leading underscore is the convention for "internal, use the property instead", covered earlier in this tutorial. - The setter's return value is ignored. Assignment is a statement, so a setter should return nothing.
What happens on assignment
When you write p.price = 12.5, Python looks for price on the class, finds a property, and calls its setter with the new value. Your code runs before anything is stored.
The order inside the setter matters. Validate first, store last. If you store the value and then check it, a failed check leaves the object holding the bad value.
Choosing the exception
Use the exception type that tells the caller what went wrong.
TypeErrormeans the value is the wrong kind of thing, such as a string where a number is needed.ValueErrormeans the type is acceptable but the value is not, such as a negative price.
A setter often needs both checks.
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
@property
def price(self):
return self._price
@price.setter
def price(self, value):
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise TypeError(f"price must be a number, got {type(value).__name__}")
if value < 0:
raise ValueError("price cannot be negative")
self._price = float(value)
p = Product("pen", 3)
print(p.price) # 3.0
for bad in ("free", True, -2):
try:
p.price = bad
except (TypeError, ValueError) as exc:
print(type(exc).__name__, exc)The isinstance(value, bool) check is deliberate. In Python, bool is a subclass of int, so True would otherwise pass as the number 1. The setter also converts the value with float(value). A setter can normalize its input as well as validate it, so the attribute always holds one consistent type.
Validation that depends on other attributes
A setter can read other attributes of the object. A date range is a typical case.
class Booking:
def __init__(self, start, end):
self._start = start
self.end = end # goes through the setter, which reads self._start
@property
def end(self):
return self._end
@end.setter
def end(self, value):
if value < self._start:
raise ValueError("end cannot be before start")
self._end = value
b = Booking(5, 8)
b.end = 9
try:
b.end = 2
except ValueError as exc:
print(exc) # end cannot be before startThis works only because _start is assigned before end. Changing the order in __init__ would raise AttributeError inside the setter. The next chapter treats validation from __init__ in detail.
Cross-attribute rules have a limit. If start is also settable, moving it past end would break the rule, and the end setter would not run. Keep such invariants simple, or put the check in a method that changes both values together.
Common errors
Storing under the property's own name
The most frequent mistake is writing to self.price inside the price setter. That assignment calls the setter again, which assigns again, and so on.
class Broken:
@property
def x(self):
return self._x
@x.setter
def x(self, value):
self.x = value # calls this setter again
b = Broken()
try:
b.x = 1
except RecursionError:
print("infinite recursion: the setter assigned to itself")The same loop happens in a getter that reads self.x. Always store under a different name, usually the underscore version.
Naming the setter differently
If the setter function has a different name, you don't extend the original property. You create a second, separate one.
class Misnamed:
def __init__(self):
self._v = 0
@property
def v(self):
return self._v
@v.setter
def set_v(self, value): # wrong name
self._v = value
m = Misnamed()
try:
m.v = 5
except AttributeError:
print("v is still read-only")
m.set_v = 5 # this works, but it is not what you wanted
print(m.v) # 5Here v keeps only its getter, and a new property called set_v appears. The error message property 'v' of 'Misnamed' object has no setter is the sign of this mistake.
Setting a value before the storage name exists
If the getter runs before anything has assigned _price, you get AttributeError: 'Product' object has no attribute '_price'. Make sure __init__ assigns the attribute, preferably through the setter, so it always exists.
Bypassing the setter
Validation protects only code that goes through the property. Writing p._price = -5 skips it. Python does not enforce privacy, so the underscore is a signal and not a barrier. Inside the class, use self.price = value when you want validation to apply, and self._price = value only when you have already validated the value and need to skip the check.
Mutable values
A setter validates assignment, not mutation. If the property holds a list, obj.items.append(-1) never calls the setter. When that matters, return a copy or a tuple from the getter, or give the class methods such as add_item().
Quick reference
| Task | Pattern |
|---|---|
| Make an attribute validated | Getter, then `@name.setter` with the same name |
| Reject a wrong type | `raise TypeError(...)` |
| Reject a wrong value | `raise ValueError(...)` |
| Keep one stored type | Convert in the setter, for example `float(value)` |
| Avoid recursion | Store under `_name`, never `name` |
Exercise
Write a class Thermostat with a property target that only accepts numbers from 10 to 30 inclusive. A non-number raises TypeError, and a number outside the range raises ValueError. Why does the setter store the value in _target instead of target, and what happens if you use self.target = value inside the setter?
Show answer
class Thermostat:
def _init(self, target=20):
self.target = target
@property
def target(self):
return self.target
@target.setter
def target(self, value):
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise TypeError("target must be a number")
if not 10 <= value <= 30:
raise ValueError("target must be between 10 and 30")
self.target = value
The value is stored in `target because target is the property itself. Using self.target = value` inside the setter calls the setter again, which repeats forever and ends with a RecursionError.