Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion src/pendulum/tz/timezone.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,18 @@ def _from_pickled_file(cls, data: bytes, key: str | None) -> Self:
return cls.from_file(io.BytesIO(data), key=key)

def __eq__(self, other: object) -> bool:
return isinstance(other, Timezone) and self.key == other.key
if not isinstance(other, Timezone):
return False
if self.key is None or other.key is None:
# Keyless instances (built via from_file) have no name to compare,
# so fall back to the raw TZif bytes: two different zones must not
# compare equal just because neither has a key.
return self.key == other.key and self._file_bytes == other._file_bytes
return self.key == other.key

def __hash__(self) -> int:
if self.key is None:
return hash((Timezone, self._file_bytes))
return hash((Timezone, self.key))

@property
Expand Down
45 changes: 45 additions & 0 deletions tests/tz/test_timezone.py
Original file line number Diff line number Diff line change
Expand Up @@ -486,6 +486,51 @@ def _paris_tzif_bytes() -> bytes:
return resources.files("tzdata.zoneinfo").joinpath("Europe", "Paris").read_bytes()


def _new_york_tzif_bytes() -> bytes:
from importlib import resources

return (
resources.files("tzdata.zoneinfo").joinpath("America", "New_York").read_bytes()
)


def test_from_file_timezones_with_different_bytes_are_not_equal():
# Two keyless Timezones built from different zone files must not compare
# equal: before this fix, __eq__ only looked at the key, which is None for
# both, so any two from_file() timezones collapsed into one.
from io import BytesIO

import pendulum.tz.timezone as timezone_module

paris = timezone_module.Timezone.from_file(BytesIO(_paris_tzif_bytes()))
new_york = timezone_module.Timezone.from_file(BytesIO(_new_york_tzif_bytes()))

assert paris.key is None
assert new_york.key is None
assert paris != new_york
assert hash(paris) != hash(new_york)
assert len({paris, new_york}) == 2

# A keyless instance still never equals a named one.
assert paris != timezone_module.Timezone("Europe/Paris")


def test_from_file_timezones_with_same_bytes_are_equal():
from io import BytesIO

import pendulum.tz.timezone as timezone_module

first = timezone_module.Timezone.from_file(BytesIO(_paris_tzif_bytes()))
second = timezone_module.Timezone.from_file(BytesIO(_paris_tzif_bytes()))

assert first == second
assert hash(first) == hash(second)
assert len({first, second}) == 1

# Equality survives a pickle round-trip.
assert pickle.loads(pickle.dumps(first)) == first


def test_from_file_without_a_key_can_be_pickled():
# get_local_timezone()'s last-resort fallback builds a Timezone this same way, with no key.
from io import BytesIO
Expand Down