Skip to content

fix: distinguish keyless Timezones built from different files in __eq__/__hash__ - #1102

Open
waw666waw666 wants to merge 1 commit into
python-pendulum:masterfrom
waw666waw666:fix/keyless-timezone-equality
Open

waw666waw666 wants to merge 1 commit into
python-pendulum:masterfrom
waw666waw666:fix/keyless-timezone-equality

Conversation

@waw666waw666

Copy link
Copy Markdown

fix: distinguish keyless Timezones built from different files in eq/hash

Why

Timezone.__eq__ and __hash__ only look at the key:

def __eq__(self, other):
    return isinstance(other, Timezone) and self.key == other.key

But instances built via Timezone.from_file() have no key (key is None).
That is exactly what get_local_timezone()'s last-resort fallback builds when
/etc/localtime is a copied file rather than a symlink, and what
_tz_from_env() builds for a TZ file path. So any two keyless timezones
compare equal and hash equal, no matter which zone they actually are:

paris = Timezone.from_file(open('/usr/share/zoneinfo/Europe/Paris', 'rb'))
ny = Timezone.from_file(open('/usr/share/zoneinfo/America/New_York', 'rb'))
paris == ny               # True (wrong)
hash(paris) == hash(ny)   # True (wrong)
len({paris, ny})          # 1 (wrong)

This is the leftover gap next to #1040, which made keyless from_file()
instances picklable by keeping the raw TZif bytes, but never fixed equality
or hashing. The __eq__/__hash__ pair (#502, #1008, #1009, #1019) was
designed for named timezones and never considered keyless ones.

What changed

How it was tested

Added two regression tests in tests/tz/test_timezone.py
(test_from_file_timezones_with_different_bytes_are_not_equal and
test_from_file_timezones_with_same_bytes_are_equal) using the tzdata
package's zoneinfo files, covering inequality, distinct hashes, set size,
same-bytes equality, and equality surviving a pickle round-trip:

pytest tests/tz/test_timezone.py tests/tz/test_local_timezone.py
# 39 passed, 3 skipped (without the fix: 38 passed, 1 failed, 3 skipped)

ruff check and ruff format --check pass on the changed files.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant