Repository navigation
Fix hash contract: equal Versions must hash equal (#515) - #516
Conversation
Version.__hash__ hashed to_tuple()[:4], keeping the raw prerelease
string, while _nat_cmp normalizes numeric identifiers for comparison.
A zero-padded prerelease (e.g. "007") compared equal to its normalized
form ("7") but hashed differently, so equal Versions behaved as
distinct set/dict keys — a contract violation live since 3.0.3.
Hoist the prerelease normalization out of _nat_cmp into a shared
_prerelease_key helper and build the hash from the normalized key, so
comparison and hashing cannot drift again. Empty/absent prerelease
maps to a canonical key.
Adds parametrized coverage for zero-padded, multi-identifier,
non-ASCII-digit, and empty-prerelease equalities (set/dict semantics
included), plus a changelog fragment.
Fixes python-semver#515
|
The two `action_required` checks are the first-time-contributor workflow gate (zero jobs ran) — they'll need a maintainer's "Approve and run." For reference: `pytest tests` passes locally on this branch (531 passed, 1 skipped, Python 3.13) and `ruff check` adds no new findings vs HEAD. |
tomschr
left a comment
There was a problem hiding this comment.
Thank you @SonicHedghog for your PR! Much appreciated! 👍
I guess, I found an edge case. Could you take a look? Let me know what you think. 😊
| return (1, 0, identifier) | ||
| @staticmethod | ||
| def _prerelease_key(identifier: str) -> tuple[int, int, str]: | ||
| if not identifier.isdigit(): |
There was a problem hiding this comment.
I think the .isdigit() is wrong here. It allows too much. For example:
>>> identifier = "²"
>>> identifier.isdigit()
True
>>> identifier.isdecimal()
FalseOnly regular decimals should be allowed, not superscripts like "²". That numeric which will make int("²") fail later.
| if not identifier.isdigit(): | |
| if not identifier.isdecimal(): |
There was a problem hiding this comment.
Great catch — you're absolutely right, isdigit() accepts superscripts and other non-decimal digits that int() chokes on. Switched to isdecimal() in 9df3f6a.
One side effect worth flagging: this changed the behavior that #488 locked in — compare() used to raise ValueError eagerly for these identifiers, but now ² sorts lexically as an alphanumeric identifier instead. I updated test_should_preserve_eager_invalid_unicode_digit_error accordingly (now test_should_compare_superscript_digit_as_alphanumeric), but let me know if you'd rather keep the error path.
There was a problem hiding this comment.
Thanks for the hint. I think that's fine. 👍 If not, I hope people will come up with additional issue or PRs. 😆
| if not identifier.isascii(): | ||
| identifier = str(int(identifier)) | ||
| if not identifier.isascii(): | ||
| identifier = str(int(identifier)) |
There was a problem hiding this comment.
Use Unicode decimal-category digits and normalize each character individually. This avoids treating superscript "²" as numeric even though int("²") fails, while preserving Arabic-Indic digit equivalence and avoiding Python’s integer-string length limit.
You may need to add import unicodedata in the header:
| identifier = str(int(identifier)) | |
| identifier = "".join( | |
| str(unicodedata.decimal(character)) for character in identifier | |
| ) |
There was a problem hiding this comment.
Applied — per-character unicodedata.decimal normalization is a nice touch, handles Arabic-Indic and fullwidth digits without ever hitting int() or the integer-string length limit. Thanks!
str.isdigit() accepts superscripts like "²" for which int() fails, and since __hash__ now reaches _prerelease_key, the crash became reachable from hashing too. Switch to str.isdecimal() and normalize each character via unicodedata.decimal, which also avoids Python's integer-string length limit and removes int() from prerelease comparison entirely. Deliberately supersedes the eager ValueError introduced for these identifiers in python-semver#488: a prerelease like "²" now compares lexically as an alphanumeric identifier instead of raising. Test updated accordingly.
|
Fixed in 9df3f6a — |
|
Heads-up on the red check: it's not the change — `tox-gh-actions` crashes at import with `ImportError: cannot import name '_PLACE_HOLDER' from 'tox.config.of_type'`. tox 4.67.14/4.67.15 shipped yesterday (~22:30 UTC), right between the green run on the previous commit and this one, and the workflow installs it unpinned. This will hit every run repo-wide until pinned (e.g. `tox<4.67.14`) or tox-gh-actions catches up. Local suite is still green on this branch (532 passed). |
Thanks, great catch! 👍 I will look into it. 👀 |
|
Ok, I pushed commit 53e92bd, let's see if that works. 🤞 |
|
Almost — the pin didn't reach the matrix jobs. The workflow installs tox a second time, unpinned, after sync: |
|
Looks like I was able to use the pinned tox version.🎉 If you would like to have a look, let me know if that looks good. Maybe I should better separate your issue from the infrastructure part.🤔 |
|
Infra change looks good to me — `uv sync --locked --group gh-action` makes both jobs resolve from the lockfile, and `tox<4.67.14` in the `test` extra is what actually constrains it now. Green matrix confirms it. 🎉 |
Great! 🎉 The clean way would be to have a separate PR for the infra structure part. However, I'm a bit lazy today 😹 so I think we combine it in this one PR. 😉😇 Once the CI is green, I will merge it to the master branch. Many thanks for your contribution! ❤️ |
|
Works for me — combined is fine since it all lands together anyway. Thanks for the review and for sorting the CI bits! 🙌 |
Summary
Version.__hash__hashedto_tuple()[:4]— the raw prerelease string — whilecompare()/_nat_cmpnormalizes numeric identifiers before comparing. A zero-padded prerelease ("007") compares equal to its normalized form ("7") but hashed differently, so equalVersionobjects behaved as distinct keys inset/dict— a violation of Python's__eq__/__hash__contract, live since 3.0.3 (commit 0f30183 fixed the_nat_cmptiebreak without updating__hash__).Fix
_nat_cmpinto a shared_prerelease_keystatic method — comparison and hashing now consume the same normalization and cannot drift again.__hash__builds its key from the normalized identifier keys; a falsy (None/"") prerelease maps to a canonical empty key soVersion(1,2,3)andVersion(1,2,3,"")hash identically (they compare equal).Non-breaking: changes no public behavior except restoring the
__eq__/__hash__contract. Alternative rejected: validating leading zeros in__init__would fix the reachable state but is a breaking change (tracked as a possible semver-4 item).Test plan
test_equal_prereleases_have_equal_hashes— 4 cases: zero-padded numeric, zero-padded mid-identifier, non-ASCII digit (٧), empty-vs-absent prerelease; each asserts equality, hash equality, set dedup, and dict lookup.pytest tests), 100% coverage onsrc/semver/version.pymaintained.ruff checkon changed file adds zero new findings vs HEAD.{Version(1,2,3,'007'), Version(1,2,3,'7')}now has length 1;{a: 'v'}.get(b)hits.Fixes #515