Python: fix TypeError: NotImplemented should not be used in a boolean context 0 ▲ Adam Johnson 1 hour ago · Tech · hide · 0 comments Take this class, which implements __eq__() and derives __ne__() from it: class Lemming: def __init__(self, name): self.name = name def __eq__(self, other): if not isinstance(other, Lemming): return NotImplemented return self.name == other.name def __ne__(self, other): return not self.__eq__(other) This technique was common on Python 2, before Python 3.0 started deriving __ne__() automatically from __eq__() (release note). Now compare a Lemming with something that isn’t one: >>> p = Lemming("Lenny") >>> p != "Lenny" False Ah, woops, that’s wrong. A Lemming is not equal to the plain string "Lenny", so != should return True. If we run the same code on Python 3.9–3.13 with warnings enabled, we can see why: $ python -W default example.py /.../example.py:12: DeprecationWarning: NotImplemented should not be used in a boolean context return not self.__eq__(other) And on Python 3.14+, it’s no longer just a warning: >>> p != "Lenny" Traceback (most recent call last): ... TypeError:… No comments yet. Log in to reply on the Fediverse. Comments will appear here.