具有通用返回类型的函数在调用具有特定类型的函数时导致键入问题

问题描述

我有一个通用的查找函数,该函数通常返回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可以返回TypeATypeB,所以get_*函数中的return语句会引发键入异常(在我的尝试中)

  1. 这些方法中的逻辑更多,我需要单独的get_*函数,所以我不能只折叠所有用法
  2. get_*函数上具有显式的返回类型真是太好了
  3. 复制get_hashed_value只是为了解决输入问题,这是一种不好的做法
  4. 仅忽略键入所有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)