How to set the default value of the pydantic field to get the current time?

👏 Do not use default in this case, but use default_factory

The difference between the two is explained as follows:

:param default: since this is replacing the field’s default, its first argument is used
      to set the default, use ellipsis (``...``) to indicate the field is required
:param default_factory: callable that will be called when a default value is needed for this field
      If both `default` and `default_factory` are set, an error is raised.

❌ Let's take a look at the wrong example, that is, get the current time through default :

from datetime import datetime, timezone
from pydantic import BaseModel, Field
from typing import Optional
import time


def get_utc_now_timestamp() -> datetime:
    return datetime.utcnow().replace(tzinfo=timezone.utc)


class Struct(BaseModel):
    releaseDate: Optional[datetime] = Field(
        default=get_utc_now_timestamp()
    )


print(Struct().releaseDate)
time.sleep(1)
print(Struct().releaseDate)

You can see that both times are the same, which is not the desired result!

2022-01-27 14:16:23.876755+00:00
2022-01-27 14:16:23.876755+00:00

✅ Let's take a look at default_factory again:

from datetime import datetime, timezone
from pydantic import BaseModel, Field
from typing import Optional
import time


def get_utc_now_timestamp() -> datetime:
    return datetime.utcnow().replace(tzinfo=timezone.utc)


class Struct(BaseModel):
    releaseDate: Optional[datetime] = Field(
        default_factory=get_utc_now_timestamp
    )


print(Struct().releaseDate)
time.sleep(1)
print(Struct().releaseDate)

As you can see, the two times are 1 seconds apart, this is the desired result ❤️

2022-01-27 14:15:55.195409+00:00
2022-01-27 14:15:56.200775+00:00

universe_king
3.4k 声望680 粉丝