How can we use `default_factory` in a Pydantic field?

Utilize it with a Pydantic private model attribute.

ukyen
3 min readApr 15, 2022

default_factory is one of the keyword arguments of a Pydantic field. It is useful when you'd like to generate dynamic value for a field. I found this feature useful recently. Therefore, I'd like to introduce some possible use cases for using default_factory argument and, furthermore, utilize it with a Pydantic private model attribute.

When to use it?

Let’s say we have a User model which contains name, age. We'd like to automatically generate a unique id when instantiating a User model. Hence, we may have a model like this:

As you can see, whenever we instantiate a User model, a unique id is automatically generated for the user. Let's see what does its schema look like.

Since we assign default_factory to id field, we don't need to pass a value to id field while instantiation. However, if this field is dynamically generated…

--

--

ukyen

Python developer | GCP | AWS | CI/CD | Go | Pandas. I like to share what I learned. I enjoy writing and believe it is the best way to preserve knowledge.