How can I mention there should return any child of parent class in Python?

680 Views Asked by At
class Element:
    def __call__(self, *args, **kwargs):
        print('Hello')
        return self


class Button(Element):
    pass


class TextBox(Element):
    pass


def some_func(element: Element) -> Element:
    return element()


some_func(Button)
some_func(TextBox)

Pycharm mentions "Expected type 'Element', got 'Type[Button]' instead ". Is there any proper way to get type of the return as parent of all it's children?

2

There are 2 best solutions below

0
Paweł Rubin On BEST ANSWER

x: Element means that x is an instance of the Element class.

Use type[Element] when you mean to pass a subclass of Element.

def some_func(element: type[Element]) -> Element:
    return element()
0
Roman On

I use Type[Element]. It seems works fine. But my friend told me that it means an instance of the class but not the class itself. Seems like right answer is some_func(element: t.Type[_T]) -> _T, where _T = t.TypeVar('_T', bound='Element') and import typing as t was performed. But it's not very readable, so I prefer use Type[Element]. Thank you all! And especialy thanks to SUTerliakov.