Pydantic set attributes with a default function

Viewed 2410

Is it possible to pass function setters for immutable Pydantic Models.

For example:

from uuid import uuid4, UUID
from pydantic import BaseModel
from datetime import datetime

def generate_uuid():
    return uuid4()

def get_datetimenow():
    return datetime.now()

class Item(BaseModel):

    class Config:
        allow_mutation = False
        extra = "forbid"

    id: UUID
    created_at: datetime

I want the methods generate_uuid and get_datetimenow to set the attributes.

>>> Item()
ValidationError: 2 validation errors for Item
id
  field required (type=value_error.missing)
created_at
  field required (type=value_error.missing)

While I want to get an Item object with id and created_at automatically set. Identical result as when you run:

>>> Item(id=generate_uuid(), created_at=get_datetimenow())
Item(id=UUID('8f898730-3fad-4ca9-9667-c090f62a2954'), created_at=datetime.datetime(2021, 1, 19, 21, 13, 7, 58051))
1 Answers

You can use default_factory parameter of Field with an arbitrary function. Like so:

from uuid import uuid4, UUID
from pydantic import BaseModel, Field
from datetime import datetime

class Item(BaseModel):

    class Config:
        allow_mutation = False
        extra = "forbid"

    id: UUID = Field(default_factory=uuid4)
    created_at: datetime = Field(default_factory=datetime.now)
Related