mypy icon indicating copy to clipboard operation
mypy copied to clipboard

fix: allow Final[T] instance fields in dataclasses to depend on type variables

Open adhavan18 opened this issue 5 months ago • 1 comments

Summary

Fixes #21637.

Final[T] fields in a @dataclass body are instance attributes, not class attributes (PEP 591 / dataclass spec: "A Final dataclass field initialized in the class body is not a class attribute unless explicitly annotated with ClassVar."). The checker was unconditionally raising Final name declared in class body cannot depend on type variables for any Final[T] in a generic class body.

Before:

from dataclasses import dataclass
from typing import Final, Generic, 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

After: no error (same behaviour as value: T without Final).

Change

In mypy/checker.py, the condition that raises DEPENDENT_FINAL_IN_CLASS_BODY now skips the error when:

  1. the active class has dataclass_tag in its metadata (i.e. it is a dataclass or dataclass-transform class), and
  2. the lvalue is a Var that is not marked is_classvar.

Plain (non-dataclass) classes and explicit ClassVar fields are unaffected.

Tests

Two new test cases in test-data/unit/check-final.test:

  • testFinalDefiningTypevarsDataclassInstanceField — Final[T] instance field in a frozen generic dataclass must not produce an error.
  • testFinalDefiningTypevarsNonDataclassStillErrors — Final[T] in a plain generic class must still produce the error.

All 83 existing check-final tests pass with no regressions.

adhavan18 avatar Jun 24 '26 10:06 adhavan18

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

github-actions[bot] avatar Jun 24 '26 11:06 github-actions[bot]

A quick note on scope, since the discussion in #21637 clarified it:

This PR intentionally handles only the dataclass case. Per @A5rocks and @gschaffner in the issue, the non-dataclass Final[T] class-body case is a separate matter (tracked under #8982), while the dataclass case "needs extra code to support" — which is what this change adds.

Behavior after the fix:

  • value: Final[T] in a @dataclass generic → allowed (it is an instance field, not a class attribute, per the dataclass spec).
  • x: Final[T] = ... in a plain generic class body → still errors (unchanged).
  • ClassVar[Final[T]] → still rejected earlier by the "Final must be the outermost qualifier" check, so the guard here is limited to non-ClassVar dataclass fields.

Both cases are covered by tests in check-final.test, CI is green, and mypy_primer reports no changes across the OSS corpus. Happy to adjust the scoping if a different split is preferred.

adhavan18 avatar Jul 09 '26 07:07 adhavan18

As per our policy we don't accept LLM generated PRs from new contributors.

ilevkivskyi avatar Aug 01 '26 22:08 ilevkivskyi