Pydantic: Simplify setting dynamic default values

Created on 5 Oct 2019  路  5Comments  路  Source: samuelcolvin/pydantic

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] = uuid4

I don't expect that this would need to modify any existing functionalities. Probably just a need to create some sort of wrapper.

feature request

Most helpful comment

1210 will implement Field(default_factory=...).

For use of ts: datetime = datetime.now we should wait for v2.

All 5 comments

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.

1210 will implement Field(default_factory=...).

For use of ts: datetime = datetime.now we should wait for v2.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

krzysieqq picture krzysieqq  路  3Comments

AlbertMukhammadiev picture AlbertMukhammadiev  路  3Comments

vvoody picture vvoody  路  3Comments

ashpreetbedi picture ashpreetbedi  路  3Comments

sbv-trueenergy picture sbv-trueenergy  路  3Comments