python / python/mypy

False negative when accessing dataclass instance attribute as class attribute

Aperta
#17,711 2 commenti 0 reazioni 1 assegnatario Vedi su GitHub

@sobolevn ci sta già lavorando.

Dal 27/8/2024.

bug topic-dataclasses
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Merge medio
1g 18h
PR unite (30g)
54

Descrizione

Apologies if it's a known issue, I searched for some time on the issue tracker, but no luck!

Bug Report

When you access a dataclass instance attribute as a class attribute, it crashes in runtime. However, mypy doesn't complain about it.

To Reproduce

from dataclasses import dataclass

@dataclass
class Cls:
    value: int

print(Cls.value)

https://mypy-play.net/?mypy=master&python=3.12&flags=strict&gist=2c0cec417b726435303ab8b25c07cccf

Expected Behavior

Mypy should complain about the missing attribute (or ideally even suggesting that you may be using instance attribute instead of class attribute if we want a nicer error message)

Actual Behavior

Mypy passes the check. Whereas in runtime we're getting

Traceback (most recent call last):
  File "/tmp/ff.py", line 7, in <module>
    print(Cls.value)
          ^^^^^^^^^
AttributeError: type object 'Cls' has no attribute 'value'

Your Environment

  • Mypy version used: latest stable and latest mastr
  • Mypy command-line flags: nona
  • 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.

Valutazione

Questa issue non è ancora stata valutata.

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.