Last active
December 15, 2015 20:59
-
-
Save kamiller/5322435 to your computer and use it in GitHub Desktop.
python comparable mixin to ease comparision and hashing of objects
This file contains hidden or 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 ComparableMixin(object): | |
def _compare(self, other, method): | |
try: | |
return method(self._cmpkey(), other._cmpkey()) | |
except (AttributeError, TypeError): | |
raise NotImplementedError("_cmpkey not implemented") | |
def __lt__(self, other): | |
return self._compare(other, lambda s,o: s < o) | |
def __le__(self, other): | |
return self._compare(other, lambda s,o: s <= o) | |
def __eq__(self, other): | |
return self._compare(other, lambda s,o: s == o) | |
def __ge__(self, other): | |
return self._compare(other, lambda s,o: s >= o) | |
def __gt__(self, other): | |
return self._compare(other, lambda s,o: s > o) | |
def __ne__(self, other): | |
return self._compare(other, lambda s,o: s != o) | |
def __hash__(self): | |
try: | |
return hash(self._cmpkey()) | |
except (AttributeError, TypeError): | |
raise NotImplementedError("_cmpkey not implemented") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment