Efficiently writing setters for property objects with similar attributes but different validations in Python

24 Views Asked by At

My Python class has an extensive list of properties. The properties share a similar structure bu have different validation conditions, which necessitates I write separate property setting functions for each one, like this:

def MyProperty:
    @property
    def content(self):
        return self._content

    @content.setter
    def content(self, value):
        self._content = value

    @property
    def sensor_name(self) -> str:
        return self._sensor_name

    @sensor_name.setter
    def sensor_name(self, value: str):
        self._sensor_name = value


def MyClass:
    def __init__(self):
        self._p1 = MyProperty()
        self._p2 = MyProperty()

    @property
    def p1(self):
        return self._p1

    @p1.setter
    def p1(self, value: str):
        self._p1.content = value

    @property
    def p2(self):
        return self._p2

    @p2.setter
    def p2(self, value: int):
        if value < 1:
            raise ValueError("Must be a positive integer.")
        self._p2.content = value

The problem: When my user instantiates c = MyClass() and sets a property of c, I want to ensure they can't circumvent the validation - i.e. they shouldn't be permitted to set c.p2.content = -10 directly. Yet, I also want to allow them to directly set the sensorName field separately from other fields, with c.p2.sensorName = "pressure" - or similar.

Possibilities I've considered:

  • Putting the validation in MyProperty is way too verbose because it requires 1 such class for every property, since each property has unique validation rules.
  • Writing separate functions for setting property fields (e.g. p1SetContent and p1SetSensorName) also seems more verbose than necessary, because setSensorName will be identical from property to property. It's only p{n}SetContentthat differs based on n.

Are there any other options?

0

There are 0 best solutions below