我有一个通用的查找函数,它主要返回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语句会引发键入异常(在我的linting期间)
get_*
函数,所以我不能简单地折叠所有用法get_*
函数上有显式的返回类型会非常好get_hashed_value
感觉像是一种糟糕的做法,只是为了避开打字问题get_hashed_value
类型感觉很糟糕谢谢你的帮助!我也确信以前有人问过这个问题,但我很难找到答案
有趣的是,这并没有为我返回类型警告(在Pycharm中)。我不知道为什么它没有警告什么可以与“沮丧”相媲美,但Pycharm并不是完美的
不管怎么说,这似乎是一份更适合^{} 而不是
Union
的工作:相关问题 更多 >
编程相关推荐