Search code examples
pythontype-hinting

Typehint method as returning return type of other method in python?


I have a base class:

from abc import abstractmethod

class Thing:
    @abstractmethod
    def _process(self):
        ...

    def process(self, x: int):
        self.pre_process(x)
        return self._process()

How do I typehint process as returning the return type of _process? My first thought was something like:

from abc import abstractmethod
from typing import TypeVar

class Thing:
    T = TypeVar("T")

    @abstractmethod
    def _process(self) -> T:
        ...

    def process(self, x: int) -> T:
        ...

But mypy 1.3.0 complains quite rightly that T is only present once in the function signature:


> mypy /tmp/t.py
...
error: A function returning TypeVar should receive at least one argument containing the same TypeVar
...

Solution

  • You can make Thing inherit Generic[T].

    from typing import TypeVar
    from typing import Generic
    from abc import abstractmethod
    
    T = TypeVar("T")
    
    class Thing(Generic[T]):
        @abstractmethod
        def _process(self) -> T:
            ...
    
        def process(self, x: int) -> T:
            return self._process()
    
    > mypy /tmp/t.py
    Success: no issues found in 1 source file
    

    Now you can inherit from Thing like this:

    class A(Thing[list]):
        def _process(self) -> list:
            return []