Mypy无法从TypedDict.getOptional [key],str推断类型

问题描述

在问问题之前,我想问一下,因为我不确定这是否是预期的行为。我的想法告诉我,这与运行时检查有关,但是我不确定,

我有这个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]代表TNone,所以a: D = {"bar": None}会进行类型检查,这就是a.get("bar","").startswith("bar")不能输入的原因。如果您可以选择将TypedDict中的每个键都设为可选,则可以使用total=False

D = TypedDict("D",{"bar": str},total=False)

相关问答

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