The kind of data structure I parse in my Python script is a json file which, after json.load(file_handle)
, is of type <class 'dict'>
. So far so good. Now for a function using it as an input argument, I want a type hint for the parsed json. I read in the typing documentation, that for dict
s as arguments, I should use Mapping[key_type, value_type]
:
from typing import Mapping
def foo(json_data: Mapping[str, str]) -> None:
...
The json I parse has str
-type keys and str
-type values, but more often than not, its structure is highly recursive. Hence a value is more likely to be a dict
with str
keys and even such dict
s as values. It is very nested, until, at the deepest level, the last dict finally has str
keys and str
values.
So how do I represent this data structure more precisely? I was thinking something, along the lines of this question, that it might be:
Union[Mapping[str, str], Mapping[str, Mapping]]
But it does seem to represent only one level of recursion. Is there a better way to type-hint this?