Skip to content

generic dataclass with default (and typevar default) #18812

Open

Description

@asottile-sentry

Bug Report

this is the sameish as #12962 however now that PEP 696 exists I expect this to work

To Reproduce

from typing import Literal
from dataclasses import dataclass

@dataclass
class D[TBool: (Literal[True], Literal[False]) = Literal[True]]:
    val: TBool = True


reveal_type(D())
reveal_type(D(True))
reveal_type(D(False))

Expected Behavior

I expect no errors however

Actual Behavior

t3.py:6: error: Incompatible types in assignment (expression has type "Literal[True]", variable has type "TBool")  [assignment]
t3.py:9: note: Revealed type is "t3.D[Literal[True]]"
t3.py:10: note: Revealed type is "t3.D[Literal[True]]"
t3.py:11: note: Revealed type is "t3.D[Literal[False]]"
Found 1 error in 1 file (checked 1 source file)

(the reveal types are all correct -- mostly just to demonstrate that the idea works)

Your Environment

  • Mypy version used: 1.15.0
  • Mypy command-line flags: n/a
  • Mypy configuration options from mypy.ini (and other config files): n/a
  • Python version used: 3.13.0

Activity

  1. added
    bug
    on Mar 17, 2025
  2. sterliakov commented on Mar 18, 2025

    @sterliakov
    Collaborator

    This is very similar to #3737 but is even more complex (substituting in one signature vs checking the whole class for conformance). As of now, mypy does not support any variables/parameters with concrete defaults annotated with a TypeVar (maybe except for a few local narrowing cases, but those are irrelevant here). You can overcome this with __init__ overloads similar to the function example in #3737, but that would probably defeat the benefits of using a dataclass.

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

    bugtopic-dataclassestopic-pep-696

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions