settingspython-3.8typeddict

Can you give an example for a NESTED TypedDict in class notation?


I want to have typed settings and came across this answer and TypedDict but could not get it working with nested structures.

Assuming the following dict, how can I best add typing?

{
    "global": {
        "region": "eu-central-1",
    },
    "env": {
        "dev": {
            "name": "dev.local",
        },
        "prod": {
            "name": "prod.world",
        }
    }
}

P.S.: I would also be interested, how to do that with data classes, if you have the answer?


Solution

  • Try something like this:

    from typing import TypedDict
    
    class Env(TypedDict):
        name: str
    
    class Region(TypedDict):
        region: str
    
    class EnvDescr(TypedDict):
        global: Region
        dev: Env
        prod: Env