Skip to content

Instantly share code, notes, and snippets.

@jfly
Created April 3, 2018 23:06
Show Gist options
  • Save jfly/98a6140a3f15a724dab6f9c9f1a03416 to your computer and use it in GitHub Desktop.
Save jfly/98a6140a3f15a724dab6f9c9f1a03416 to your computer and use it in GitHub Desktop.
Playing around with python's rich comparison operators
from __future__ import print_function
import functools
@functools.total_ordering
class Comparable():
def __init__(self, value):
self._value = value
def __lt__(self, o):
return self._value < o._value
def __eq__(self, o):
return self._value == o._value
#<<< def __cmp__(self, o):
#<<< return self._value - o._value
def __repr__(self):
return "{}".format(self._value)
one = Comparable(1)
two = Comparable(2)
other_one = Comparable(1)
def every_operator(val1, val2):
print("{} == {}: {}".format(val1, val2, val1 == val2))
print("{} < {}: {}".format(val1, val2, val1 < val2))
print("{} <= {}: {}".format(val1, val2, val1 <= val2))
print("{} > {}: {}".format(val1, val2, val1 > val2))
print("{} >= {}: {}".format(val1, val2, val1 >= val2))
every_operator(one, one)
print()
every_operator(one, two)
@jfly
Copy link
Author

jfly commented Apr 3, 2018

I was toying around with this after reading http://portingguide.readthedocs.io/en/latest/comparisons.html.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment