Skip to content

Error inferring typevar on generic classes #18706

Closed
@alfred82santa

Description

@alfred82santa

Bug Report

The inferred type of methods of a generic class are not bounded to typevar value on descendant classes.

To Reproduce

from typing import Iterator, Generic, TypeVar

T = TypeVar("T", str, int)

class Parent(Generic[T]):

    @classmethod
    def method_1(cls, value: T) -> T:
        return 2*value
        
    def method_2(self, value: T) -> T:
        return 2*value
        
class ChildInt(Parent[int]):
    pass

instance = ChildInt()

reveal_type(instance.method_1)  # Revealed type is "def (value: builtins.int) -> builtins.int"
reveal_type(ChildInt.method_1)  # Revealed type is "def (value: builtins.int) -> builtins.int"

reveal_type(instance.method_2)  # Revealed type is "def (value: builtins.int) -> builtins.int"
reveal_type(ChildInt.method_2)  # Revealed type is "def (self: __main__.Parent[T`1], value: T`1) -> T`1"

https://mypy-play.net/?mypy=latest&python=3.12&gist=7ce2739ccc2b43f37187d54dcdd5f923

Expected Behavior

reveal_type(ChildInt.method_2)  # Revealed type is "def (self: __main__.ChildInt, value: builtins.int) -> builtins.int"

This soulution could be acceptable, as well:

reveal_type(ChildInt.method_2)  # Revealed type is "def (self: __main__.Parent[builtins.int], value: builtins.int) -> builtins.int"

Actual Behavior

reveal_type(ChildInt.method_2)  # Revealed type is "def (self: __main__.Parent[T`1], value: T`1) -> T`1"

Your Environment

  • Mypy version used: 1.15
  • Mypy command-line flags: no flags
  • Mypy configuration options from mypy.ini (and other config files): no config
  • Python version used: 3.13

Releated issues

#15658

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