Sub topic 8
Validating from __init__ through the setter
This chapter assumes you can write a class with __init__, that you know the @property getter and @x.setter syntax, and that you can raise and catch exceptions. Here you learn why __init__ should assign through the public property name, and what goes wrong when it doesn't.
The gap: validation that __init__ skips
A setter only runs when code assigns through the property name. If __init__ writes to the private storage attribute instead, the setter never runs for the starting value.
class Celsius:
def __init__(self, degrees):
self._degrees = degrees # writes storage directly, skips the setter
@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
c = Celsius(-500)
print(c.degrees) # -500, an impossible value got in
try:
c.degrees = -500
except ValueError as exc:
print(exc) # temperature is below absolute zeroThe same value -500 is accepted by the constructor and rejected by the assignment. The class makes a promise ("degrees is never below absolute zero") that holds for every path except object creation. Object creation is the path most callers use, so this is a real hole.
The fix: assign through the public name
Write self.degrees = degrees in __init__. Python looks up degrees on the class, finds a data descriptor (the property), and calls its setter. The validation rule then lives in one place and covers both construction and later assignment.
class Celsius:
def __init__(self, degrees):
self.degrees = degrees # runs the setter
@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
print(Celsius(25).degrees) # 25
try:
Celsius(-500)
except ValueError as exc:
print(exc) # temperature is below absolute zeroWhen __init__ raises, the call Celsius(-500) produces no usable object. The caller never receives a half-built instance, so an invalid Celsius cannot exist. This is the main benefit of the pattern.
Mistakes to avoid
Writing to the storage name in __init__
This is the bug shown earlier. It is easy to introduce because self._degrees = degrees looks correct and works for valid input. Tests that only pass valid values will not catch it. Add a test that constructs the object with an invalid value and expects the exception.
Assigning to the property name inside its own setter
Inside the setter, the storage name must differ from the property name. If the setter assigns to self.degrees, it calls itself.
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("setter called itself until the stack ran out")The same mistake in the getter (return self.x) also ends in RecursionError. Use a different name for the stored value, conventionally the property name with a leading underscore.
Forgetting that the getter needs the value to exist
If __init__ raises before the setter stores anything, there is no _degrees. That is harmless here because the object is discarded. It matters if you catch the exception inside __init__ and carry on. Then reading the property later raises AttributeError: 'Celsius' object has no attribute '_degrees'. Let validation errors propagate out of __init__ instead of swallowing them.
Skipping the setter with __dict__ or object.__setattr__
Code such as obj.__dict__["_degrees"] = -500 or setattr(obj, "_degrees", -500) writes straight to the storage name. Python does not stop this, which fits its convention-based approach to privacy. Treat the underscore as a signal to other developers, not a lock.
Setters that depend on other attributes
A setter can read other attributes of the instance. Then the order of assignments in __init__ matters, because the setter runs at the moment of assignment.
class Level:
def __init__(self, floor, value):
self.floor = floor # plain attribute, must be set first
self.value = value # setter reads self.floor
@property
def value(self):
return self._value
@value.setter
def value(self, new_value):
if new_value < self.floor:
raise ValueError(f"value {new_value} is below floor {self.floor}")
self._value = new_value
lvl = Level(floor=10, value=15)
print(lvl.value) # 15
try:
Level(floor=10, value=5)
except ValueError as exc:
print(exc) # value 5 is below floor 10If you swapped the two lines in __init__, the setter would run before self.floor exists. You would get AttributeError: 'Level' object has no attribute 'floor'. The error message points at floor, but the cause is the assignment order.
This design has a second weakness. After construction, lvl.floor = 20 is accepted by the plain attribute, and lvl.value (15) is now below the floor. The setter only checks value at the moment value is assigned. When two attributes must stay consistent, make both properties and have each setter check the other. Or store them together and validate them in one method. For example, a set_bounds(floor, value) method can check the pair and then assign both.
Converting values as well as checking them
A setter can also normalize its input. The rule then applies on every path, including construction.
class User:
def __init__(self, email):
self.email = email
@property
def email(self):
return self._email
@email.setter
def email(self, value):
if "@" not in value:
raise ValueError("email must contain @")
self._email = value.strip().lower()
u = User(" [email protected] ")
print(u.email) # [email protected]Raise TypeError when the type is wrong (for example, a number where a string is required) and ValueError when the type is right but the value is not acceptable. Callers can then tell the two failures apart.
Subclasses and the constructor
self.degrees = degrees in the base class __init__ looks up degrees on the instance's actual class. If a subclass overrides the property, the subclass setter runs during base construction. That is usually what you want, because the subclass's stricter rule applies to the starting value too.
class Celsius:
def __init__(self, degrees):
self.degrees = degrees
@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
class Freezer(Celsius):
@Celsius.degrees.setter
def degrees(self, value):
if value > 0:
raise ValueError("a freezer must stay at or below 0")
Celsius.degrees.fset(self, value) # reuse the base rule
print(Freezer(-18).degrees) # -18
try:
Freezer(5)
except ValueError as exc:
print(exc) # a freezer must stay at or below 0Freezer inherits the getter and replaces only the setter. It calls the base setter through Celsius.degrees.fset so the absolute-zero check still applies. The subclass does not need its own __init__. If the base class had written self._degrees = degrees, the Freezer rule would be skipped at construction, which is another reason to go through the property.
Summary of the pattern
| Situation | What to write in __init__ | Result |
|---|---|---|
| Attribute has a validating setter | `self.name = name` | Validation runs on construction |
| Attribute is a plain attribute | `self.name = name` | Value is stored as is |
| Read-only property with stored value | `self._name = name` | Setter does not exist, so write to storage |
| Setter reads another attribute | Assign that attribute first | No `AttributeError` from missing state |
The read-only row is the one case where you do write to the underscore name. A read-only property has no setter to go through, so __init__ must set the storage attribute directly. If a read-only value needs validation, check it in __init__ before storing it.
Exercise
A class defines a price property whose setter rejects negative numbers. Its __init__ contains self._price = price. A test calls Item(-5) and expects a ValueError, but the test fails because no exception is raised. Explain why, and show the one-line change that fixes it.
Show answer
self._price = price writes directly to the storage attribute, so the setter never runs and the negative value is stored. Change the line to self.price = price. Python then finds the price property on the class and calls its setter, which raises ValueError for -5.
Exercise
A class Range has plain attribute low and property high. The high setter raises ValueError if the new value is less than self.low. __init__(self, low, high) first runs self.high = high and then self.low = low. What happens when you call Range(1, 5), and how do you fix it?
Show answer
The high setter runs first and reads self.low, which has not been assigned yet. This raises AttributeError: 'Range' object has no attribute 'low'. Fix it by assigning self.low = low before self.high = high in __init__.