Skip to content

Fix has_entries() crash with non-sortable dictionary keys#275

Open
gaoflow wants to merge 1 commit into
hamcrest:mainfrom
gaoflow:fix-has-entries-nonsortable-keys-271
Open

Fix has_entries() crash with non-sortable dictionary keys#275
gaoflow wants to merge 1 commit into
hamcrest:mainfrom
gaoflow:fix-has-entries-nonsortable-keys-271

Conversation

@gaoflow

@gaoflow gaoflow commented Jun 25, 2026

Copy link
Copy Markdown

Summary

has_entries() raises TypeError at construction time when the supplied dictionary contains keys that do not support comparison (__lt__). This happens because IsDictContainingEntries.__init__ stores entries as sorted(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

self.value_matchers = sorted(value_matchers.items())  # crashes if keys aren't comparable

The sorted() call was presumably added to produce deterministic output for describe_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() with list() to preserve insertion order without imposing an ordering requirement on keys.

A regression test (testHasEntriesWithNonSortableKeys) is added to isdict_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.

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
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.

has_entries TypeError if keys can't sort

1 participant