【发布时间】:2020-10-02 20:36:36
【问题描述】:
我有一个继承自typing.Generic 的类,并传入一个TypeVar 作为参数。
稍后在代码中,我想:
- 静态(不是在运行时)从类中获取
TypeVar参数 - 将其别名为另一个类型变量
- 使用该别名键入提示函数的
return
在 Python 中有什么方法可以实现这一点吗?
我唯一缺少的是第 1 步,如何从类型变量中获取类型参数
我的用例
from abc import ABC, abstractmethod
from typing import TypeVar, Generic
TFloat = TypeVar("TFloat", bound=float)
class BaseDataClass(Generic[TFloat], ABC):
@property
@abstractmethod
def data(self) -> TFloat:
"""Get data."""
class ChildDataClass(BaseDataClass[int]):
@property
def data(self) -> int:
return 1
然后我将BaseDataClass 和ChildDataClass 导入另一个模块。
在第二个模块中,有没有办法从BaseDataClass 静态获取TFloat 参数,或者从ChildDataClass 获取int 参数,并在mypy 中使用它?
仅供参考:我使用的是 Python 3.8.2。
【问题讨论】:
标签: python generics mypy static-typing python-typing