您可能想要的是设置总体性,但我会三思而行使用它。
Quoting the PEP https://www.python.org/dev/peps/pep-0589/#totality
默认情况下,所有键都必须出现在 TypedDict 中。可以通过指定总体性来覆盖它。以下是如何使用基于类的语法来执行此操作:
class MyTable(TypedDict, total=False):
caption: List[str]
header: List[str]
table: pd.DataFrame
epilogue: List[str]
result: MyTable = {}
result2: MyTable = {"caption": ["One", "Two", "Three"]}
正如我所说,请三思而后行。总计TypedDict
给你一个很好的保证,所有的项目都会存在。也就是说,因为 MyPy 不允许结果存在而没有“标题”,所以您可以安全地调用cap = result["caption"]
.
如果你设置total=False,那么这个保证就会消失。假设您正在使用您的MyTable
比您制造的更常见,在使用时获得额外的安全保证可能是一笔不错的交易。
就我个人而言,我会保留total=False
对于创建代码有时确实遗漏了某些内容的情况,并且任何使用它的代码都必须处理该问题。如果只是需要几行来初始化,我会这样做:
def returnsMyTable():
result = {}
result_caption = ['caption line 1','caption line 2']
result_header = ['header line 1','header line 2']
result_table = pd.DataFrame()
result_epilogue = ['epilogue line 1','epilogue line 2']
result = {
"caption": result_caption,
"header": result_header,
"table": result_table,
"epilogue": result_epilogue
}
return result