python / python/cpython

`isinstance(obj, Hashable)` raises `TypeError` when both `obj` and `type(obj)` are unhashable

未關閉
#129,589 2 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

extension-modules type-bug
主要語言
Python
星號
77.2k
分支
36k
PR 合併指標
PR 指標待擷取

描述

Bug report

Bug description:

Assumption: isinstance(anything, any_type) should never raise.

The problem appears to be in _abc.c function _abc__abc_subclasscheck_impl (known at runtime as _abc._abc_subclasscheck()), which reads (in part):

    /* 1. Check cache. */
    incache = _in_weak_set(impl->_abc_cache, subclass);

The implementation assumes subclass is hashable. That's almost always true of classes, but not guaranteed.

Reproduction case:

from __future__ import annotations
from collections.abc import Hashable

class UnhashableMeta(type):
    def __eq__(self, other: object) -> bool:
        return super().__eq__(other)

class UnhashableClass(metaclass=UnhashableMeta):
    def __eq__(self, other: object) -> bool:
        return super().__eq__(other)

# any non-hashable instance of a non-hashable class
#         ┌────────┴────────┐
isinstance(UnhashableClass(), Hashable)

Traceback for (cpython) Python 3.13.1:

Traceback (most recent call last):
  File "<frozen runpy>", line 198, in _run_module_as_main
  File "<frozen runpy>", line 88, in _run_code
  File ".../bug.py", line 14, in <module>
    isinstance(UnhashableClass(), Hashable)
    ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen abc>", line 119, in __instancecheck__
  File "<frozen abc>", line 123, in __subclasscheck__
TypeError: unhashable type: 'UnhashableMeta'

Tracebacks are nearly identical with Python 3.8, 3.9, 3.10, 3.11, and 3.12, as well as Python 3.14.0a4.

CPython versions tested on:

3.13, 3.12, 3.11, 3.10, 3.9, 3.14

Operating systems tested on:

macOS

貢獻指南

開啟貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

研究方向

開啟 Modules/_abc.c,從 _abc__abc_subclasscheck_impl 開始,具體檢查 issue 中描述的 _in_weak_set 呼叫。在 CPython 上執行提供的 UnhashableMeta 和 UnhashableClass reproduction,然後驗證 isinstance(UnhashableClass(), Hashable) 不再引發例外,並確認該 regression 已由適當的 test 覆蓋。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
c, python
領域
backend
Issue 類型
缺陷
難度
4/5
預估耗時
3-5 天
活躍度
停滯
描述清晰度
描述清楚
新手友好度
45/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。