Skip to content

Instantly share code, notes, and snippets.

@slezica
Created May 20, 2012 04:57
Show Gist options
  • Save slezica/2748698 to your computer and use it in GitHub Desktop.
Save slezica/2748698 to your computer and use it in GitHub Desktop.
Automatic comparison operators in python
class Order(object):
__lt__ = lambda self, other: other > self
__gt__ = lambda self, other: not self <= other
__le__ = lambda self, other: other >= self
__ge__ = lambda self, other: not self < other
__ne__ = lambda self, other: self < other or other < self
__eq__ = lambda self, other: not self != other
import operator, inspect
if __name__ == '__main__':
# Test all operators work after inheriting Order and overriding only one
OPS = ('lt', 'gt', 'le', 'ge')
class Test(Order):
def __init__(self, n):
self.n = n
__repr__ = lambda self: repr(self.n)
def testClass(fname, f):
return type('Test' + fname, (Test,), {
fname: lambda self, other: f(self.n, other.n),
})
classes = [ testClass('__%s__' % op, getattr(operator, op)) for op in OPS ]
def testOperators(a, b):
for op in ("<", ">", "<=", ">=", "==", "!="):
result = eval("a " +op+ " b")
correct = "OK" if result == eval("a.n " +op+ " b.n") else "ERROR"
print "\t%(a)s %(op)s %(b)s\t%(result)s\t(%(correct)s)" % locals()
for cls in classes:
print "Testing " + cls.__name__
testOperators(cls(1), cls(5))
testOperators(cls(3), cls(3))
testOperators(cls(8), cls(1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment