catspeake
TypedDict通过PEP 589在 Python 3.8 中被接受。在 Python 中,它似乎是一个默认__total__设置为的布尔标志:Truetot = TypedDict.__total__print(type(tot))print(tot)# <class 'bool'># True正如其他帖子中提到的,有关此方法的详细信息在文档中有所限制,但@Yann Vernier 指向CPython 源代码的链接强烈建议与Python 3.8 中引入__total__的新total关键字有关:# cypthon/typing.pyclass _TypedDictMeta(type): def __new__(cls, name, bases, ns, total=True): """Create new typed dict class object. ... """ ... if not hasattr(tp_dict, '__total__'): tp_dict.__total__ = total ...它是如何工作的?概要:默认情况下,实例化定义时需要所有键TypedDict。 total=False覆盖此限制并允许可选键。请参阅以下演示。给定测试目录树:代码测试目录下的文件:# rgb_bad.pyfrom typing import TypedDictclass Color(TypedDict): r: int g: int b: int a: floatblue = Color(r=0, g=0, b=255) # missing "a"# rgb_good.pyfrom typing import TypedDictclass Color(TypedDict, total=False): r: int g: int b: int a: floatblue = Color(r=0, g=0, b=255) # missing "a"演示如果缺少密钥,mypy 将在命令行中抱怨:> mypy code/rgb_bad.pycode\rgb_bad.py:11: error: Key 'a' missing for TypedDict "Color"...设置total=False允许可选键:> mypy code/rgb_good.pySuccess: no issues found in 1 source file