Skip to content

False positive: Final dataclass field with type variable #22396

Closed as duplicate

Description

@aatle

Bug Report

When using a dataclass with a field defined using Final and containing a type variable, mypy incorrectly errors because it infers the field as a class variable.

To Reproduce

from dataclasses import dataclass
from typing import Final

@dataclass
class Wrapper[T]:
    obj: Final[T]

https://gist.github.com/mypy-play/edaf1efd9e1fec0e7b89e68b17ffae6e

Expected Behavior

No errors, the check does not apply to dataclasses.

Actual Behavior

main.py:6: error: Final name declared in class body cannot depend on type variables  [misc]
Found 1 error in 1 file (checked 1 source file)

Note: mypy does correctly infer that the field is a readonly generic instance attribute, but this is a separate, specific error that should exempt dataclasses.
Simply suppressing the specific misc error leads to desired behavior.

Your Environment

  • Mypy version used: 2.4.1
  • Mypy command-line flags: N/A
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: 3.12

Activity

  1. added
    bugmypy got something wrong
    on Nov 7, 2026
  2. changed the title [-]False positive: Final dataclass field[/-] [+]False positive: Final dataclass field with type variable[/+] on Nov 7, 2026
  3. nilayp-codes commented on Nov 8, 2026

    @nilayp-codes

    I’d like to work on this. The error comes from the DEPENDENT_FINAL_IN_CLASS_BODY check in TypeChecker.visit_assignment_stmt (mypy/checker.py), which doesn’t account for dataclass fields. Those are instance attributes, and the dataclass plugin already allows bare Final[...] fields. I’m planning to skip the check for classes processed by the dataclass plugin and add a test case to check-dataclasses.test.

  4. ilevkivskyi commented on Nov 8, 2026

    @ilevkivskyi
    Member

    This is essentially a duplicate of #21637

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions