Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 38 ยท Models and Types

Optional Fields and Defaults

Learn the difference between required, optional and nullable fields in Pydantic, how to set defaults, use default_factory, and avoid the mutable default trap.

Real data is rarely complete. A user may not have a phone number, a task may not have a due date, a request may leave out a page size. Pydantic gives you precise tools to describe this, and mixing up the three ideas of required, optional and nullable is the most common beginner mistake. This lesson separates them.

Three different questions

For any field you can ask two independent questions:

  1. Must the key be present? (required or not)
  2. May the value be None? (nullable or not)
Declaration Key required? None allowed?
name: str yes no
name: str | None yes yes
name: str = "x" no no
name: str | None = None no yes

The second row surprises many people. In Pydantic v2, Optional[str] and str | None mean "may be None", not "may be omitted". A field without a default is always required.

Python Required, nullable and optional

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Optional[X] from the typing module is simply another spelling of X | None. On modern Python prefer the | form.

Simple defaults

Any value can be a default. A field with a default can be left out, and the default is used. As you saw earlier, defaults are not validated unless you ask.

You can also write a default with Field(default=...), which is the form you need when you also want to add other metadata:

Python Field with a default

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

default_factory for fresh values

If a default is a list, dict or set, Pydantic makes a safe copy for every instance, so you do not hit the notorious Python shared-default bug. For values that must be computed at creation time, such as the current time or a new ID, use default_factory with a callable:

Python default_factory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Never write created: datetime = datetime.now(). That runs once, when the class is defined, so every instance would get the same timestamp. Use default_factory.

A factory may also take the already-validated data as its single argument, which lets one default depend on earlier fields:

Python Factory using other fields

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Telling "missing" from "null"

Sometimes the difference matters. In a partial update (a PATCH request) a client who sends {"bio": null} wants to clear the bio, while one who sends {} wants to leave it alone. Use model_fields_set or model_dump(exclude_unset=True):

Python Partial updates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Required fields that look optional

Sometimes you want a field with Field(...) metadata but still no default. Leave out default; the field stays required:

Python
from pydantic import BaseModel, Field

class Item(BaseModel):
    name: str = Field(min_length=1)       # required
    price: float = Field(gt=0)            # required

You will use Field heavily in Field Constraints. In older code you may see Field(...) with the literal ... (Ellipsis) as the first argument to mean "required"; it still works but is no longer needed.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does nickname: str | None (with no default) mean in Pydantic v2?

    A field with no default is required. The | None only widens the allowed values.
  2. 2. How do you declare an optional field that may be omitted and may be None?

    You need both the | None type and a default (usually None).
  3. 3. Why is created: datetime = datetime.now() a bug?

    Default expressions run at class-definition time. Use Field(default_factory=...) for per-instance values.
  4. 4. A PATCH body is {}. Which call gives you only the fields the client actually sent?

    exclude_unset drops everything that was not provided, so an explicit null is kept and a missing key is not.

Summary

  • Required vs optional is about the default; nullable is about | None. They are independent.
  • x: int | None = None is optional and nullable; x: int | None is required but nullable.
  • Use Field(default=...) for metadata and default_factory for values computed per instance (UUIDs, timestamps, lists).
  • Defaults are not validated unless validate_default=True.
  • model_dump(exclude_unset=True) separates "not sent" from "sent as null".

Next: Nested Models and Collections