Created
May 20, 2012 04:57
-
-
Save slezica/2748697 to your computer and use it in GitHub Desktop.
Automatic comparison operators in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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