python / python/mypy

Type aliases inside dataclass definitions are not supported at runtime inside of if TYPE_CHECKING

Open
#19,706 1 comment 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

Mypy produces a "Type aliases inside dataclass definitions are not supported at runtime" even for code inside of if TYPE_CHECKING: blocks, which are not going to be executed at runtime. This error is correct outside of if TYPE_CHECKING:. Furthermore, wrapping TypeAlias in a ClassVar to avoid the error satisfies mypy, but the resulting type alias becomes Any.

To Reproduce

from dataclasses import dataclass
from typing import TYPE_CHECKING, ClassVar, TypeAlias, assert_type

if TYPE_CHECKING:
    @dataclass
    class DC:
        T: TypeAlias = int

@dataclass
class DC2:
    T: ClassVar[TypeAlias] = int

def test(x1: DC.T, x2: DC2.T) -> None:
    assert_type(x1, int)
    assert_type(x2, int)

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

Expected Behavior

At least one of these should work without errors. Currently, DC generates a mypy error, but produces a working type alias. DC2 does not generate any errors, but DC2.T is Any instead of int.

Actual Behavior

main.py:7: error: Type aliases inside dataclass definitions are not supported at runtime  [misc]
main.py:15: error: Expression is of type "Any", not "int"  [assert-type]

Your Environment

  • Mypy version used: 1.17.1
  • Python version used: 3.12

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 provided dataclass reproducer in mypy-play using Python 3.12 and mypy 1.17.1, then inspect the type-alias handling that emits the dataclass runtime error and resolves DC2.T. Done means at least one form type-checks without errors and both assert_type calls infer int.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
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.