python / python/mypy

dataclasses with generated __hash__ subclassing Hashable are considered abstract

Aperta
#18,962 2 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

bug topic-dataclasses
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

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

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia eseguendo la riproduzione collegata di mypy-play con Python 3.12 e mypy 1.15.0. Traccia come vengono trattate le dataclasses con frozen=True o unsafe_hash=True quando una sottoclasse richiede hash, quindi aggiungi una copertura di regressione che dimostri che B(1) viene accettato senza un errore di classe astratta.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
devtools
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Specificata chiaramente
Idoneità per principianti
45/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.