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 ofNone
.
Implication:
- In the provided code, both
Bar
andBaz
models will have theira
attribute set toNone
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.
Python, DevOps, Data, Typing, PyCharm, ORM Michael Kennedy (@mkennedy) returns to the show to talk about Pydantic, a Python library that ...
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.
Python, DevOps, Data, Typing, PyCharm, ORM Michael Kennedy (@mkennedy) returns to the show to talk about Pydantic, a Python library that ...