Python: inheretance messes up order of arguments for __eq__

Viewed 50

For some I-dont-care-about reason python swaps order of at least __eq__ and __ne__ when it sees that one side is an instance of derived class of the other side

    class Base:
        def __init__(self,n):
            self.whoami=n
        def __eq__(self, other):
            print(f"{self.whoami} == {other.whoami}")
        
    class Derived(Base):
        pass

    base_lhs = Base("base.lhs")
    base_rhs = Base("base.rhs")
    derived_rhs = Derived("derived.rhs")

    ok                              = base_lhs == base_rhs
    what_the_fuck_you_stupid_donkey = base_lhs == derived_rhs

Produces

base.lhs == base.rhs
derived.rhs == base.lhs

What's a good way to make python stop doing this implicit swap of arguments? Can I inside of __eq__ somehow check that python done goofed and I need to rearrange arguments back? I can't simply swap them or return NotImplemented as sometimes I compare base to derived and sometimes I do it the other way.

0 Answers
Related