Samuel Wan
Samuel Wan

Reputation: 51

Subclassing python's dict, override of __setitem__ doesn't retain new value

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?

Upvotes: 2

Views: 1126

Answers (1)

Ned Batchelder
Ned Batchelder

Reputation: 376012

You are constructing new instances of CustomDict on each line. CustomDict(data) makes a new instance, which copies data.

Try this:

cd = CustomData({"message":"foo"})
cd["message"] = "bar"
print cd # prints "{'message': 'bar'}".

Upvotes: 10

Related Questions