Python 3 中的 __total__ dunder 属性是什么意思?

在新发布的 Python 3.8 中有一个新的类型注解typing.TypedDict。它的文档提到

自省的类型信息可以通过Point2D.__annotations__和访问Point2D.__total__。[……]

虽然__annotations__众所周知,已在PEP 3107中引入,但我找不到任何关于__total__. 谁能解释它的含义,如果可能的话,链接到权威来源?


交互式爱情
浏览 191回答 2
2回答

狐的传说

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

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):&nbsp; &nbsp; def __new__(cls, name, bases, ns, total=True):&nbsp; &nbsp; &nbsp; &nbsp; """Create new typed dict class object.&nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; &nbsp; """&nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; &nbsp; if not hasattr(tp_dict, '__total__'):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tp_dict.__total__ = total&nbsp; &nbsp; &nbsp; &nbsp; ...它是如何工作的?概要:默认情况下,实例化定义时需要所有键TypedDict。 total=False覆盖此限制并允许可选键。请参阅以下演示。给定测试目录树:代码测试目录下的文件:# rgb_bad.pyfrom typing import TypedDictclass Color(TypedDict):&nbsp; &nbsp; r: int&nbsp; &nbsp; g: int&nbsp; &nbsp; b: int&nbsp; &nbsp; a: floatblue = Color(r=0, g=0, b=255)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# missing "a"# rgb_good.pyfrom typing import TypedDictclass Color(TypedDict, total=False):&nbsp; &nbsp; r: int&nbsp; &nbsp; g: int&nbsp; &nbsp; b: int&nbsp; &nbsp; a: floatblue = Color(r=0, g=0, b=255)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# 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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python