I have a dict with of which the types of the keys and values are fixed. I want to define the types in a TypedDict
as follows:
class MyTable(TypedDict):
caption: List[str]
header: List[str]
table: pd.DataFrame
epilogue: List[str]
I have function that returns a MyTable
. I want to define first an empty (Typed)dict
and fill in keys and values.
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']
return result
Here MyPy complains that a type annotation for result is needed. I tried the this:
result: MyTable = {}
but then MyPy complains that the keys are missing. Similarly, if I define the keys but set the values to None
, it complains about incorrect types of the values.
Is it at all possible to initialize a TypedDict
as an empty Dict first and fill in the keys and values later? The docs seem to suggest it is.
I guess I could first define the values as variables and assemble the MyTable
later but I'm dealing with legacy code that I'm adding type hinting to. So I'd like to minimize the work.