Skip to content

[mypyc] Fix OverflowError when a native __hash__ returns a large int - #22439

Closed
rheard wants to merge 1 commit into
python:masterfrom
rheard:fix-mypyc-1253
Closed

rheard wants to merge 1 commit into
python:masterfrom
rheard:fix-mypyc-1253

Conversation

@rheard

@rheard rheard commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

Fixes mypyc/mypyc#1253

The tp_hash slot of a native class converted the value returned by __hash__ with CPyTagged_AsSsize_t(), so an int that doesn't fit in Py_hash_t made hash() raise OverflowError. CPython's slot_tp_hash, which a class defined in Python uses, accepts any int and hashes one that doesn't fit again with int.__hash__.

generate_hash_wrapper() now does the same:

  • A short int is still handled inline, with -1 changed to -2 as before.
  • A long int goes through the new CPy_HashFromResult() in generic_ops.c, which does what slot_tp_hash
    does with the result: an int that fits in Py_hash_t is used as is, a larger one is hashed again, and
    anything that isn't an int raises TypeError: __hash__ method should return an integer.
  • Other return types are boxed if needed and passed to CPy_HashFromResult(). With -> Any, a result that
    isn't an int used to raise TypeError: an integer is required. A __hash__ declared to return a native int
    type such as i64 segfaulted (or raised SystemError if it returned 0), because the slot passed the C value
    to PyLong_AsSsize_t() as an object pointer.

The new run test testDundersHashResult covers -> int and -> Any with values that fit in Py_hash_t, -1, values that don't fit, a long int that fits only on 64-bit platforms (2**62), True and results that aren't ints, plus an -> i64 method that returns -1. The expected results are the same on 32-bit platforms.

@rheard rheard closed this Nov 12, 2026
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.

hash() raises OverflowError when a native __hash__ returns a large int

1 participant