python / python/mypy

Generic subclass of a generic class, using a constrained TypeVar is mishandled

Open
#17,757 1 comment 1 reaction 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

Bug Report

from typing import Generic, TypeVar

T = TypeVar("T")
N = TypeVar("N", int, float)

class C(Generic[T]):
    def __init__(self, c: T):
        self.c = c

class C2(C[N]):
    def __init__(self, c: N):
        super().__init__(c) # Unexpected error

results in an unexpected

error: Argument 1 to "__init__" of "C" has incompatible type "int"; expected "N"  [arg-type]
error: Argument 1 to "__init__" of "C" has incompatible type "float"; expected "N"  [arg-type]

on the last line of the test file.

Your Environment

Confirmed with mypy 1.11.2 in Python 3.11.9, without any flags; does not seem version-specific.

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 by reproducing the reported snippet with mypy 1.11.2 on Python 3.11.9, without flags, and inspect the handling of the constrained TypeVar N in the generic subclass and super().init call. Done means the example no longer emits the two unexpected arg-type errors while preserving the intended generic type checking.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.