Hi, I'm subclassing dict, but ran into a problem with setitem where one assignment works, but another assignment does not. I've boiled it down to the following basic problem:
class CustomDict(dict):
def __setitem__(self, key, value):
super(CustomDict, self).__setitem__(key, value)
Test 1 fails:
data = {"message":"foo"}
CustomDict(data)["message"] = "bar"
print CustomDict(data) # Expected "{'message': 'bar'}". Actual is "{'message': 'foo'}".
print data # Expected "{'message': 'bar'}". Actual is "{'message': 'foo'}".
Test 2 succeeds:
data = CustomDict({"message":"foo"})
data["message"] = "bar"
print CustomDict(data) # Expected "{'message': 'bar'}". Actual matches expected.
print data # Expected "{'message': 'bar'}". Actual matches expected.
I looked online but couldn't tell whether the subclass constructor copies the dictionary so operations are performed on a different instance of the dictionary. Any advice?