Could not make a good title … better see the code.
I’m trying to use pydantic to process nested configuration data. Of course, I want to validate the whole structure, but the final result should be a class at the top level (BaseModel or dataclass), but the fields should be dicts.
from pydantic import BaseModel, Field
class Inner(BaseModel):
name: str
count: int = Field(default=123)
class Outer(BaseModel):
main: Inner
aux: str = Field(default="stable")
DATA = {'main': {'name': 'blues'}}
mclass = Outer.validate(DATA)
# class -> attr based access
print(mclass.main.count)
# dict -> key based access
mdict = mclass.model_dump()
print(mdict['main']['count'])
# what I want: class at the top level, but field values as dict
mxxx.main['count'] # <--- ???
I could change the type of all fields corresponding to nested models:
mclass.main = mclass.main.model_dump()
But can the pydantic
define such nested model “naturally”? I’m not an experienced user. I tried the TypedDict
(as in this related post: /a/74643914/5378816), but it cannot create defaults or use custom validators.