Let's say I have a function that is able to compare fruits, I could explicitly mention this in type annotations like this:
def compare_fruits(one: Fruit, other: Fruit) -> bool:
assert type(one) is type(other) # <-- type hint for this
...
This implies it would be a valid operation to compare an Apple
and Pear
objects as subclasses, but it's not for my program. I'd like to find a way to type-annotate the function's arguments with an generic of "same-type". I think I know how to do that in abstract classes with user-defined Generic types, but it's not clear to me how to do this for plain functions.
I tried this the naive way:
FruitType = TypeVar("FruitType")
def compare_fruits(one: Generic[FruitType], other: Generic[FruitType]) -> bool:
...
yields error: Variable "typing.Generic" is not valid as a type
in mypy, which makes sense.
Then I tried this:
FruitType = TypeVar("FruitType")
class MyFruitModule(Generic[FruitType]):
@staticmethod
def compare(one: FruitType, other: FruitType) -> bool:
...
compare_apples = MyFruitModule[Apple].compare # still not implicit same-type
Any ideas or a source about that this is simply impossible as of the moment?