Skip to content

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

@eltoder

Description

@eltoder

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

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