尽管阅读了
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.
TypedDict
不定义 dict
的 实例。它定义了
dict
的子类型,其中有一个(零个?)或多个 必须 存在的键。没有值,只有 type(s) 对于实例中的任何值。
例如,
{'messages': [1,2,3]}
是MyClass
的实例。 {'foo': [1,2,3]}
不是(因为 MyClass
没有定义键 fo
),{'messages': [1,2,3], 'foo': 3}
也不是(因为 MyClass
仅将 messages
定义为键,而不是任何其他键)。