Skip to content

Error with TypeVar with constraints on field initialization #20975

@thierry-martinez

Description

@thierry-martinez

The following example fails to type-check with mypy and pyright, but succeeds with ty:

from dataclasses import dataclass
from typing import TypeVar, Generic

class X:
    pass

class Y(X):
    pass

T = TypeVar("T", X, Y)

@dataclass
class C(Generic[T]):
    v: T

def f(c: C[T]):
    # no error with mypy and ty
    # pyright reports an error on the argument
    c.v = Y()

    # no error with mypy and ty
    # pyright reports an error on the assignment
    d: C[T] = C(Y())

class M(Generic[T]):
    # no error with ty
    # mypy and pyright report an error on the assignment
    c: C[T] = C(Y())

The constraints on T effectively make Y a lower bound for T, meaning that C(Y()) should be considered a valid C[T] for any allowed T. This seems to be correctly understood by mypy for field assignment and constructor assignment within a function, but not for field initialization at the class level.

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