2 回答

TA贡献1804条经验 获得超3个赞
我猜该__total__
字段表示实例是否必须完整(默认)或不(所有字段可选)。我从PEP 589开始搜索,它介绍TypedDict
并描述了整体性。它使用了一个参数,为 语法total
重命名 dunder-style 是有意义的。class
但是,我没有找到这样的重命名发生的时间。
查看 MyPy,它是关心这些注释的实际类型检查器,在和 totality上有类似的文档TypedDict
,但同样没有引用 dunder 语法。深入研究它的实现会导致更多的混乱,因为TypedDictType
types.py没有一个总字段,而是单独的items
and required_keys
。Totality 会暗示这一点,items.keys()==required_keys
但实现会做出不同的假设,例如单独can_be_false
依赖。原则上应该意味着是空的。items
total=False
required_keys
_TypedDictMeta的 CPython 源代码至少表明total
参数和__total__
dunder 是相同的,尽管源代码将TypedDict
自己描述为“可能很快会添加”。

TA贡献1111条经验 获得超0个赞
TypedDict通过PEP 589在 Python 3.8 中被接受。在 Python 中,它似乎是一个默认__total__设置为的布尔标志:True
tot = TypedDict.__total__
print(type(tot))
print(tot)
# <class 'bool'>
# True
正如其他帖子中提到的,有关此方法的详细信息在文档中有所限制,但@Yann Vernier 指向CPython 源代码的链接强烈建议与Python 3.8 中引入__total__的新total关键字有关:
# cypthon/typing.py
class _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.py
from typing import TypedDict
class Color(TypedDict):
r: int
g: int
b: int
a: float
blue = Color(r=0, g=0, b=255) # missing "a"
# rgb_good.py
from typing import TypedDict
class Color(TypedDict, total=False):
r: int
g: int
b: int
a: float
blue = Color(r=0, g=0, b=255) # missing "a"
演示
如果缺少密钥,mypy 将在命令行中抱怨:
> mypy code/rgb_bad.py
code\rgb_bad.py:11: error: Key 'a' missing for TypedDict "Color"
...
设置total=False允许可选键:
> mypy code/rgb_good.py
Success: no issues found in 1 source file
添加回答
举报