Python __ne__ Method
Last modified November 18, 2026 Python 3.15
The != operator calls __ne__ on its left operand.
By default object.__ne__ delegates to __eq__ and
negates the result, so most classes only need to define equality. This article
shows that default, explicit implementations, mixed types, a tolerance-based
rule, an early-exit optimization, inheritance and the functional form
operator.ne.
The default __ne__ from __eq__
When a class defines __eq__ but not __ne__,
Python's default __ne__ calls __eq__ and returns its
negation. The Point class below defines only equality.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
if not isinstance(other, Point):
return NotImplemented
return self.x == other.x and self.y == other.y
def __repr__(self):
return f"Point({self.x}, {self.y})"
p1 = Point(1, 2)
p2 = Point(1, 2)
p3 = Point(3, 4)
print(p1 == p2, p1 != p2)
print(p1 == p3, p1 != p3)
Both comparisons agree: p1 equals p2 and is not
unequal to it, while the opposite holds for p3. Writing only
__eq__ was enough because the default hook supplies the
negation.
$ python default_ne.py True False False True
An explicit __ne__ with NotImplemented
An explicit __ne__ should mirror the type checks in
__eq__ and return NotImplemented for unsupported
types. A common implementation delegates to equality and negates its result.
class Money:
def __init__(self, amount, currency):
self.amount = amount
self.currency = currency
def __eq__(self, other):
if not isinstance(other, Money):
return NotImplemented
return (self.amount, self.currency) == (other.amount, other.currency)
def __ne__(self, other):
if not isinstance(other, Money):
return NotImplemented
return not self.__eq__(other)
def __repr__(self):
return f"Money({self.amount}, {self.currency!r})"
a = Money(100, "USD")
b = Money(100, "USD")
c = Money(100, "EUR")
print(a != b, a != c)
The currency is part of both hooks, so two amounts in different currencies
are unequal. Returning NotImplemented for a foreign type lets
Python try the reflected operation before giving up.
$ python explicit_ne.py False True
Comparing with different types
A wrapper can compare with both its own type and a built-in. The inequality hook should reuse the equality logic so the two answers can never disagree.
class RomanNumeral:
def __init__(self, value):
self.value = value
def __eq__(self, other):
if isinstance(other, RomanNumeral):
return self.value == other.value
if isinstance(other, int):
return self.value == other
return NotImplemented
def __ne__(self, other):
eq = self.__eq__(other)
if eq is NotImplemented:
return NotImplemented
return not eq
def __repr__(self):
return f"RomanNumeral({self.value})"
n = RomanNumeral(5)
print(n != 5, n != 6, n != RomanNumeral(5))
print(n != "V")
The numeral compares cleanly with integers and with its own type. For the
string "V" both hooks return NotImplemented, so
Python falls back to identity comparison and the distinct objects are unequal.
That fallback is why NotImplemented is preferable to returning
False.
$ python cross_type_ne.py False True False True
Custom tolerance logic
Equality does not have to mean bit-for-bit identity. A geometry class can
treat points within a small distance as equal, and __ne__ must use
the same rule to stay the logical complement of equality.
class ClosePoint:
tolerance = 0.01
def __init__(self, x, y):
self.x = x
self.y = y
def _close(self, a, b):
return abs(a - b) <= self.tolerance
def __eq__(self, other):
if not isinstance(other, ClosePoint):
return NotImplemented
return self._close(self.x, other.x) and self._close(self.y, other.y)
def __ne__(self, other):
if not isinstance(other, ClosePoint):
return NotImplemented
return not self.__eq__(other)
def __repr__(self):
return f"ClosePoint({self.x}, {self.y})"
a = ClosePoint(1.0, 2.0)
b = ClosePoint(1.005, 2.0)
c = ClosePoint(1.1, 2.0)
print(a == b, a != b)
print(a == c, a != c)
The second point is within the tolerance, so it is equal and not unequal. The third point is outside the tolerance, so both hooks agree the other way. Sharing one rule between the two methods prevents contradictions.
$ python tolerance_ne.py True False False True
Early-exit optimization
For a large object, computing full equality can be wasteful when a single
different field is enough to answer !=. Checking components one
by one returns True as soon as a difference is found, while
producing exactly the same result as negating equality.
class Vector:
def __init__(self, *parts):
self.parts = list(parts)
def __eq__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return self.parts == other.parts
def __ne__(self, other):
if not isinstance(other, Vector):
return NotImplemented
if len(self.parts) != len(other.parts):
return True
for a, b in zip(self.parts, other.parts):
if a != b:
return True
return False
def __repr__(self):
return f"Vector{self.parts}"
v1 = Vector(1, 2, 3)
v2 = Vector(1, 2, 3)
v3 = Vector(1, 0, 3)
v4 = Vector(1, 2)
print(v1 != v2, v1 != v3, v1 != v4)
The first vector matches, the second differs in one component and the
third has a different length. All three answers match what negating
__eq__ would give, but the unequal cases can stop early.
$ python early_exit_ne.py False True True
Inheritance
A subclass that adds fields should extend equality and leave inequality to negate it. This keeps the two methods consistent even when the child adds new state.
class Animal:
def __init__(self, name):
self.name = name
def __eq__(self, other):
if not isinstance(other, Animal):
return NotImplemented
return self.name == other.name
def __ne__(self, other):
eq = self.__eq__(other)
if eq is NotImplemented:
return NotImplemented
return not eq
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
def __eq__(self, other):
if not isinstance(other, Dog):
return NotImplemented
return super().__eq__(other) and self.breed == other.breed
def __repr__(self):
return f"Dog({self.name}, {self.breed})"
d1 = Dog("Buddy", "Labrador")
d2 = Dog("Buddy", "Poodle")
print(d1 == d2, d1 != d2)
print(d1 == Animal("Buddy"), d1 != Animal("Buddy"))
Dogs with different breeds are unequal. The mixed comparison is subtler:
Dog.__eq__ returns NotImplemented for a plain
Animal, so Python tries Animal.__eq__ with the
arguments reversed. That hook accepts any Animal (including a
Dog) and compares only the name, so the two are equal and not
unequal. Use type(other) is type(self) if you want to forbid such
cross-class matches.
$ python inherit_ne.py False True True False
The operator.ne function
operator.ne(a, b) is the functional form of a != b.
It calls the same hook and is handy when a callable predicate is needed.
import operator
class Token:
def __init__(self, text):
self.text = text
def __eq__(self, other):
if not isinstance(other, Token):
return NotImplemented
return self.text == other.text
def __repr__(self):
return f"Token({self.text!r})"
a, b, c = Token("x"), Token("x"), Token("y")
print(operator.ne(a, b))
print(operator.ne(a, c))
print(operator.ne(2, 3))
The custom tokens use their equality hook through the default
__ne__, and the integers use their own. The results are ordinary
booleans suitable for filtering or sorting keys.
$ python operator_ne.py False True True
Best practices
A few rules keep != consistent:
- Define
__eq__; the default__ne__will usually be enough. - If you write
__ne__, make it the exact logical complement of__eq__. - Return
NotImplementedfor unsupported types instead ofFalse. - Reuse one rule for both hooks when adding tolerance or other custom logic.
- Use
operator.newhen you need a callable form of the operator.
Source
object.__ne__ - Python documentation
object.__eq__ - Python documentation
Rich comparisons - Python documentation
operator.ne - Python documentation
In this article we have implemented the __ne__ method. We have
covered the default derived from __eq__, explicit implementations,
mixed types, tolerance logic, early exit, inheritance and
operator.ne. For related topics, see
Python __eq__ method,
Python __lt__ method, and
Python operators.
Author
List all Python tutorials.