python / python/mypy

Error with TypeVar with constraints on field initialization

Open
#20,975 0 comments 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

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.

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 minimal Python example in the issue and compare mypy's handling of constrained TypeVar assignments during function bodies with class-level field initialization. Reproduce the differing results from mypy, pyright, and ty, then determine whether class-level initialization should accept C(Y()) for every allowed T and add coverage for the reported cases.

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
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.