具有泛型返回类型的函数导致调用具有特定类型的函数时出现类型问题

2024-09-29 02:27:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个通用的查找函数,它主要返回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语句会引发键入异常(在我的linting期间)

  1. 在这些方法中有更多的逻辑,我需要单独的get_*函数,所以我不能简单地折叠所有用法
  2. get_*函数上有显式的返回类型会非常好
  3. 复制get_hashed_value感觉像是一种糟糕的做法,只是为了避开打字问题
  4. 忽略所有调用的get_hashed_value类型感觉很糟糕

谢谢你的帮助!我也确信以前有人问过这个问题,但我很难找到答案


Tags: 方法key函数getreturnvaluedeftable
1条回答
网友
1楼 · 发布于 2024-09-29 02:27:26

有趣的是,这并没有为我返回类型警告(在Pycharm中)。我不知道为什么它没有警告什么可以与“沮丧”相媲美,但Pycharm并不是完美的

不管怎么说,这似乎是一份更适合^{}而不是Union的工作:

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)

相关问题 更多 >