models.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. __slots__ = ['_compare_key', '_defining_class']
  10. def __init__(self, key, defining_class):
  11. self._compare_key = key
  12. self._defining_class = defining_class
  13. def __hash__(self):
  14. return hash(self._compare_key)
  15. def __lt__(self, other):
  16. return self._compare(other, operator.__lt__)
  17. def __le__(self, other):
  18. return self._compare(other, operator.__le__)
  19. def __gt__(self, other):
  20. return self._compare(other, operator.__gt__)
  21. def __ge__(self, other):
  22. return self._compare(other, operator.__ge__)
  23. def __eq__(self, other):
  24. return self._compare(other, operator.__eq__)
  25. def __ne__(self, other):
  26. return self._compare(other, operator.__ne__)
  27. def _compare(self, other, method):
  28. if not isinstance(other, self._defining_class):
  29. return NotImplemented
  30. return method(self._compare_key, other._compare_key)