I have a user defined dictionary (sub-classing python's built-in dict object), which does not allow modifying the dict directly:
class customDict(dict):
"""
This dict does not allow the direct modification of
its entries(e.g., d['a'] = 5 or del d['a'])
"""
def __init__(self, *args, **kwargs):
self.update(*args, **kwargs)
def __setitem__(self,key,value):
raise Exception('You cannot directly modify this dictionary. Use set_[property_name] method instead')
def __delitem__(self,key):
raise Exception('You cannot directly modify this dictionary. Use set_[property_name] method instead')
My problem is that I am not able to deep copy this dictionary using copy.deepcopy. Here's an example:
d1 = customDict({'a':1,'b':2,'c':3})
print d1
d2 = deepcopy(d1)
print d2
where it throws the exception I've defined myself for setitem:
Exception: You cannot directly modify this dictionary. Use set_[property_name] method instead
I tried overwriting deepcopy method as follows as suggested here:
def __deepcopy__(self, memo):
cls = self.__class__
result = cls.__new__(cls)
memo[id(self)] = result
for k, v in self.__dict__.items():
setattr(result, k, deepcopy(v, memo))
return result
This doesn't throw any errors but it returns an empty dictionary:
d1 = customDict({'a':1,'b':2,'c':3})
print d1
d2 = deepcopy(d1)
print d2
{'a': 1, 'c': 3, 'b': 2}
{}
Any ideas how to fix this?