在Python类型注释中排除类型

在Python类型注释中排除类型,第1张

在Python类型注释中排除类型

假设您愿意在调用函数时修复键和值的类型,则可以使用泛型来使其明确。这还可能会允许的情况下

V
None
,但它使意图很清楚。请注意,
Mapping
由于存在差异问题,因此必须使用。但是,无论如何这是优选的。

from typing import *K = TypeVar("K")V = TypeVar("V")def _clean_dict(d: Mapping[K, Optional[V]]) -> MutableMapping[K, V]:    return {k: v for k, v in d.items() if v is not None}

使用此定义,可以

mypy
正确地将可选类型转换为非可选类型。

# clean_dict.pyd = {"a": 1, "b": 2, "c": None}reveal_type(d)reveal_type(_clean_dict(d))

$ mypy clean_dict.py

note: Revealed type is 'builtins.dict[builtins.str*, Union[builtins.int, None]]'note: Revealed type is 'typing.MutableMapping[builtins.str*, builtins.int*]'


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5630362.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存