python / python/mypy

ClassVar[TypeAlias] in dataclass-like classes becomes Any

Open
#17,031 5 comments 2 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

When defining a type alias within a dataclass (or attrs) class, it has to be marked as ClassVar[^1] which causes the field to be treated as Any.

This bug has been already reported in https://github.com/python/mypy/issues/9238#issuecomment-1089065588 but never followed up.

To Reproduce

from dataclasses import dataclass
from typing import ClassVar, TypeAlias


@dataclass
class Namespace:
    Alias: ClassVar[TypeAlias] = int
    
reveal_type(Namespace.Alias)

https://mypy-play.net/?mypy=latest&python=3.12&gist=e66e903f3b055fa8433707a5e8b99ebc

Expected Behavior

main.py:16: note: Revealed type is "int"

Actual Behavior

main.py:16: note: Revealed type is "Any"

Your Environment

See the playground. Python 3.12 on Mypy 1.9.0.

[^1]: The attrs plugin crashes with an assertion error if this is forgotten, but that's a bug for another day.

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 by running the provided Python reproducer with mypy 1.9.0 and compare the revealed type with the expected int. Trace how ClassVar[TypeAlias] is handled in dataclass-like classes, then add or update coverage so the revealed type is no longer Any; the attrs-plugin assertion is explicitly out of scope.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.