Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to annotate that a classmethod returns an instance of that class [duplicate]

Using PEP 484, is there a way to annotate that a classmethod returns an instance of that class?

e.g.

@dataclass
class Bar:

    foo: str

    @classmethod
    def new_from_foo(cls, foo) -> Bar
        ...

or

    @classmethod
    def new_from_foo(cls, foo) -> cls
like image 422
Gary van der Merwe Avatar asked Aug 02 '18 07:08

Gary van der Merwe


Video Answer


1 Answers

The trick is to use a TypeVar to connect the cls parameter to the return annotation:

from typing import TypeVar, Type

T = TypeVar('T')

class Bar:
    @classmethod
    def new_from_foo(cls: Type[T], foo) -> T:
        ...
like image 152
Aran-Fey Avatar answered Nov 14 '22 21:11

Aran-Fey