I have a subclass of dict, but when I am writing it into database, I want to convert it back to a regular dict first. I wanted to use dict(a_instance_of_a_subclass_of_dict)
which looks like casting but I need to decide only certain keys are exported to the regular dict.
I don't know what special method of a mapping is called when you write dict(mapping)
so I did this experiment:
class Mydict(dict):
def __getattribute__(self, what):
print 'getting attribute:', what
m = Mydict(x = 2, y = 3, z = 4)
print '--------- mark ---------'
print dict(m)
It prints:
--------- mark ---------
getting attribute: keys
{'y': 3, 'x': 2, 'z': 4}
It looks like dict(mapping)
will call keys
method of mapping. (Actually something weird happens here. __getattribute__
returns None
here but dict
simply didn't rely on the return value and still gets the correct contents. Let's forget about this for now.)
Then I rewrote another subclass of dict like this:
class Mydict2(dict):
def keys(self):
print 'here keys'
return ['x', 'y']
m2 = Mydict2(x = 2, y = 3, z = 4)
print '--------- mark2 ---------'
print dict(m2)
Output is this:
--------- mark2 ---------
{'y': 3, 'x': 2, 'z': 4}
It didn't call keys method. Weird again!
Can somebody explain this behavior? Thanks in advance!