在Python中,如何将一个方法的返回类型作为另一个方法的类型提示?

huangapple go评论71阅读模式
英文:

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
...
英文:

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
...

答案1

得分: 3

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 []
英文:

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 []

huangapple
  • 本文由 发表于 2023年6月12日 21:00:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76456918.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定