Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 906
MarcTheSpark Avatar asked Aug 31 '26 05:08

MarcTheSpark


1 Answers

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
like image 75
user2357112 supports Monica Avatar answered Sep 02 '26 18:09

user2357112 supports Monica