python / python/mypy

False negative when accessing dataclass instance attribute as class attribute

Open
#17,711 2 comments 0 reactions 1 assignee View on GitHub

@sobolevn is already working on this.

Since Aug 27, 2024.

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

Description

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

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.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.