Skip to content

False positive for Final attributes using typevars in dataclasses #21637

Description

@gschaffner

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 Final dataclass field initialized in the class body is not a class attribute unless explicitly annotated with ClassVar.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions