6

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 Answer 1

8

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)
Sign up to request clarification or add additional context in comments.

2 Comments

what if the function is within the Item class? How can I refer to it?
what if i want created_at as a timestamp? How would that work?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.