排除Python类型注释中的类型 [英] Exclude type in Python typing annotation
问题描述
我编写了以下函数:
def _clean_dict(d):
return {k: v for k, v in d.items() if v is not None}
我想在函数中添加类型注释:
I want to add type annotations to the function:
def _clean_dict(d: Dict[Any, Any]) -> Dict[Any, Any]:
return {k: v for k, v in d.items() if v is not None}
但是,我想明确定义返回的字典中的值不能为None.
However, I want to explicitly define that the values inside the returned dictionary cannot be None.
有没有办法说"Any
类型,除了NoneType
"还是除None
以外的所有可能值"?
Is there a way to say "Any
type, except NoneType
" or "Every possible value but None
"?
推荐答案
鉴于您愿意在调用函数时修复键和值的类型,可以使用泛型对此进行明确.这仍然可能允许V
的实例成为None
,但是使意图很明确.请注意,由于差异问题,您必须使用Mapping
.但是,无论如何这是优选的.
Given that you are willing to fix the types of keys and values when the function is called you can use generics to make this explicit. This still potentially allows instances of V
to be None
, but it makes the intent pretty clear. Note that you have to use Mapping
because of variance issues. However, this is preferable anyway.
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
可以将可选类型正确地转换为非可选类型.
With this definition mypy
correctly turns optional into non-optional types.
# clean_dict.py
d = {"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*]'
这篇关于排除Python类型注释中的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!