pythonmetadatapydanticpydantic-v2

Add same meta data for a class each time an instance of class is created in Pydantic


I have three Pydantic classes like so:

    class Meta(BaseModel):
         """Meta data attached to parent objects"""
        description: str = Field(description="description of the parent object")
        type: str = Field(description="type of the parent object")  

    class Goal(BaseModel):
        """Customer goals"""
        _id: str
        meta: Meta_v2

    class Insurance(BaseModel):
        """Customer insurance"""
        _id: str
        meta: Meta_v2

When I create an Insurance class, I want to automatically create a nested instance of Meta with:

description: "A customer insurance policy"
type: "insurance"

But when I create a Goal class, I want to automatically create a nested instance of Meta with:

description: "A customer goal"
type: "goal"

How do I do this pls?


Solution

  • I'm assuming Meta is Meta_v2 or some subclass that is omitted.

    Just add a meta object as a default value to your classes (Insurance, Goal, etc).

    default_meta = Meta_v2(description="A customer insurance policy", type="insurance")
    
    
    class Insurance(BaseModel):
        id: str
        meta: Meta_v2 = Field(default_meta)
    
    
    insurance = Insurance(id="1234")
    print(insurance.model_dump())
    # {'id': '1234', 'meta': {'description': 'A customer insurance policy', 'type': 'insurance'}}
    

    Or:

    class Goal(BaseModel):
        id: str
        meta: Meta_v2 = Field(Meta_v2(description="A customer goal", type="goal"))
    
    
    goal = Goal(id="1234")
    print(goal.model_dump())
    # {'id': '1234', 'meta': {'description': 'A customer goal', 'type': 'goal'}}
    

    Just note that I replaced _id with id, since Pydantic don't treat variables starting with _ as fields, as pointed in Private model attributes