Skip to content

Commit 9c72264

Browse files
committed
Make Timezone and FixedTimezone hashable
1 parent d3f44aa commit 9c72264

2 files changed

Lines changed: 20 additions & 0 deletions

File tree

‎src/pendulum/tz/timezone.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,9 @@ def __new__(cls, key: str) -> Self:
6969
def __eq__(self, other: object) -> bool:
7070
return isinstance(other, Timezone) and self.key == other.key
7171

72+
def __hash__(self) -> int:
73+
return hash((Timezone, self.key))
74+
7275
@property
7376
def name(self) -> str:
7477
return self.key
@@ -178,6 +181,9 @@ def __init__(self, offset: int, name: str | None = None) -> None:
178181
def __eq__(self, other: object) -> bool:
179182
return isinstance(other, FixedTimezone) and self._offset == other._offset
180183

184+
def __hash__(self) -> int:
185+
return hash((FixedTimezone, self._offset))
186+
181187
@property
182188
def name(self) -> str:
183189
return self._name

‎tests/tz/test_timezone.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from pendulum.tz import fixed_timezone
1414
from pendulum.tz.exceptions import AmbiguousTime
1515
from pendulum.tz.exceptions import NonExistingTime
16+
from pendulum.tz.timezone import FixedTimezone
1617
from tests.conftest import assert_datetime
1718

1819

@@ -47,6 +48,11 @@ def test_equality():
4748
assert timezone("Europe/Paris") != timezone("Europe/Berlin")
4849

4950

51+
def test_hash():
52+
assert hash(timezone("Europe/Paris")) == hash(timezone("Europe/Paris"))
53+
assert len({timezone("Europe/Paris"), timezone("Europe/Paris")}) == 1
54+
55+
5056
def test_skipped_time_with_pre_rule():
5157
dt = datetime(2013, 3, 31, 2, 30, 45, 123456, fold=0)
5258
tz = timezone("Europe/Paris")
@@ -409,6 +415,14 @@ def test_fixed_equality():
409415
assert fixed_timezone(19800) != fixed_timezone(19801)
410416

411417

418+
def test_fixed_hash():
419+
assert hash(fixed_timezone(19800)) == hash(fixed_timezone(19800))
420+
assert fixed_timezone(19800) == FixedTimezone(19800, name="custom"), (
421+
"Pre-condition: name ignored for FixedTimezone"
422+
)
423+
assert len({fixed_timezone(19800), FixedTimezone(19800, name="custom")}) == 1
424+
425+
412426
def test_just_before_last_transition():
413427
tz = pendulum.timezone("Asia/Shanghai")
414428
dt = datetime(1991, 4, 20, 1, 49, 8, fold=0)

0 commit comments

Comments
 (0)