问题描述
在问问题之前,我想问一下,因为我不确定这是否是预期的行为。我的想法告诉我,这与运行时检查有关,但是我不确定,
我有这个MVE
from typing import Optional
from typing_extensions import TypedDict
D = TypedDict("D",{"bar": Optional[str]})
def foo() -> None:
a: D = {"bar": ""}
a.get("bar","").startswith("bar")
mypy会抱怨:
Item "None" of "Optional[str]" has no attribute "startswith"
现在非常明显的是,由于get的第二个参数是字符串,因此返回具有.startswith,但仍然是错误。我正在使用# type:ignore
,还有其他方法吗?
解决方法
Optional[T]
代表T
或None
,所以a: D = {"bar": None}
会进行类型检查,这就是a.get("bar","").startswith("bar")
不能输入的原因。如果您可以选择将TypedDict
中的每个键都设为可选,则可以使用total=False
:
D = TypedDict("D",{"bar": str},total=False)