如何将字典的get方法与具有mypy和types的map等高阶函数一起使用?

问题描述

我有以下相当简单的代码段,它们使用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]]"

这是一个已知问题,还是有一种不需要使用类型ignore的变通办法(也希望它不会过于繁琐或降低性能)?我想我的代码中可能还会出现其他错误,但它似乎按预期工作。

解决方法

由于如果密钥不存在,dict.get()返回None作为默认值,所以您需要使用Optional

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

在这里使用 map.__getitem__ 而不是 map.get 可能更好。由于您已经确保存在键,因此您无需在之后进行额外的过滤来说服 mypy .get(...) 将始终返回一个值:

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

__getitem__[...] 运算符的魔术方法名称

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...