Please complete:
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] = uuid4
I don't expect that this would need to modify any existing functionalities. Probably just a need to create some sort of wrapper.
I'm hesitant about pseudo types, without reading the docs it's not clear what this does.
What we could do is just is the function as the default/initial value? Then unless the type of the field was Callable it would call the function to generate a value.
This would not be completely backwards, but I think it would be more intuitive.
This would work as well! The main idea would be to reduce the amount of boilerplate code required for this type of usage.
I think this might be better suited as a keyword argument to Schema (or Field now), or similar. That鈥檚 how this functionality is handled by both attrs and dataclasses.
I think this might be better suited as a keyword argument to Schema (or Field now), or similar. That鈥檚 how this functionality is handled by both attrs and dataclasses.
agreed.
Field(default_factory=...).For use of ts: datetime = datetime.now we should wait for v2.
Most helpful comment
1210 will implement
Field(default_factory=...).For use of
ts: datetime = datetime.nowwe should wait for v2.