我在打开问题之前在这里询问,因为我不确定这是否是预期的行为。我的感觉告诉我这与运行时检查有关,但我不确定,
我有这个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的第二个参数是一个字符串,所以返回有.startswitch,但仍然是错误。我在这个问题上使用# 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)