Back to results for “Exception Handling”
Python › Descriptors & Properties

How do you add a setter to a property so assignment (obj.attr = value) triggers custom logic, like validation?

Beginner

Answer

Define a second method with the SAME name, decorated with @property_name.setter — this method runs whenever someone assigns to the property, letting you validate or transform the incoming value before storing it (typically in a differently-named private attribute).
class Temperature:
    def __init__(self, celsius):
        self._celsius = celsius
    @property
    def celsius(self):
        return self._celsius
    @celsius.setter
    def celsius(self, value):
        if value < -273.15:
            raise ValueError("Below absolute zero!")
        self._celsius = value

t = Temperature(20)
t.celsius = 25  # runs the setter's validation logic
Real-world example Validating that a value assigned to an attribute (like temperature or age) meets certain constraints before accepting it.

Common follow-ups: Why does the underlying stored value typically need a DIFFERENT name (like _celsius) from the property itself (celsius)?