models.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  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: Any, defining_class: Type["KeyBasedCompareMixin"]) -> None:
  9. self._compare_key = key
  10. self._defining_class = defining_class
  11. def __hash__(self) -> int:
  12. return hash(self._compare_key)
  13. def __lt__(self, other: Any) -> bool:
  14. return self._compare(other, operator.__lt__)
  15. def __le__(self, other: Any) -> bool:
  16. return self._compare(other, operator.__le__)
  17. def __gt__(self, other: Any) -> bool:
  18. return self._compare(other, operator.__gt__)
  19. def __ge__(self, other: Any) -> bool:
  20. return self._compare(other, operator.__ge__)
  21. def __eq__(self, other: Any) -> bool:
  22. return self._compare(other, operator.__eq__)
  23. def _compare(self, other: Any, method: Callable[[Any, Any], bool]) -> bool:
  24. if not isinstance(other, self._defining_class):
  25. return NotImplemented
  26. return method(self._compare_key, other._compare_key)