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()
If your function supposed to return classes instead of their instances then we can use
type
as generic
from typing import Type
...
def get_letter_class(condition: str) -> type[A]:
typing.Type
generic
from typing import Type
...
def get_letter_class(condition: str) -> Type[A]:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With