How to: Override Equals in Python

Just got bit by this. So if you want to override the equality operator in python the simplest thing to do is override the __eq__ method. For example:

class MyFoo(object):
    def __init__(self, equalityprop):
        self.equalityprop = equalityprop
    def __eq__(self, obj):
        return isinstance(obj, MyFoo) and obj.equalityprop == self.equalityprop
Then you can use the == operator and it behaves as you would expect.
MyFoo(“bar”) == MyFoo(“bop”)  # False
MyFoo(“bar”) == MyFoo(“bar”)   # True
What you might not realize is that this has absolutely no effect on the != operator.
MyFoo(“bar”) == MyFoo(“bop”)  # True
MyFoo(“bar”) !=  MyFoo(“bar”)   # True (!)
If you want to override != (which you probably do) you also have to override the __ne__ method. One simple thing you can do is:
    def __ne__(self, obj):
        return not self == obj
Good times.



Similar Articles

The World's Most Powerful Mobile Data Collection Platform

Start a FREE 30-day CommCare trial today. No credit card required.

Get Started

Learn More

Get the latest news delivered
straight to your inbox