为什么 Final 字典不能用作 TypedDict 中的文字?

Mar*_*hac 6 python dictionary type-hinting mypy python-typing

我正在尝试完成以下任务(请参阅mypy Playground):

from typing import TypedDict, Final

account_schema: Final = {"name": str, "email": str}

Account = TypedDict("Account", account_schema)
AccountPatch = TypedDict("AccountPatch", account_schema, total=False)
Run Code Online (Sandbox Code Playgroud)

我的想法是,我可以在一个地方指定我的模式,一个版本需要所有字段(Account插入数据库时​​),另一个版本使所有字段可选(AccountPatch更新数据库时)。

来自PEP 586

限定符Final用作声明变量有效的简写Literal

mypy错误如下:

error: TypedDict() expects a dictionary literal as the second argument
Run Code Online (Sandbox Code Playgroud)

为什么不允许TypedDict字典Final作为其第二个参数?

对于我的核心问题,我是否可以对两个TypedDicts 使用相同的架构(一个具有整体性,一个不具有整体性),而不必复制架构?

edd*_*313 1

正如评论中指出的,这是不可能的。请参阅 mypy 的 github 上提出的问题:TypedDict 键重用?。错误就在这里出现。

定义两个 TypeDict 的唯一方法是重复代码

from typing import TypedDict

Account = TypedDict("Account", {"name": str, "email": str})
AccountPatch = TypedDict("AccountPatch", {"name": str, "email": str}, total=False)
Run Code Online (Sandbox Code Playgroud)