python / python/mypy

dataclasses with generated __hash__ subclassing Hashable are considered abstract

オープン
#18,962 コメント 2 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

bug topic-dataclasses
主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

Bug Report

Dataclasses that are hashable (e.g. frozen=True) that extend any abc/protocol requiring __hash__ (e.g. collections.abc.Hashable) is considered abstract and gives an error when trying to be instantiated.

In addition to frozen=True/Hashable, you also get the same error with unsafe_hash=True, as well as using your own protocol or abc that requires __hash__.

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.12&gist=390504f01055e489b12b388eec1de256

from dataclasses import dataclass
from collections.abc import Hashable


@dataclass(frozen=True)
class A:
    a: int


@dataclass(frozen=True)
class B(Hashable):
    a: int


a: Hashable = A(1)  # ok
b = B(1)  # error: Cannot instantiate abstract class "A" with abstract attribute "__hash__"  [abstract]

print(hash(b))  # prints -6644214454873602895

Expected Behavior

This works at runtime -- running the script prints the hash, demonstrating that it has __hash__ defined.

Actual Behavior

main.py:16: error: Cannot instantiate abstract class "B" with abstract attribute "__hash__"  [abstract]

Your Environment

  • Mypy version used: 1.15.0
  • Mypy command-line flags: N/A
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: 3.12

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

Python 3.12 と mypy 1.15.0 で、リンクされた mypy-play の再現例を実行することから始めます。次に、サブクラスが hash を必要とする場合に、frozen=True または unsafe_hash=True を持つ dataclasses がどのように扱われるかを追跡し、B(1) が抽象クラスエラーなしで受け入れられることを示す回帰テストを追加します。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
devtools
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
明確に書かれている
初心者へのやさしさ
45/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。