具有通用 return 类型的函数在调用具有特定类型的函数时导致输入问题

Function with generic return type causing typing issues in calling functions with specific type

我有一个通用的查找函数,主要是 returns TypeA,但有时 return 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 可以 return TypeATypeBget_* 函数中的 return 语句抛出输入异常(在我的 linting 期间)

  1. 这些方法的逻辑比较多,我需要单独的get_*函数,所以我不能把所有的用法都折叠起来
  2. get_* 函数上有明确的 return 类型会非常好
  3. 感觉复制 get_hashed_value 是一种不好的做法,只是为了解决打字问题
  4. 忽略所有 get_hashed_value 被调用的类型感觉很糟糕

感谢您的帮助!我也确信之前有人问过这个问题,但我找不到答案。 :\

有趣的是,这对我来说 return 不是类型警告(在 Pycharm 中)。我不确定为什么它没有警告与“沮丧”相当的东西,但是 Pycharm 并不完美。

无论如何,这似乎是一份 TypeVarUnion 更适合的工作:

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)