Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type hint for returning non-instantiated class type [duplicate]

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()
like image 297
tikej Avatar asked Sep 02 '25 10:09

tikej


1 Answers

If your function supposed to return classes instead of their instances then we can use

Python3.9+

type as generic

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

before Python3.9

typing.Type generic

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

Further reading

  • PEP-484 entry.
  • PEP-585 entry
like image 76
Azat Ibrakov Avatar answered Sep 05 '25 00:09

Azat Ibrakov