如何将字典的“get”方法与高阶函数(如 map 与 mypy 和 typings)结合使用?

How do you use a dictionary's `get` method with higher-order-functions like map with mypy and typings?

我有以下相当简单的代码片段,使用 map 和字典的 get 方法作为映射函数:

OverlapDict = Dict[str, Set[str]]

oMap: OverlapDict = openOverlapMap(sys.argv[1])

oMapKeys: List[str] = list(oMap.keys())[0:nOverlapKeys]
oMapVals: Iterable[Set[str]] = map(oMap.get, oMapKeys)  # type: ignore

如果我删除 # type: ignore,我会收到以下错误:

 error: Argument 1 to "map" has incompatible type overloaded function; expected "Callable[[str], Set[str]]"

这是一个已知问题,还是有不需要使用类型忽略的解决方法(也希望不会过于麻烦或降低性能)?我想我的代码中可能还有其他错误,但它似乎按预期工作。

因为dict.get() return None 作为默认值如果key不存在,你需要使用Optional:

oMapVals: Iterable[Optional[Set[str]]] = map(oMap.get, oMapKeys)

您最好在这里使用 map.__getitem__ 而不是 map.get。由于您已经确保密钥存在,因此您不需要事后进行额外的过滤来说服 mypy .get(...) 将始终 return 一个值:

oMapKeys: List[str] = list(oMap.keys())[0:nOverlapKeys]
oMapVals: Iterable[Set[str]] = map(oMap.__getitem__, oMapKeys)

__getitem__[...] 运算符

的神奇方法名称