False positive for `Final` attributes using typevars in dataclasses
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
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
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne damit, den Python-Reproducer aus dem Issue auszuführen, und vergleiche die im Update beschriebenen Fälle mit dataclass und ohne dataclass. Verfolge, wie mypy Final-Annotationen validiert, an denen Typparameter beteiligt sind; abgeschlossen ist es, wenn die Fälle mit Instanzattributen keinen Fehler erzeugen, während Klassenattribute weiterhin korrekt abgelehnt werden.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- compilers, devtools
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Ruhig
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 48/100