simple dicts
you can simply use Mapping[K, V]
as the value for another Mapping
. let's say your json looks like this:
{
"person_1": {"money": 1000},
"person_2": {"money": 1000}
}
in this case you can use a type hint that looks like this:
Mapping[str, Mapping[str, int]]
harder dicts
but let's say you have something more complex, like this:
{
"person_1": {
"money": 1000,
"job": "coder",
}
}
how could you type hint this then? you can use Union
(from typing) to do something like this:
Mapping[str, Mapping[str, Union[str, int]]]
but now we would run into a problem with tools like mypy thinking that our_dict["person_1"]["job"]
has the type Union[str, int]
well it is not wrong, that is what we told it after all. something that could help here is TypedDict from typing_extensions.
from typing_extensions import TypedDict
class Person(TypedDict):
money: int
job: str
# type hint you would use in your function:
Mapping[str, Person]
NOTE: in python 3.8 TypedDict
is part of typing
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…