I want to print class variable `animal_name` for multiple classes. Multiple classes consist of dataclass `Cat` and non-dataclass `Bird`.
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
I want to print class variable animal_name for multiple classes. Multiple classes consist of dataclass Cat and non-dataclass Bird.
Parent class of class Cat and Bird has class variable animal_name.
But mypy raised error.
Details: https://qiita.com/yuji38kwmt/items/29c9163a69dc37917d33
To Reproduce
https://gist.github.com/mypy-play/4e59803f4761dbbf59f6e253ca53d420
https://mypy-play.net/?mypy=latest&python=3.11&gist=4e59803f4761dbbf59f6e253ca53d420
from dataclasses import dataclass
from typing import ClassVar
class Animal:
animal_name: ClassVar[str]
@dataclass
class Cat(Animal):
cat_id: str
animal_name: ClassVar[str] = "cat"
def only_cat_method(self) -> None:
print("only cat method")
class Bird(Animal):
"""Not dataclass"""
animal_name: ClassVar[str] = "bird"
def only_bird_method(self) -> None:
print("only bird method")
for cls in [Cat, Bird]:
print(cls.animal_name)
Expected Behavior
no error
Actual Behavior
The following error occurred.
$ mypy sample.py
sample.py:28: error: "type" has no attribute "animal_name" [attr-defined]
Found 1 error in 1 file (checked 1 source file)
But I create __init__ method to Bird class, error did not occurre.
class Bird(Animal):
"""Not dataclass"""
animal_name: ClassVar[str] = "bird"
def only_bird_method(self) -> None:
print("only bird method")
def __init__(self, foo) -> None:
pass
Your Environment
- Mypy version used: 1.2.0
- Mypy command-line flags: no options
- Mypy configuration options from
mypy.ini(and other config files): no file - Python version used: 3.11.2
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by running the sample.py reproduction from the issue or the linked mypy-play gist with mypy 1.2.0, then trace how the type checker infers the common class type for Cat and Bird and handles dataclass versus non-dataclass classes. Done means the reproduction reports no error for cls.animal_name while preserving the existing behavior for the shown classes.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 35/100