python / python/mypy

Mypy treating type of final class variable in dataclass as Any

Open
#21,906 6 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

from dataclasses import dataclass
from typing import ClassVar, Final, reveal_type

class Bar: pass

@dataclass
class Foo:
    cv: ClassVar[Final[dict[type[Bar], Foo]]] = {}

reveal_type(Foo.cv)
$ mypy test.py
test.py:10: note: Revealed type is "Any"
Success: no issues found in 1 source file

The correct type of Foo.cv is builtins.dict[type[Bar], Foo].

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.14&gist=2fad4ef5fded90ecaeb0f1d1e59d882a

Expected Behavior

reveal_type should report the correct type for the class variable.

Actual Behavior

reveal_type showed incorrect type (Any).

Your Environment

  • Fedora 44
  • python3-mypy-1.18.2-4.fc44.noarch (reproducible with Mypy 2.3.1)
  • python3-3.14.6-1.fc44.x86_64
  • No config files used

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the minimal reproducer in the issue or its mypy-play link, then trace how dataclass handling processes ClassVar[Final[...]] while running reveal_type. Done means mypy reports dict[type[Bar], Foo] for Foo.cv and the behavior is covered by a regression test.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
68/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.