[Python] Type hint return type of abstract method to be any instance of parent class

Discussão em 'Python' iniciado por Stack, Abril 5, 2025.

  1. Stack

    Stack Membro Participativo

    How can I type hint that the return type of a method of some abstract class is some instance of this class?

    My intuitive answer is that

    @abstractmethod
    def mymethod() -> typing.Self:
    pass


    should be the correct way (as suggested in this post for example). But when I now subclass from this class, the return type is restricted to the type of the child class. What is the correct way to type hint here, so every subclass of the parent class is allowed?

    Example code:

    from abc import ABC, abstractmethod
    from typing import Self, override
    import random

    class DiceResult(ABC):
    @abstractmethod
    def reroll(self) -> Self:
    pass

    class NaturalTwenty(DiceResult):
    @override
    def reroll(self) -> DiceResult: # Type checkers report an error here
    return random.choice([NaturalTwenty(), NaturalOne()])

    class NaturalOne(DiceResult):
    @override
    def reroll(self) -> DiceResult: # Type checkers report an error here
    return random.choice([NaturalTwenty(), NaturalOne()])


    Mypy playground Basedpyright playground

    Continue reading...

Compartilhe esta Página