The following code tests parts of a dictionary. The idea is, that only the keys available in the TestDict
are checked. Other keys should be ignored. What troubles me, are the two asserts at the bottom:
Both comparisons work fine. For the first one, I expected this. The TestDict
is on the left, so his __eq__
is called. But I would have expected the second one to fail, as I assumed it would not call the __eq__
of TestDict
. Obviously Python is smart enough to switch the order of the arguments. Can somebody explain the exact rules to me?
class TestDict(dict):
def __eq__(self, other):
print "other:", other
for key, val in self.items():
if callable(val):
return val(other[key])
else:
return val == other[key]
ref = TestDict(
a=5,
b=lambda x: x > 5
)
result = dict(
a=5,
b=9,
c=10
)
assert ref == result
assert result == ref