Danii672
Danii672

Reputation: 33

Python generic TypeVar bound to generic base class

Say I have a Python abstract class in the shape:

class AbcClass(ABC, Generic[T]): ...

With some implementations:

class IntClass(AbcClass[int]): ...
class StrClass(AbcClass[str]): ...
class FloatClass(AbcClass[float]): ...

Then I want to have a function foo that takes in an instance of any of the subclasses and a value that matches the type of the generic of that subclass. For example:

def foo(obj: IntClass, value: int) -> None: ...
def foo(obj: StrClass, value: str) -> None: ...
def foo(obj: FloatClass, value: float) -> None: ...

I'm trying to create a decorator for foo and want to correctly type the method signature. What's the right way to type the function foo with a Callable? Right now I'm doing:

T = TypeVar("T", bound=AbcClass)
V = TypeVar("V")
FooFn = Callable[[T, V], None]

However, V is not related to T in the above code so even for a specific IntClass technically V could be any value. How can I fix this? Using the following is not possible since AbcClass is not covariant and I want to be able to type any subclass (e.g.: IntClass) as well.

FooFn = Callable[[AbcClass[V], V], None]

Upvotes: 0

Views: 39

Answers (0)

Related Questions