So I'm investigating how to Type large JSON objects I get back from devices. I found the TypedDict
type in Python 3.8 and think it's pretty cool.
But then I started going down the rabbit hole of nested dictionaries and wasn't sure if there was a better way.
Question: Is there a way to define nested typed Dicts using the class notation?
I have the following dictionary
object = {
'name': 'My Name',
'somekey': {
'subkey1': 1,
'subkey2': {
'subsubkey1': 2,
'subsubkey2': 'nested'
}
}
}
I import the following library
from typing import TypedDict
Using the assignment annotation I was able to come up with this but it's ugly and hard to read.
MyObjAssignmentNotation = TypedDict('Obj', {'name': str, 'somekey': TypedDict('SubObj_1', {'subkey1': int, 'subkey2': TypedDict(
'SubObj_2', {'subsubkey1': int, 'subsubkey2': str})})}
Using the class notation I came up with this, but the types are all separated and it's not easy to read what the combined type should be since you have to read from the bottom up.
class SubObj_Layer2(TypedDict):
subsubkey1: int
subsubkey2: str
class SubObj_Layer1(TypedDict):
subkey1: int
subkey2: SubObj_Layer2
class MyObjClassNotation(TypedDict):
name: str
somekey: SubObj_Layer1
Then i got a bit creative and put the two together and it's a little better, but not much.
class MyObjClassAndAssignmentNotation(TypedDict):
name: str
somekey: TypedDict('SubObj_1', {'subkey1': int, 'subkey2': TypedDict(
'SubObj_2', {'subsubkey1': int, 'subsubkey2': str})})
Any suggestions on improving the above syntax?