'Custom default getters and setters in Python dataclass

I have a python dataclass, which, due to underlying storage data format, stores scalars as arrays of size 1, and vectors as bigger arrays. Thus for each member the dataclass implements an appropriate setter and getter, like:

@dataclass
class A():
 _scalar: np.ndarray = np.zeros(1, np.uint32)
 _vector: CustomVector("unsigned short") = CustomVector("unsigned short")

    @property
    def scalar(self):
        return self._scalar

    @scalar.setter
    def scalar(self, val: np.uint16) -> None:
        self._scalar[0] = val

    @property
    def vector(self):
        return self._vector

    @vector.setter
    def vector(self, value):
        # Clear the vector before setting
        self._vector.clear()

        self._vector += value

Of course, I have many other properties mainly of those two scalar and vector types. My code ends up being mainly getters and setters, which differ only in the variable name in the decorator and inside the method. I wonder, if there is a way in Python to make a default getter and setter, that would automatically be used? Something like:

@dataclass
class A():
 @use_scalar_gettersetter
 _scalar: np.ndarray = np.zeros(1, np.uint32)
 @use_vector_gettersetter
 _vector: CustomVector("unsigned short") = CustomVector("unsigned short")

Which would make the code much more readable... Thanks for any advice!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source