mypy icon indicating copy to clipboard operation
mypy copied to clipboard

'got "C[T]", expected "C[T]"' with staticmethod

Open comex opened this issue 2 years ago • 1 comments

Bug Report

In the below playground link, mypy gives this error:

main.py:10: error: Incompatible return value type (got "C[T]", expected "C[T]")  [return-value]

I think the program should pass type checking (it does with Pyright), but if there is some problem with it I'm not understanding, at least the error message should be better.

To Reproduce

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

from typing import Generic, TypeVar 
T = TypeVar('T')

class C(Generic[T]):
    @staticmethod
    def c() -> 'C[T]':
        return C()

def f(t: T) -> C[T]:
    return C[T].c()

Your Environment

  • Mypy version used: 1.7.1 on playground
  • Mypy command-line flags: -
  • Mypy configuration options from mypy.ini (and other config files): -
  • Python version used: 3.12

comex avatar Dec 15 '23 21:12 comex

The error message is confusing because the type variable T is actually not the same in f and C. (Technically it is T`-1 and T`1 but mypy does not expose these names.) You can reproduce using two separate type variables as well:

T = TypeVar('T')
S = TypeVar('S')

class C(Generic[T]):
    @staticmethod
    def get() -> T: ...

def func(x: S) -> S:
    return C[S].get()  # E: Incompatible return value type (got "T", expected "S")  [return-value]

Generally you'd use @classmethod for this kind of thing, and mypy handles this edge case correctly:

T = TypeVar('T')

class C(Generic[T]):
    @classmethod
    def c(cls: 'type[C[T]]') -> 'C[T]':
        return cls()

def f(t: T) -> C[T]:
    return C[T].c()

kbouchiat avatar Dec 16 '23 13:12 kbouchiat