Q:

SQLAlchemy custom load/save functionality (setter and getter)

I am using the SQLAlchemy ORM for loading/saving from the database. However, I would like specific functions to be called on loading the data from the database, something like this:
class MyClass(Base):
    id = Column(Integer, primary_key = True)
    _data = relationship('Data')

    def __init__(self):
        self._data = []
        self.max_data = None
        self.min_data = None

    @property
    def data(self):
        return self._data

    @data.setter
    def data(self, data):
        print('gone through setter')
        self.min_data = min(data)
        self.max_data = max(data)
        self._data = data

However, I noticed that the setters and getters aren't called when saving/loading from the db. Is there a way to have these setters and getters called?
myclass = MyClass()
myclass.data = [0,1,2,3,4,5]
# gone through setter
myclass.max_data
# 5
myclass.min_data
# 0
session.add(myclass)
session.commit()

del myclass

myclass = session.query(MyClass).all()[0]
# setter is not called here
myclass.max_data
# None
myclass.min_data
# None

I would like the setter to be called on loading from the db as well, so that the min_data and max_data are set (without having to save them in the db explicitly)

A:

To attach behavior on load, use the load event:
@event.listens_for(MyClass, "load")
def _set_min_max_on_load(target, context):
    target.max_data = max(target._data)
    target.min_data = min(target._data)

In this particular instance, it may be helpful to simply use hybrid_propertys instead:
class MyClass(Base):
    ...
    @hybrid_property
    def max_data(self):
        return max(self.data)

    @max_data.expression
    def max_data(cls):
        return select([func.max(Data.__table__.c.some_value)]).where(Data.__table__.c.my_class_id == cls.id)

