Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

property.setter — controlled writes to a property

Use `property.setter` to make ordinary assignment to an instance attribute call a function that can validate the new value before storing it.

Version: Python 3.12

Syntax

class Task:
    @property
    def priority(self):
        return self._priority

    @priority.setter
    def priority(self, value):
        self._priority = value

# Functional form for an existing property p and a setter function set_priority:
# p = p.setter(set_priority)

In Python 3.12, @property creates a property with a getter. property.setter is a method on an existing property object. It takes a write function and returns a new property with that function as fset, preserving the getter and any deleter. It does not modify the original property object.

Place @priority.setter after the getter and name the setter function priority too. In the class body, the decorator result is bound to the function's name. If you use a different name, the new property will not replace the original priority.

Reading task.priority calls the getter. Assigning task.priority = value calls the setter with the instance as self and the new value as value. Without a setter, assignment raises AttributeError. The setter does not store anything automatically, and assignment ignores its return value.

Validate the value before storing it in a separate attribute such as self._priority. Assigning to self.priority inside its own setter would call the setter again. The leading underscore is only a convention: writing directly to _priority bypasses validation.

Examples

class Task:
    def __init__(self, priority):
        self.priority = priority

    @property
    def priority(self):
        return self._priority

    @priority.setter
    def priority(self, value):
        if type(value) is not int:
            raise TypeError("priority must be an int")
        if not 1 <= value <= 5:
            raise ValueError("priority must be between 1 and 5")
        self._priority = value


task = Task(2)
print(task.priority)
task.priority = 4
try:
    task.priority = 0
except ValueError:
    print("ValueError")
print(task.priority)

Result

2
ValueError
4

Construction and later assignment use the same setter. It accepts only values of type `int` from `1` to `5`. Assigning `0` raises `ValueError`; the program catches it and shows that the stored value is still `4`.

Related lessons

  • Python · Lesson 2 · Advanced · Version: 5

Sources