Skip to content

[mypyc] Allow class with only non-eq comparison methods to be hashable - #22347

Merged
JukkaL merged 1 commit into
masterfrom
mypyc-bulkfix-1173-ordering-hash
Nov 2, 2026
Merged

JukkaL merged 1 commit into
masterfrom
mypyc-bulkfix-1173-ordering-hash

Conversation

@JukkaL

@JukkaL JukkaL commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator

Fixes mypyc/mypyc#1173.

A native class that defines __lt__ (or another comparison method other than __eq__) without __hash__ was unhashable when compiled:

class C:
    def __lt__(self, other: C) -> bool:
        return True

hash(C())  # TypeError: unhashable type: 'C'

Only defining __eq__ should make a class unhashable. CPython doesn't inherit tp_hash if a type defines tp_richcompare, and this happens for all comparison methods. Now we explicitly use the default object hash function in this case, unless __eq__ is also defined.

…shable

Fixes mypyc/mypyc#1173.

A native class that defines `__lt__` (or another comparison method other
than `__eq__`) without `__hash__` was unhashable when compiled:

```python
class C:
    def __lt__(self, other: C) -> bool:
        return True

hash(C())  # TypeError: unhashable type: 'C'
```

Only defining `__eq__` should make a class unhashable. CPython doesn't
inherit `tp_hash` if a type defines `tp_richcompare`, and this happens
for all comparison methods. Now we explicitly use the default `object`
hash function in this case, unless `__eq__` is also defined.
@JukkaL
JukkaL merged commit caba63e into master Nov 2, 2026
18 checks passed
@JukkaL
JukkaL deleted the mypyc-bulkfix-1173-ordering-hash branch November 2, 2026 12:03
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.

Compiled native classes become unhashable if ordered comparison methods are defined

2 participants