0

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
Achim
  • 15,415
  • 15
  • 80
  • 144
  • Note that `result.__eq__(ref)` is `False`; the reflection doesn't happen if you call the method directly. `x == y` is interpreted as `x.__eq__(y) or y.__eq__(z)`. – jonrsharpe Oct 14 '15 at 10:13
  • Sure. The `print` shows me, that the correct `__eq__` is called in both cases. But I'm curious why and how the exact rules are. – Achim Oct 14 '15 at 10:15

0 Answers0