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
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:
...
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