At first i thought about __copy__
overriding but this way you will not use built-in dict copy method. So, jump to update!
You can define __copy__
method for your DictWithTimestamp
class in which you can copy additional class data. From docs:
In order for a class to define its own copy implementation, it can
define special methods __copy__()
and __deepcopy__()
. The former is
called to implement the shallow copy operation; no additional
arguments are passed. The latter is called to implement the deep copy
operation; it is passed one argument, the memo dictionary. If the
__deepcopy__()
implementation needs to make a deep copy of a component, it should call the deepcopy() function with the component
as first argument and the memo dictionary as second argument.
update: you can do it with collections.MutableMapping
subclass (read more about it here: How to "perfectly" override a dict?):
class DictWithTimestamp(collections.MutableMapping):
def __init__(self, timestamp=None):
self.store = dict()
self.timestamp = timestamp
def __getitem__(self, key):
return self.store[key]
def __setitem__(self, key, value):
self.store[key] = value
def __delitem__(self, key):
del self.store[key]
def __iter__(self):
return iter(self.store)
def __len__(self):
return len(self.store)
def setstore(self, store):
self.store = store
def copy(self):
copy = self.__class__(self.timestamp)
copy.setstore(self.store.copy())
return copy
Test:
>>> d = DictWithTimestamp(1234)
>>> d['i'] = 1
>>> d.timestamp
1234
>>> d1 = d.copy()
>>> d1.items()
[('i', 1)]
>>> d1.timestamp
1234