MarcTheSpark
MarcTheSpark

Reputation: 543

Python: specify return type of class method that works with inheritance

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!

Upvotes: 6

Views: 4030

Answers (1)

user2357112
user2357112

Reputation: 281758

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

Upvotes: 14

Related Questions