130 days ago · Tech · hide · Fediverse post

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:…

Commenting on Bubbles has been removed. Why? If you want to talk about this post, write to the author, use the comments on their blog if it has them, or reply with a "RE:" post on your own blog. Suggestions? feedback@bubbles.town