Python如何根据输入的类类型参数指定函数返回值类型,解决mypy报错
解决方案
核心思路是通过绑定泛型建立输入类参数和返回值类型的静态关联,具体修改如下:
首先定义绑定了BaseObject的泛型变量,修改df2objects的类型注解:
import pandas as pd from typing import Tuple, Type, TypeVar # 泛型T限定为BaseObject及其子类 T = TypeVar('T', bound=BaseObject) def df2objects(df: pd.DataFrame, object_type: Type[T]) -> Tuple[T, ...]: return tuple(object_type(**kwargs) for kwargs in df.to_dict(orient='records'))
修改完成后原use_it函数无需额外加cast即可通过mypy检查:
def use_it(df: pd.DataFrame) -> Tuple[DerivedObject,...]: return df2objects(df, DerivedObject)
原写法失效原因
你之前尝试的写法中直接把运行时参数object_type写到类型注解里,而Python的类型检查是静态执行的,无法识别运行时变量作为类型,因此需要通过泛型TypeVar提前建立参数和返回值的类型映射关系。
内容的提问来源于stack exchange,提问作者Dan Hook
相关产品推荐
相关产品推荐

