What you might want here is to set totality, but I'd think twice about using it.
Quoting the PEP
By default, all keys must be present in a TypedDict. It is possible to override this by specifying totality. Here is how to do this using the class-based syntax:
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"]}
As I said, think twice about that. A total TypedDict
gives you a very nice guarantee that all of the items will exist. That is, because MyPy won't allow result to exist without "caption", you can safely call cap = result["caption"]
.
If you set total=False, that guarantee goes away. On the assumption that you're using your MyTable
much more commonly than you're making it, getting the additional safety assurances when you use it is probably a good trade.
Personally, I'd reserve total=False
for cases where the creation code sometimes genuinely does leave things out and any code that uses it has to handle that. If it's just a case of taking a few lines to initialise, I'd do it like this:
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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…