Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python type hinting with abstract base classes [duplicate]

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?

like image 575
mrip Avatar asked May 03 '26 08:05

mrip


1 Answers

Using python 3.7 it works by importing annotations from __future__

from __future__ import annotations

class Base():
    def f(self) -> Base: ## Here the type is Base since we can not guarantee it is a Blah
        pass

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

    def f(self) -> Blah: ## Here we can be more specific and say that it is a Blah
        return Blah(self.x + 1)
like image 72
Cedric Avatar answered May 05 '26 20:05

Cedric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!