Fix has_entries() crash with non-sortable dictionary keys#275
Open
gaoflow wants to merge 1 commit into
Open
Conversation
IsDictContainingEntries stored the key-value pairs as `sorted(value_matchers.items())`, which raises TypeError for keys that do not implement __lt__ (dataclass instances, Enum composites, or any custom object without a natural ordering). Python 3.7+ guarantees dict insertion order, so the sort served no functional purpose. Replace sorted() with list() to preserve insertion order without requiring keys to be comparable. Fixes hamcrest#271
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
has_entries()raisesTypeErrorat construction time when the supplied dictionary contains keys that do not support comparison (__lt__). This happens becauseIsDictContainingEntries.__init__stores entries assorted(value_matchers.items()).Real-world example (from issue #271): keys that are dataclass instances composed with an
Enum— perfectly valid as dict keys (__hash__+__eq__), but not orderable.Root cause
The
sorted()call was presumably added to produce deterministic output fordescribe_to(). Python 3.7+ already preserves dict insertion order, so the sort is redundant and the determinism concern is satisfied by the caller's dict.Fix
Replace
sorted()withlist()to preserve insertion order without imposing an ordering requirement on keys.A regression test (
testHasEntriesWithNonSortableKeys) is added toisdict_containingentries_test.py. All 454 existing tests continue to pass.Fixes #271
This pull request was prepared with the assistance of AI, under my direction and review.