Pydantic model fields with typing.Optional[] vs. typing.Optional[] = None – Pydantic

by
Ali Hasan
llama-cpp-python pydantic python-typing springannotations

Quick Fix: To set the default value as None, one can either use the type annotation typing.Optional[T] or can use the equivalent typing.Optional[] = None. Both options result in the same functionality and are interchangeable.

The Solutions:

Solution 2: Updated for Pydantic v2

In Pydantic v2 released in 2023, the behavior of implicitly setting optional attributes has changed.

New Behavior in Pydantic v2:

  • Fields annotated with typing.Optional[] are now considered optional by default, even without explicitly assigning = None.
  • Fields annotated with Any no longer have a default value of None.

Implication:

  • In the provided code, both Bar and Baz models will have their a attribute set to None by default.
  • The @pydantic.validator will be called for both models, printing "WITHOUT NONE" and "WITH NONE" respectively.

Output:

print(Bar())
print(Baz())

Output:

WITHOUT NONE
{}
name='a' type=Optional[int] required=False default=None
a=None
WITH NONE
{}
name='a' type=Optional[int] required=False default=None
a=None

Q&A

What’s the difference between setting an optional parameter to ‘None’ with ‘typing.Optional[]’ vs. ‘typing.Optional[] = None’ in ‘Pydantic‘ models?

Functionally, there is no distinction. Both set the default value as ‘None’ if not specified otherwise.

What’s the reasoning behind setting the required property to False and the allow_none property to True when the field type is determined to be a union?

This inconsistency allows for optional fields with a ‘None’ default value, without requiring an explicit default declaration.

Video Explanation:

The following video, titled "Pydantic: Modern Python Data Validation and Settings by Michael ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Python, DevOps, Data, Typing, PyCharm, ORM Michael Kennedy (@mkennedy) returns to the show to talk about Pydantic, a Python library that ...