Skip to content

fix(version): set _hash_cache when copying a Version in _TrimmedRelease - #1242

Merged
henryiii merged 1 commit into
pypa:mainfrom
henryiii:fix/trimmed-release-hash-cache
Jul 8, 2026
Merged

henryiii merged 1 commit into
pypa:mainfrom
henryiii:fix/trimmed-release-hash-cache

Conversation

@henryiii

@henryiii henryiii commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Looks like a simple missing line. Not likely to cause issues, but best for correctness.

🤖 AI text below 🤖

Part of #1239

Summary

_TrimmedRelease.__init__ has a fast path (when given an existing Version
object) that copies all internal state slots but omits _hash_cache. Because
__slots__ leaves that slot uninitialized, calling hash() on the result
raises AttributeError:

from packaging.version import _TrimmedRelease, Version
hash(_TrimmedRelease(Version("1.0")))
# AttributeError: '_TrimmedRelease' object has no attribute '_hash_cache'

Version.__hash__ reads self._hash_cache directly (no getattr guard),
so any _TrimmedRelease built via the fast path was broken for hashing.

Fix

Copy _hash_cache from the source Version, wrapped in try/except AttributeError because the source's slot may itself be unset if hash()
was never called on it. Two regression tests cover both cases: a fresh
(never-hashed) source Version and a pre-hashed source Version.

🤖 Generated with Claude Code

The fast path in `_TrimmedRelease.__init__` copied all Version slots from
the source object except `_hash_cache`, leaving that slot uninitialized.
Calling `hash()` on the resulting instance raised `AttributeError` because
`Version.__hash__` reads the slot unconditionally.

The fix copies `_hash_cache` unconditionally, mirroring `_key_cache`;
every Version construction path initializes the slot, so it is always
populated on the source object.  Two regression tests cover both the
fresh-Version and pre-hashed-Version cases.

Assisted-by: ClaudeCode:claude-sonnet-4-6
Assisted-by: ClaudeCode:claude-fable-5
@henryiii
henryiii force-pushed the fix/trimmed-release-hash-cache branch from 7d3841e to 9183e09 Compare June 10, 2026 22:36
@henryiii
henryiii merged commit a33b294 into pypa:main Jul 8, 2026
59 checks passed
@henryiii
henryiii deleted the fix/trimmed-release-hash-cache branch July 8, 2026 01:22
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.

2 participants