models.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. """Utilities for defining models
  2. """
  3. # The following comment should be removed at some point in the future.
  4. # mypy: disallow-untyped-defs=False
  5. import operator
  6. class KeyBasedCompareMixin(object):
  7. """Provides comparison capabilities that is based on a key
  8. """
  9. def __init__(self, key, defining_class):
  10. self._compare_key = key
  11. self._defining_class = defining_class
  12. def __hash__(self):
  13. return hash(self._compare_key)
  14. def __lt__(self, other):
  15. return self._compare(other, operator.__lt__)
  16. def __le__(self, other):
  17. return self._compare(other, operator.__le__)
  18. def __gt__(self, other):
  19. return self._compare(other, operator.__gt__)
  20. def __ge__(self, other):
  21. return self._compare(other, operator.__ge__)
  22. def __eq__(self, other):
  23. return self._compare(other, operator.__eq__)
  24. def __ne__(self, other):
  25. return self._compare(other, operator.__ne__)
  26. def _compare(self, other, method):
  27. if not isinstance(other, self._defining_class):
  28. return NotImplemented
  29. return method(self._compare_key, other._compare_key)