理解仅定义一个字段的“TypedDict”子类

问题描述 投票:0回答:1

尽管阅读了

TypedDict
文档和大量示例,但我无法理解下面的代码片段。我肯定错过了一些东西(一个概念)。

MyClass
指定一个字段(
messages
),但它不应该至少有两个吗?对于
key
value
?在这种情况下,
key
value
是什么?

from typing import Annotated
from typing_extensions import TypedDict

class MyClass(TypedDict):
    messages: Annotated[list, add_messages]
    # messages have the type "list".
    # "add_messages" is some function that appends
    # rather than overwrites messages to list.
python python-typing
1个回答
0
投票

TypedDict
不定义 dict
实例
。它定义了
dict
的子类型,其中有一个(零个?)或多个 必须 存在的键。没有值,只有 type(s) 对于实例中的任何值。

例如,

{'messages': [1,2,3]}
MyClass
的实例。
{'foo': [1,2,3]}
不是(因为
MyClass
没有定义键
fo
),
{'messages': [1,2,3], 'foo': 3}
也不是(因为
MyClass
仅将
messages
定义为键,而不是任何其他键)。

© www.soinside.com 2019 - 2024. All rights reserved.