Skip to content

Instantly share code, notes, and snippets.

@jfly
Created April 3, 2018 23:06
Show Gist options
  • Select an option

  • Save jfly/98a6140a3f15a724dab6f9c9f1a03416 to your computer and use it in GitHub Desktop.

Select an option

Save jfly/98a6140a3f15a724dab6f9c9f1a03416 to your computer and use it in GitHub Desktop.

Revisions

  1. jfly created this gist Apr 3, 2018.
    34 changes: 34 additions & 0 deletions rich_comparisons.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    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)