I am trying to make an object act like an inline list
, except that its value is saved after changing it.
The implementation I came across includes a list
in the PersistentList
class. For each access to the method that can change the list, the wrapper delegates the wrapped list
and stores it in the key database after it is called.
the code:
class PersistentList(object): def __init__(self, key): self.key = key self._list = db.get(key, []) def __getattr__(self, name): attr = getattr(self._list, name) if attr: if attr in ('append', 'extend', 'insert', 'pop', 'remove', 'reverse', 'sort'): attr = self._autosave(attr) return attr raise AttributeError def _autosave(self, func): @wraps(func) def _(*args, **kwargs): ret = func(*args, **kwargs) self._save() return ret return _ def _save(self): db.set(self.key, self._list)
There are several problems with this implementation:
I have to decorate methods like append
every time they are available, is there a better way to decorate several methods of some object?
Operations like l += [1,2,3]
do not work, because I do not have implemented the iadd method.
What can I do to simplify this?
source share