I've been trying to understand how I can specify the return type of a class method in Python, such that it is interpreted correctly (e.g. in my Sphinx documentation) even for child classes.
Suppose I had:
class Parent:
@classmethod
def a_class_method(cls) -> 'Parent':
return cls()
class Child(Parent):
pass
What should I specify as the return type of a_class_method if I want it to be Parent for the parent and Child for the child? I've also tried __qualname__, but that doesn't seem to work either. Should I just not annotate the return type?
Thanks in advance!
There's supported syntax for that now, by annotating cls with a type variable. Quoting one of the examples from PEP 484:
T = TypeVar('T', bound='C')
class C:
@classmethod
def factory(cls: Type[T]) -> T:
# make a new instance of cls
class D(C): ...
d = D.factory() # type here should be D
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