Skip to content

Covariance is not inferred for NamedTuple and frozen Dataclasses #17623

Open
@nielsbuwen

Description

@nielsbuwen

The new experimental feature NewGenericSyntax (#15238) should infer the variance of type variables. For attributes in NamedTuple and frozen dataclass the variance is inferred as "invariant" when it should be "covariant"
(A clear and concise description of what the bug is.)

To Reproduce

I defined a generic NamedTuple and frozen dataclass with one member of type T. The classes should be covariant in T. So converting from Container[int] to Container[int |None] should be no problem.

playground link

Expected Behavior

mypy should accept all four variants of the type def

Actual Behavior

For Sequence and tuple[T, ...] it correctly accepts the function definition.

But for NamedTuple and dataclass it says

Incompatible return value type (got "XY[int]", expected "XY[int | None]") [return-value]

It looks like mypy does not think that the NamedTuple and dataclass are not covariant in T.

Your Environment

  • Mypy Playgrond
  • Python: 3.12
  • with or without --strict
  • --enable-incomplete-feature=NewGenericSyntax
  • versions tried: 1.11.1 and master

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