英文:
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 []
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论