False positive for `Final` attributes using typevars in dataclasses
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Update: The false positive happens for non-dataclasses as well; see https://github.com/python/mypy/issues/21637#issuecomment-4806794052.
Bug Report
In a dataclass, annotating an instance attribute with a Final that depends on a type variable gives a false positive Final name declared in class body cannot depend on type variables [misc] error.
I think that this should be allowed for instance attributes (but not class attributes). Per the spec:
A
Finaldataclass field initialized in the class body is not a class attribute unless explicitly annotated withClassVar.
Related to #5608 and #21334.
To Reproduce
from dataclasses import dataclass
from typing import Final
from typing import Generic
from typing import TypeVar
T = TypeVar("T")
@dataclass(frozen=True)
class A(Generic[T]):
value: Final[T] # error: Final name declared in class body cannot depend on type variables [misc]
@dataclass(frozen=True)
class B(Generic[T]):
value: T
(https://mypy-play.net/?mypy=2.1.0&python=3.14&gist=996c4b8d68e8b57e292b49a834f4ac24)
Expected Behavior
No error.
Actual Behavior
main.py:11: error: Final name declared in class body cannot depend on type variables [misc]
Your Environment
- Mypy version used: 2.1.0
- Mypy command-line flags: none for reproducer
- Mypy configuration options from
mypy.ini(and other config files): none for reproducer - Python version used: 3.14
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 Python reproducer from the issue and compare the dataclass and non-dataclass cases described in the update. Trace how mypy validates Final annotations involving type variables; done means the instance-attribute cases produce no error while class attributes remain correctly rejected.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers, devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 48/100