Search code examples
pythongenericsinheritancesubclasspython-typing

Dynamic typing of subclasses using generics in Python


Let's say i have to following classes.

class A:
    @staticmethod
    def foo():
        pass

class B(A):
    pass

And I have some kind of function that constructs an object based on it's type as well as calls a function.

def create(cls: Type[A]) -> A:
    cls.foo()
    return cls()

Now I can make the following calls to that function. And because B inherits from A it's all good.

instance_a: A = create(A)
instance_b: B = create(B)

Except the with the latter, type-checking will start complaining because create according to the annotations returns an instance of A.

This could be solved with TypeVar as follows.

from typing import Type, TypeVar

T = TypeVar('T')
def create(cls: Type[T]) -> T:
   cls.foo() 
   return cls()

Except now the typing checking doesn't do it's original job of guarantying that cls has a method called foo. Is there a way to specify a generic to be of a certain type?


Solution

  • You can supply a bound:

    T = TypeVar('T', bound=A)