I'm curious if it's possible to get mypy to understand that some method in a class takes a cls argument rather than a self argument. The concrete use-case I have in mind is typing a sqlalchemy hybrid_property's .expression decorator, but a simpler example would be trying to implement a custom/non-built-in version of classmethod.
Applying an explicit type annotation to cls doesn't work, e.g.
from typing import Type
class Example:
@my_custom_classmethod
def foo(cls: Type["Example"]) -> str:
return "doesn't work"
Mypy complains that The erased type of self "Type[Example]" is not a supertype of its class "Example", which, ok, I guess often makes sense, but it doesn't make sense here :/
The best solution I've managed to come up with so far is to just # type: ignore the method's signature:
class Example:
@my_custom_classmethod
def foo(cls: Type["Example"]) -> str: # type: ignore
return "this actually kind of does work!"
This actually does seem to basically work, insofar as cls has the right type in the body of the method and the decorator receives a method of the right type, but it feels a bit hacky.