Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Pydantic Optional Fields: Defaults & default_factory

Learn how to define optional fields in Pydantic, what `Optional[T]` actually means, and how `default_factory` differs from a plain `default` for mutable default values.

~4 min readPython
#Pydantic#Python#Optional Fields#Default Values
Diagram showing a Pydantic model with an optional field using default_factory to generate a fresh mutable default.

Optional fields in Pydantic are easy to declare, but the choice between a plain default and default_factory affects validation and runtime behavior. This article explains what Optional[T] means, when a field is truly optional, and when to use default_factory for mutable or dynamic defaults.

What Does Optional Mean in Pydantic?

In Pydantic, an optional field is one that accepts None as a value. You declare it using Optional[T] from typing, which is equivalent to Union[T, None]. In Python 3.10+, you can also write T | None. However, Optional[T] alone does not make the field optional in the sense of being omittable. A field declared as Optional[int] without a default is still required—it must be present in the input, but it may be None.

python
from typing import Optional from pydantic import BaseModel class User(BaseModel): nickname: Optional[str] # required, but can be None

If you try to instantiate User without nickname, Pydantic raises a validation error. To make the field truly optional (that is, not required), you must provide a default value, typically None.

python
class User(BaseModel): nickname: Optional[str] = None # not required, defaults to None

Now User() is valid and nickname is None. This is the most common way to declare an optional field, but it has a subtle limitation when the default is a mutable object like a list or dict.

Default Values vs default_factory

The default parameter in Pydantic's Field function (or simply assigning a value in the class body) sets a static default. This works fine for immutable types like int, str, or None. For mutable defaults, using a plain class-body assignment is less predictable because Pydantic's behavior has changed across versions. The explicit, documented way to create a fresh mutable value for each instance is default_factory.

python
class ShoppingCart(BaseModel): items: list[str] = [] # avoid relying on this for mutable defaults

If you write the above, Pydantic may copy or share the default depending on the version. Rather than depending on that behavior, use default_factory:

python
from pydantic import BaseModel, Field class ShoppingCart(BaseModel): items: list[str] = Field(default_factory=list)

Now each cart gets its own empty list. The same pattern works for dicts, sets, and any custom mutable type.

Using default_factory for Mutable Defaults

default_factory is not limited to built-in types. You can pass any zero-argument callable, including a lambda or a function you define.

python
from datetime import datetime, timezone def utc_now() -> datetime: return datetime.now(timezone.utc) class Event(BaseModel): created_at: datetime = Field(default_factory=utc_now)

Here, each Event instance gets the current UTC time at creation. If you used default=datetime.now(timezone.utc), the timestamp would be fixed at class definition time, which is rarely what you want.

default_factory also works with Pydantic's Field for more complex defaults, such as a list of dictionaries:

python
class Order(BaseModel): line_items: list[dict] = Field(default_factory=list)

When the field is omitted, the factory is called. When the field is provided, the factory is not called—the provided value is validated and used.

Common Pitfalls and Edge Cases

One common mistake is using default_factory on a field that you want to require. If you give a field a default_factory, it becomes optional—Pydantic will not require it. If you want the field to be required, do not give it a default or a factory.

Another edge case is combining Optional[T] with default_factory. For example:

python
class Config(BaseModel): tags: Optional[list[str]] = Field(default_factory=list)

This field is optional and defaults to an empty list, not None. If you want the default to be None, use default=None instead. The choice depends on your domain: do you want a missing field to become an empty collection, or a None that signals absence?

When the field is omitted, default_factory is called at instance creation, not at class definition. This means it can depend on runtime state, such as environment variables or current time, without causing shared state issues.

Runtime Behavior and Validation

When you instantiate a Pydantic model, validation runs on the provided data. For fields with a default_factory, the factory is invoked only if the field is absent from the input. If the field is present, its value is validated against the declared type. This means the factory is not called for every instance—only when needed.

The factory itself is not validated. What happens to its return value depends on Pydantic's validate_default setting: by default, default values and factory results are not validated. If you want an invalid factory result to raise an error, enable Pydantic's validate_default model config option.

Another subtle behavior: default_factory is evaluated per instance. This is different from default, which is evaluated once at class definition. For immutable defaults, the difference is negligible. For mutable or dynamic defaults, default_factory is the correct choice.

Performance and Maintainability Considerations

Using default_factory has a tiny runtime cost: the callable is invoked each time a new instance is created without that field. For most applications, this overhead is negligible. However, if you have a model with many fields that each use a factory, and you create millions of instances, the cumulative cost can matter. In such cases, consider whether a simple immutable default (like None or a constant) is acceptable.

From a maintainability perspective, default_factory makes the default behavior explicit and testable. You can unit-test the factory independently. It also avoids relying on mutable-default behavior that has caused subtle bugs in some versions. When reviewing code, prefer default_factory for any mutable default, and reserve default for immutable values.

One more consideration: if your factory is expensive (for example, it reads from a database), be aware that it runs on every instance creation where the field is omitted. You might want to cache the result if the value is truly constant across instances, but then you would lose per-instance freshness. The right tradeoff depends on your use case. For most models, a simple list or dict factory is cheap and safe.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.