Handy Python tip #1

Posted on Thu 07 June 2012 in Posts

The other day I was adding the rich comparison methods (the ones for operator overloading) to a class I had defined. Like many Python programmers before me I wondered "why is it that if I define a method for equality, I still have to define a not-equal method?" and "if I define a comparison method, why do I have to define the other comparison methods?"

And then low and behold, while looking for something completely different, I stumbled across the functools.total_ordering class decorator. With it, you can define just the __eq__ method, and any rich comparison method (__le__, __lt__, __gt__, etc), and it provides default implementations for all the others.

Very handy stuff.

An example can be found in my MiscPython examples collection on Github.

(Note: this post originally appeared on my blogspot blog at: