如何解决具有通用返回类型的函数在调用具有特定类型的函数时导致键入问题
我有一个通用的查找函数,该函数通常返回TypeA
,但有时可以返回TypeB
:
Types = Union[TypeA,TypeB]
def get_hashed_value(
key:str,table: Dict[str,Types]
) -> Types:
return table.get(key)
并且我在两个不太通用的函数中使用它:
def get_valueA(key: str) -> TypeA:
return get_hashed_value(key,A_dict) # A_dict: Dict[str,TypeA]
和
def get_valueB(key: str) -> TypeB:
return get_hashed_value(key,B_dict) # B_dict: Dict[str,TypeB]
由于get_hashed_value
可以返回TypeA
或TypeB
,所以get_*
函数中的return语句会引发键入异常(在我的尝试中)
- 这些方法中的逻辑更多,我需要单独的
get_*
函数,所以我不能只折叠所有用法 - 在
get_*
函数上具有显式的返回类型真是太好了 - 复制
get_hashed_value
只是为了解决输入问题,这是一种不好的做法 - 仅忽略键入所有
get_hashed_value
的类型感到很难过
感谢您的帮助!另外,我敢肯定,这已经被问过了,但是我很难找到答案。 :\
解决方法
有趣的是,这并没有为我返回类型警告(在Pycharm中)。我不确定为什么不警告什么可以与“失败”相提并论,但是Pycharm并不完美。
无论如何,这似乎是比Union
更适合TypeVar
的工作:
from typing import TypeVar,Dict
T = TypeVar("T",TypeA,TypeB) # A generic type that can only be a TypeA or TypeB
# And the T stays consistent from the input to the output
def get_hashed_value(key: str,table: Dict[str,T]) -> T:
return table.get(key)
# Which means that if you feed it a Dict[str,TypeA],it will expect a TypeA return
def get_valueA(key: str) -> TypeA:
return get_hashed_value(key,A_dict)
# And if you feed it a Dict[str,TypeB],it will expect an TypeB return
def get_valueB(key: str) -> TypeB:
return get_hashed_value(key,B_dict)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。