diff --git a/src/pendulum/tz/timezone.py b/src/pendulum/tz/timezone.py index e46e13df1..ffc3c1304 100644 --- a/src/pendulum/tz/timezone.py +++ b/src/pendulum/tz/timezone.py @@ -69,6 +69,9 @@ def __new__(cls, key: str) -> Self: def __eq__(self, other: object) -> bool: return isinstance(other, Timezone) and self.key == other.key + def __hash__(self) -> int: + return hash(self.key) + @property def name(self) -> str: return self.key @@ -178,6 +181,9 @@ def __init__(self, offset: int, name: str | None = None) -> None: def __eq__(self, other: object) -> bool: return isinstance(other, FixedTimezone) and self._offset == other._offset + def __hash__(self) -> int: + return hash(self._offset) + @property def name(self) -> str: return self._name diff --git a/tests/tz/test_timezone.py b/tests/tz/test_timezone.py index 3f0901681..cef378419 100644 --- a/tests/tz/test_timezone.py +++ b/tests/tz/test_timezone.py @@ -47,6 +47,18 @@ def test_equality(): assert timezone("Europe/Paris") != timezone("Europe/Berlin") +def test_hashable(): + # Timezones are hashable and can be used as dict keys / set members. + # __eq__ and __hash__ must stay consistent: equal timezones hash equally. + assert hash(timezone("Europe/Paris")) == hash(timezone("Europe/Paris")) + assert timezone("Europe/Paris") in {timezone("Europe/Paris")} + assert len({timezone("Europe/Paris"), timezone("Europe/Berlin")}) == 2 + + assert hash(fixed_timezone(3600)) == hash(fixed_timezone(3600)) + assert fixed_timezone(3600) in {fixed_timezone(3600)} + assert len({fixed_timezone(3600), fixed_timezone(7200)}) == 2 + + def test_skipped_time_with_pre_rule(): dt = datetime(2013, 3, 31, 2, 30, 45, 123456, fold=0) tz = timezone("Europe/Paris")