Sub topic 7
Adding a setter with validation
This chapter assumes you can define classes with __init__, use the @ decorator syntax, raise and catch exceptions, and write a read-only @property getter. Here you add a setter, so assignment to an attribute can check the new value before storing it.
The problem a setter solves
A plain attribute accepts anything:
class Product:
def __init__(self, price):
self.price = price
p = Product(10)
p.price = -5 # accepted, though a negative price makes no senseYou want p.price = -5 to fail, but callers should still write p.price = ... rather than p.set_price(...). A property with a setter gives you both.
Defining the setter
A setter is a second method with the same name as the property. 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 = -5
except ValueError as exc:
print(exc) # price cannot be negative
print(p.price) # 12.5, the rejected value was never storedThe value lives in _price, and the public name price is the property. Because the setter raises before it assigns, a rejected value leaves the object unchanged.
What happens on assignment
Python looks up price on the class, finds a property, and calls its setter instead of writing to the instance dictionary.
Rules to remember
- The getter must be defined first.
@price.setteruses the existing property objectpriceand returns a copy of it with the setter added. - The setter method must have the same name as the property. A different name creates a separate, ordinary attribute and leaves the property read-only.
- The setter should store the value under a different name, conventionally
_price. - Raise
ValueErrorfor a value of the right type but an unacceptable content, andTypeErrorfor a wrong type.
Common errors
The most frequent mistake is storing under the property's own name. The setter then calls itself:
class Broken:
@property
def size(self):
return self._size
@size.setter
def size(self, value):
self.size = value # calls this setter again, forever
try:
Broken().size = 1
except RecursionError:
print("setter called itself until the stack ran out")The fix is self._size = value.
Two other errors are easy to hit:
- Defining
@price.setterwithout a getter above it gives aNameError, becausepricedoes not exist yet. - Mutating a stored object bypasses the setter. If a property holds a list,
obj.items.append(x)calls the getter and then mutates the list, so no validation runs.
Exercise
Exercise
A class defines @property def level(self) and then @level.setter def level(self, value): self.level = value. What happens on obj.level = 3, and how do you fix it?
Show answer
The setter assigns to self.level, which triggers the same setter again, so it recurses until Python raises RecursionError. Store the value in a different attribute, such as self._level = value, and have the getter return self._level.