← 输入框|github.com|刷新
Skip to content

Equal Version objects can have different hashes (zero-padded prerelease) #515

Closed

Description

@SonicHedghog

Which version of Python is the problem with?

3.13

What semver version are you using?

3.1.2 (also reproduced on master)

What OS are you using? (Add more in the Environment section)

Windows (platform-independent)

Situation

Two Version objects that compare equal can have different hashes when a numeric
prerelease identifier is zero-padded. This violates Python's requirement that
a == b implies hash(a) == hash(b), breaking set/dict behavior even when
only Version objects are involved.

This is related to #506 (cross-type hash contract), but is a distinct, same-type
violation: no str/tuple comparison is involved, so it can be fixed without
touching documented cross-type equality.

How to reproduce

from semver import Version

a = Version(1, 2, 3, prerelease="007")
b = Version(1, 2, 3, prerelease="7")

print(a == b)              # True
print(hash(a) == hash(b))  # False  <-- inconsistent

print({a, b})              # {1.2.3-007, 1.2.3-7}: two "equal" items in one set
print(b in {a})            # False, despite a == b
print({a: "x"}.get(b))     # None

Output:

True
False
{Version(major=1, minor=2, patch=3, prerelease='007', build=None),
 Version(major=1, minor=2, patch=3, prerelease='7', build=None)}
False
None

Root cause: __eq__ -> compare() -> _nat_cmp normalizes leading zeros
(identifier.lstrip("0") or "0"), so "007" and "7" get the same comparison
key (0, 1, "7"). __hash__ hashes self.to_tuple()[:4], which keeps the raw
prerelease string, so the hashes differ.

The state is only reachable because Version.__init__ accepts
prerelease="007" unvalidated, while Version.parse("1.2.3-007") correctly
raises ValueError (SemVer 2.0.0 spec section 9 forbids leading zeros in
numeric identifiers).

Expected behavior

hash(a) == hash(b) whenever a == b; {a, b} has length 1; dict lookups hit.

Possible fixes, either resolves it:

  1. Normalize the prerelease inside __hash__ using the same prerelease_key
    logic as _nat_cmp.
  2. Reject leading-zero numeric prerelease identifiers in __init__, matching
    parse's strictness (breaking change).

Environment

semver 3.1.2 from PyPI, CPython 3.13 on Windows/amd64; __hash__ and
_nat_cmp are identical on current master.

Activity

  1. tomschr commented on Nov 17, 2026

    @tomschr
    Member

    Thank you @SonicHedghog for your issue. 👍❤️

    This issue was already fixed in #507 and released in version 3.1.2. Therefore, I'm closing this issue as duplicate.

    In case you think this is a different issue, just reopen it and we can discuss it. Many thanks!

  2. tomschr commented on Nov 17, 2026

    @tomschr
    Member

    Oh wait! Sorry, it seems, I was too quick to close it. 😂 I reopen it.

    Still, we need to discuss the relationship of #507.

  3. SonicHedghog commented on Nov 17, 2026

    @SonicHedghog
    ContributorAuthor

    No worries. I filed the issue originally and saw of the similar issues happening right now so I almost closed it myself 😅 It does look like the hashing function only considers the original input of the constructor, not the normalized input. The equals operator does use the normalized input however.

  4. SonicHedghog commented on Nov 17, 2026

    @SonicHedghog
    ContributorAuthor

    Some history on how this inconsistency came about.

    Tracing with git log -S on semver.py / src/semver/version.py:

    • Pre-2017: _nat_cmp converted numeric identifiers with int(text), so "007" and "7" already compared equal — but VersionInfo had no __hash__, so there was no contract to violate.
    • e1a633c (2017-01-16, first released in 2.7.4): a comparison fix introduced a tiebreak of cmp(len(a), len(b)) — the lengths of the raw prerelease strings. '007' (3) vs '7' (1) compared unequal, so the equal-hash requirement was moot.
    • 3dfd54f (2018-05-15, PR Implements __str__ and __hash__ #75, first in 2.8.0): __hash__ added as hash(tuple(self)), hashing the raw prerelease string. Still consistent, since equality said unequal.
    • 0f30183 (2024-10-17, "Improve private _nat_cmp() method", first in 3.0.3, released 2025-01-18): the tiebreak was corrected to compare identifier counts (len(a_parts) vs len(b_parts)), matching SemVer §11.4. That made "007" compare equal to "7" — but __hash__ still hashes the raw string, so the contract violation begins here.

    Verified against released wheels:

    semver 3.0.2:  a == b → False   (consistent, though arguably wrong precedence)
    semver 3.0.3:  a == b → True, hash(a) != hash(b)   (violation begins)
    semver 3.1.2:  same as 3.0.3
    

    So the inconsistency has shipped in every release since 3.0.3 (Jan 2025). It also means fixing __hash__ to normalize the prerelease (or validating leading zeros in __init__) is independent of the cross-type deprecation work in #507 — happy to put together a PR for either approach if you have a preference.

  5. tomschr commented on Nov 17, 2026

    @tomschr
    Member

    Thank you @SonicHedghog for your help and the history. Super helpful! 👍

    If you like to work on that, go head! I'm currently a bit under pressure with other topics, so feel free to open a pull request. I'll review it.

    Many thanks for the issue!

  6. SonicHedghog commented on Nov 17, 2026

    @SonicHedghog
    ContributorAuthor

    The initial work is done. Just need you to look it over. I can also make any suggested comment changes if they need to be made.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    SIze

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions