models.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. """Utilities for defining models
  2. """
  3. import operator
  4. from typing import Any, Callable, Type
  5. class KeyBasedCompareMixin:
  6. """Provides comparison capabilities that is based on a key"""
  7. __slots__ = ["_compare_key", "_defining_class"]
  8. def __init__(self, key, defining_class):
  9. # type: (Any, Type[KeyBasedCompareMixin]) -> None
  10. self._compare_key = key
  11. self._defining_class = defining_class
  12. def __hash__(self):
  13. # type: () -> int
  14. return hash(self._compare_key)
  15. def __lt__(self, other):
  16. # type: (Any) -> bool
  17. return self._compare(other, operator.__lt__)
  18. def __le__(self, other):
  19. # type: (Any) -> bool
  20. return self._compare(other, operator.__le__)
  21. def __gt__(self, other):
  22. # type: (Any) -> bool
  23. return self._compare(other, operator.__gt__)
  24. def __ge__(self, other):
  25. # type: (Any) -> bool
  26. return self._compare(other, operator.__ge__)
  27. def __eq__(self, other):
  28. # type: (Any) -> bool
  29. return self._compare(other, operator.__eq__)
  30. def _compare(self, other, method):
  31. # type: (Any, Callable[[Any, Any], bool]) -> bool
  32. if not isinstance(other, self._defining_class):
  33. return NotImplemented
  34. return method(self._compare_key, other._compare_key)