Skip to content
Advertisement

Abstract base class using type of subclass in abstractmethods

I want to create an abstract base class with an abstract method that returns an instance of any subclass that implements the interface. Is there a more pythonic way to achieve this for mypy other than what I have created below?

In my code example, I make the Animal class generic. Subclasses can inherit from Animal and specify the generic parameter as itself but it seems clunky and wrong to me. I think I may be missing something obvious.

Notice that in the code below, when I subclass Animal the class definition uses something like Dog(Animal["Dog"]). It doesn’t look right to me, but it works for type checking. Is there a way to indicate for an abstract method that it must return the same type as self?

JavaScript

Advertisement

Answer

AFAIK you don’t need your Animal class to be Generic unless it is some kind of container, e.g. Sequence, we can just use TypeVar for a particular method

So this should work as intended

JavaScript

mypy will inform about an error on a last line:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement