-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Closed
Labels
Milestone
Description
Feature Request
Please complete:
- OS: Windows
- Python version 3.7.4 (default, Aug 9 2019, 18:34:13) [MSC v.1915 64 bit (AMD64)]
- Pydantic version: 0.30
Feature Request
Currently, if I want to have a dynamic default value, it has to be done the following way:
from datetime import datetime
from pydantic import BaseModel, validator
from uuid import UUID, uuid4
class DemoModel(BaseModel):
ts: datetime = None
id: UUID = None
@validator('id', pre=True, always=True)
def set_id(cls, v):
return v or uuid4()
@validator('ts', pre=True, always=True)
def set_ts_now(cls, v):
return v or datetime.now()This is fine for cases where actual validation has to be provided, however, in many cases like the one portrayed below, this leads to unnecessary code, especially if there are multiple dynamically set values. For instance, a timestamp and an id.
It would be great to be able to replace this usage pattern by a pydantic field called Dynamic for instance such that one can pass a callable as a default value. This would look like this:
from datetime import datetime
from uuid import UUID, uuid4
from pydantic import BaseModel, validator, Dynamic
class DemoModel(BaseModel):
ts: Dynamic[datetime] = datetime.now
id: Dynamic[UUID] = uuid4I don't expect that this would need to modify any existing functionalities. Probably just a need to create some sort of wrapper.
Bobronium, senpos, dannymilsom, heckad, dmig-alarstudios and 29 moreantonwnk