Thursday, 4 March 2021

Python type hinting with abstract base classes

I have an ABC with a method that subclasses should return with their own type, and I'm trying to figure out the best way to typehint this. For example:

from abc import ABC, abstractmethod

class Base(ABC):
    @abstractmethod
    def f(self): ## here i want a type hint for type(self)
        pass

class Blah(Base):
    def __init__(self, x: int):
        self.x = x

    def f(self) -> "Blah":
        return Blah(self.x + 1)

The best I could think of is this, which is a bit heavy:

from abc import ABC, abstractmethod
from typing import TypeVar, Generic

SELF = TypeVar["SELF"]

class Base(ABC, Generic[SELF]):

    @abstractmethod
    def f(self) -> SELF:
        pass

class Blah(Base["Blah"]):

    def __init__(self, x: int):
        self.x = x

    def f(self) -> "Blah":
        return Blah(self.x+1)

I there a better/cleaner way?



from Python type hinting with abstract base classes

No comments:

Post a Comment