python / python/mypy

Hashing of unhashable objects is not detected

Open
#20,230 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-runtime-semantics
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

False negatives for hashing unhashable objects

To Reproduce

class Unhashable1:
    def __eq__(self, other: object) -> bool:
        return False


class Unhashable2:
    __hash__ = None  


for obj in Unhashable1(), Unhashable2():
    try:
        hash(obj)
    except TypeError:
        pass
    else:
        raise AssertionError(f"{obj} should be unhashable")

    try:
        obj in set()
    except TypeError:
        pass
    else:
        raise AssertionError(f"{obj} should be unhashable")

    try:
        obj in {}
    except TypeError:
        pass
    else:
        raise AssertionError(f"{obj} should be unhashable")

    try:
        s = {obj}  
    except TypeError:
        pass
    else:
        raise AssertionError(f"{obj} should be unhashable")

    try:
        d = {obj: "value"}
    except TypeError:
        pass
    else:
        raise AssertionError(f"{obj} should be unhashable")

Expected Behavior

5 errors to be reported

Actual Behavior

No errors reported (other than the __hash__ = None false positive)

Your Environment

  • Mypy version used: 1.18.2
  • Python version used: 3.12

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the supplied Python reproduction and trace mypy's handling of hashability for membership tests, set literals, and dictionary literals. Confirm the fix by adding or running checks that report errors for both example classes in all five operations.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.