pythonpycharmpython-typing

Why does PyCharm show that the return of a classmethod called on a class derived from a Generic class is not an instance of the derived class?


This is using Python 3.13.

I have a case where I'm derived from a Generic class (specifying a concrete type), and I came across a warning that I was not expecting. I have a classmethod on the base class that returns an instance of "Self", and PyCharm is telling me that when I call that classmethod on the derived class, it doesn't actually return an instance of the derived class - it returns an instance of the specified-generic-type that the derived class inherits from. I'm pretty new to python Generics, but I don't understand why this is incorrect. Here's a minimal example that exhibits the warning:

from typing import Self

class A[T]:
    @classmethod
    def create(cls) -> Self:
        return cls()

class B(A[int]):
    pass

def create_b() -> B:
    return B.create() # Warning: "Expected type 'B', got 'A[int]' instead"

Solution

  • There's nothing wrong with your code. This is a bug in PyCharm.

    Put a # type: ignore or # noqa there and move on.