From 2b293727bafa288b832714f251f7b2b3b23e0e67 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Ma=C5=9Blanka?= <piotr.maslanka@henrietta.com.pl> Date: Tue, 5 Mar 2024 19:11:43 +0100 Subject: [PATCH] improve OmniHashableMixin --- satella/coding/structures/mixins/hashable.py | 50 ++++++++------------ 1 file changed, 19 insertions(+), 31 deletions(-) diff --git a/satella/coding/structures/mixins/hashable.py b/satella/coding/structures/mixins/hashable.py index 5ae8fc2a..8472ae79 100644 --- a/satella/coding/structures/mixins/hashable.py +++ b/satella/coding/structures/mixins/hashable.py @@ -1,3 +1,4 @@ +import operator import typing as tp from abc import ABCMeta, abstractmethod @@ -180,40 +181,27 @@ class OmniHashableMixin(metaclass=ABCMeta): """ Note that this will only compare _HASH_FIELDS_TO_USE """ - if not isinstance(other, type(self)): - return False - - if not isinstance(other, OmniHashableMixin): - return super().__eq__(other) - - cmpr_by = self._HASH_FIELDS_TO_USE - try: - if isinstance(cmpr_by, str): - return getattr(self, cmpr_by) == getattr(other, cmpr_by) - - for field_name in self._HASH_FIELDS_TO_USE: - if getattr(self, field_name) != getattr(other, field_name): - return False - return True - except AttributeError: - return False + return _generic_eq(self, other, False, operator.eq, 'eq', ) def __ne__(self, other) -> bool: - if not isinstance(other, type(self)): - return True + return _generic_eq(self, other, True, operator.ne, 'ne') - if not isinstance(other, OmniHashableMixin): - return super().__ne__(other) - cmpr_by = self._HASH_FIELDS_TO_USE +def _generic_eq(self, other, truth, comparator, name): + if not isinstance(other, type(self)): + return truth - try: - if isinstance(cmpr_by, str): - return getattr(self, cmpr_by) != getattr(other, cmpr_by) + if not isinstance(other, OmniHashableMixin): + return getattr(super(), name)(other) - for field_name in cmpr_by: - if getattr(self, field_name) != getattr(other, field_name): - return True - return False - except AttributeError: - return True + cmpr_by = self._HASH_FIELDS_TO_USE + try: + if isinstance(cmpr_by, str): + return comparator(getattr(self, cmpr_by), getattr(other, cmpr_by)) + + for field_name in self._HASH_FIELDS_TO_USE: + if getattr(self, field_name) != getattr(other, field_name): + return truth + return not truth + except AttributeError: + return truth -- GitLab