Type hint for returning non-instantiated class type

Viewed 1162

I have a situation where I want to return a non instantiated class object, a type. I would go for ->type, as non-instantiated classes are of type 'type', but the function is not supposed to return 'any class type', I'm interested only in returning one of class types that inherits from A, because on instantiated object of this class I'm later to run some methods specific for it.

To better illustrate this, here is a sample code. The question is this possible to put some reasoned type annotation in this case? or if not what would be the correct practice in such situation?

class A():
    def run(self):
        pass

class B(A):
    pass

class C(A):
    pass

def get_letter_class(condition: str) -> ?:
    if condition == 'b':
        return B
    elif condition == 'c':
        return C

class_type = get_letter_class('b')
letter = class_type()
letter.run()
1 Answers

If your function supposed to return classes instead of their instances then we can use typing.Type generic like

from typing import Type
...
def get_letter_class(condition: str) -> Type[A]:

Further reading

Related