Sub topic 8
Validating from __init__ through the setter
This chapter assumes you can define classes, write __init__, use the @ decorator syntax, and raise and catch exceptions. It also assumes you know the basic @property getter and setter pattern from the previous chapters.
The problem: validation that can be bypassed
A setter only protects an attribute if every assignment goes through it. The constructor is the easiest place to break that rule. Consider this version:
class Celsius:
def __init__(self, degrees):
self._degrees = degrees # writes the private name directly
@property
def degrees(self):
return self._degrees
@degrees.setter
def degrees(self, value):
if value < -273.15:
raise ValueError("temperature is below absolute zero")
self._degrees = value
bad = Celsius(-500) # no error
print(bad.degrees) # -500
bad.degrees = -500 # ValueErrorThe object is created in an invalid state. Only later assignments are checked, so the class has two different sets of rules.
The fix: assign through the public name
In __init__, assign to self.degrees, not self._degrees. Python then finds the property on the class and calls the setter, so the same check runs for the first value and for every later one.
class Celsius:
def __init__(self, degrees):
self.degrees = degrees # runs the setter, so validation applies here too
@property
def degrees(self):
return self._degrees
@degrees.setter
def degrees(self, value):
if value < -273.15:
raise ValueError("temperature is below absolute zero")
self._degrees = value
@property
def fahrenheit(self):
return self._degrees * 9 / 5 + 32
t = Celsius(25)
print(t.degrees) # 25
print(t.fahrenheit) # 77.0
t.degrees = 30 # goes through the setter
try:
t.degrees = -300
except ValueError as exc:
print(exc) # temperature is below absolute zeroThe setter is the only place that writes _degrees. The validation rule exists once, and you can change it without touching __init__.
What happens when validation fails
If the setter raises inside __init__, the exception propagates out of the constructor call. No object is returned to the caller, so you never hold a half-built, invalid instance. Callers handle this the same way as any other error:
try:
Celsius(-300)
except ValueError as exc:
print("could not create:", exc)Common errors
- Assigning to the private name in
__init__. This skips validation, as in the first example. Look forself._name = ...in constructors of classes that also define a setter. - Reading before the setter has run. The getter returns
self._degrees. If you readself.degreesin__init__before assigning it, you getAttributeErrorbecause_degreesdoes not exist yet. - Using the setter name inside the setter. Writing
self.degrees = valueinside thedegreessetter calls itself and ends inRecursionError. The setter must store to the private name. - Setters that depend on other attributes. If validation of one attribute reads another, assign the attributes in an order that makes the needed values available.
Exercise
A class defines a price property with a setter that rejects negative values. Its __init__ contains self._price = price. What bug does this cause, and how do you fix it?
Show answer
Objects can be created with a negative price, because __init__ writes the private attribute and skips the setter. Change the line to self.price = price so the setter validates the initial value.
Exercise
What happens if Celsius(-300) is called with the setter-based __init__, and does the caller receive an object?
Show answer
The setter raises ValueError inside __init__. The exception propagates out of the call, so no object is returned to the caller.