Pydantic Models and Optional Fields
Does an Empty Note Mean the Field Was Omitted?
Pydantic is a Python library that checks incoming data against declared types and other rules. We describe a record in a model class, then ask the library to construct a validated instance or explain why the input does not satisfy it. A Pydantic model here is a data contract, not a machine learning model.
Suppose a report request must include a title and a note field. The note may be None, meaning the requester explicitly has no note. The number of copies may be omitted, in which case we use a declared default. These choices look similar in an informal description, but a program needs to distinguish them.
These pieces demonstrate selected field rules. They do not run Pydantic. JSON null represents Python None; the Python challenges check the full model.
Step 1 of 1
Two Questions for Every Field
Ask whether the caller must supply the key, then ask which values that key allows. These are Pydantic v2 declarations.
| Declaration | May omit the key? | May supply None? |
|---|---|---|
| title: str | No | No |
| note: str | None | No | Yes |
| comment: str | None = None | Yes; its default is None | Yes |
| status: str = 'draft' | Yes; its default is 'draft' | No |
title: str
- May omit the key?
- No
- May supply None?
- No
note: str | None
- May omit the key?
- No
- May supply None?
- Yes
comment: str | None = None
- May omit the key?
- Yes; its default is None
- May supply None?
- Yes
status: str = 'draft'
- May omit the key?
- Yes; its default is 'draft'
- May supply None?
- No
Describe One Record with a Model Class
Allowing null does not supply a missing key. The copies default applies only when copies is absent; it does not replace an explicit zero.
Required and Nullable Fields in Pydantic v2
BOTIE
The word optional caused a particular ambiguity. It might mean a key can be left out, or that its value can be None. Samuel Colvin’s 2022 plan for Pydantic v2 explicitly discussed separating these cases. In v2, allowing None without declaring a default does not make a field omittable. That distinction is the center of this lesson; older v1 examples can behave differently.
Sources for this history
Check a Note and Default the Copy Count
A report request must include note, even when the sender chooses null, meaning no note. If copies is absent, use 1. The supplied titles are already valid text.
BOTIE
The completed request or its error message
- title
- Inspection notes
- note
- null
- copies
- 1
Follow the operations
1. Report request
- title
- Inspection notes
- note
- null
2. Check one request field
- title
- Inspection notes
- note
- null
3. Default missing copies
- title
- Inspection notes
- note
- null
- copies
- 1
4. Result
- title
- Inspection notes
- note
- null
- copies
- 1
These pieces demonstrate selected field rules. They do not run Pydantic. JSON null represents Python None; the Python challenges check the full model.
1. Describe One Record with a Model Class
A dictionary can contain any keys. It does not tell the next function which fields to expect. A model class gives those fields a named definition. The class keyword introduces the definition, and BaseModel in parentheses tells Python that our class uses Pydantic’s model behavior.
Inside the indented class body, title: str declares a field named title whose validated value is text. It is a field declaration, not a local variable being read from a particular request. After defining the class, Dispatch.model_validate(data) checks one supplied value against it and returns a Dispatch instance when validation succeeds.
The returned instance represents one request. We read an attribute with dispatch.title, much as the dataclass lesson accessed a named field. Ordinary annotations and dataclasses do not automatically provide Pydantic’s validation. The behavior comes from this library and its BaseModel interface.
Keep the class definition separate from the incoming record. One describes the contract; the other is data being checked against it.
2. Separate Presence from Nullability
A field is required when the input must supply it. A field is nullable when None is one of its allowed values. A report can require a note field and still accept note=None. The key then communicates an explicit choice, rather than leaving the receiving program to guess.
The declaration note: str | None describes allowed values. It does not include a default. Pydantic v2 therefore rejects a record with no note key. The declaration comment: str | None = None adds a default and permits omission.
The typing spelling Optional[str] means str or None. It does not mean an argument or record field can automatically disappear. Keep that distinction consistent with the preceding optional-values lesson.
In the program below, the first request supplies note with a None value. The second request omits it and fails.
Supply None, Then Omit the Key
The same model receives both requests. The error is caught so the complete program can show both outcomes.
from pydantic import BaseModel, ValidationError
class Dispatch(BaseModel):
title: str
note: str | None
copies: int = 2
for data in [{'title': 'Weekly report', 'note': None}, {'title': 'Weekly report'}]:
try:
dispatch = Dispatch.model_validate(data)
print(dispatch.model_dump())
except ValidationError as error:
print([(item['loc'], item['type']) for item in error.errors()]){'title': 'Weekly report', 'note': None, 'copies': 2}
[(('note',), 'missing')]The model supplies copies because it has a default. It does not supply note because no default was declared.
Check yourself
Questions on Parts 1 and 2
Question 1 of 2
What does this note declaration require?
Question data
Pydantic v2 model field: note: str | None. No default is declared. Input: {"title":"Report"}. Assume title is another valid field.3. Choose a Default for Omission
A default answers a specific question: what should the receiving program use when the caller leaves this field out? copies: int = 2 supplies an integer when copies is absent. A caller can still provide a different acceptable integer.
The default does not generally replace an explicitly supplied invalid value. If copies cannot be None, supplying copies=None is a validation failure rather than a request to use the default. Otherwise a caller’s explicit choice could quietly turn into a different operation.
Choose defaults because they make sense for the application, not because a field is inconvenient to require. A default output directory, permission level, or send flag can have consequences. A missing value should sometimes remain an error.
Omission, an explicit None value, and an invalid value are different inputs. Test each one that your contract distinguishes.
4. Decide Whether Conversion Is Allowed
Data arriving from a text form often contains digits as strings. Pydantic’s ordinary validation can convert some representations, such as the string "3" into an int field. This is useful when conversion is part of the interface. It can also conceal that a producer is sending the wrong representation.
A strict int field or strict model rejects that string instead. ConfigDict(strict=True) in the model_config attribute makes that policy visible for the model. Strictness follows Pydantic’s rules for each type and input mode; it is not a universal exact-Python-type-identity test. For example, a strict float field can accept a Python integer.
The examples here validate Python dictionaries, not raw JSON. JSON has fewer native types, so some strict-mode rules differ when validating JSON directly. Use the documentation for the type and input mode you actually accept.
Choose coercion deliberately at the boundary. Later calculation code should not repeatedly guess whether a count is a string.
Make the Count Representation a Policy
A flexible integer field converts a text count. The strict model rejects the same representation.
from pydantic import BaseModel, ConfigDict, ValidationError
class FlexibleCount(BaseModel):
count: int
class StrictCount(BaseModel):
model_config = ConfigDict(strict=True)
count: int
print(FlexibleCount.model_validate({'count': '3'}).count)
try:
StrictCount.model_validate({'count': '3'})
except ValidationError as error:
print(error.errors()[0]['type'])3
int_typeThe strict error concerns the representation of the input. A positive-range check would be a separate rule.
5. Choose What Happens to Unknown Keys
A request might contain copes instead of copies. Pydantic models ignore extra fields by default. In a contract that is supposed to reject misspelled keys, this can make an input appear to work while a default is used instead of the intended value.
ConfigDict(extra="forbid") rejects unknown keys. The alternative extra="allow" deliberately retains them, while extra="ignore" deliberately discards them. Pick the behavior the interface promises. Forbidding extras is useful for a tightly specified request, but a forward-compatible event reader might choose another policy.
Requiredness is independent of this choice. Rejecting unknown keys does not make a declared field required, and allowing an unknown key does not satisfy a missing required one.
An explicit extra-field policy makes producer mistakes easier to diagnose. It does not prove the allowed fields express the right business operation.
6. Read and Export a Validated Instance
Once validation succeeds, use the returned instance. Read request.title as an attribute. When ordinary Python code needs a dictionary, request.model_dump() produces a representation of the model’s fields. This is different from continuing to process the original unchecked dictionary.
The model may contain defaults or converted values, so its data can differ from the original input. Returning the raw input after validation would discard that work. For nested models, model_dump also exports their fields into dictionaries; the next lesson uses that behavior explicitly.
model_dump is not a promise that every Python value is ready for every external format. Pydantic has separate serialization options, including JSON output. Here the examples contain only ordinary text, integers, and None.
Use the validated value as the boundary between the producer’s representation and the rest of the program.
7. Keep Track of What the Caller Supplied
A model can show the same final None value for an omitted optional comment and for an explicit comment=None. Sometimes the distinction matters. A patch request might leave an existing comment alone when the key is absent, but clear it when the key is present with None.
The model_fields_set attribute records which fields were explicitly supplied. Test whether "comment" is in that set instead of inferring presence from the final value. model_dump(exclude_unset=True) is another way to export only explicitly supplied fields when that matches an interface.
This is a presence distinction, not a truthiness test. Empty text, zero, False and None can each be meaningful values. A condition such as if comment cannot tell you whether the key was present.
The ticket exercise asks you to return the final comment and a separate presence flag. That keeps the two questions visible.
8. Handle Validation Failure at the Boundary
Pydantic raises ValidationError when input data fails its declared checks. Catch that exception around the validation call when this layer can return useful input feedback. Its errors() method supplies structured details such as the field location and error type.
A validation failure is different from a bug in the code that runs afterward. Keep the try block narrow. If a later calculation contains a NameError or another programming defect, do not label it “invalid request” by catching Exception around the whole handler.
Error details can contain submitted values. errors(include_input=False) omits the input entry from the structured error details. ConfigDict(hide_input_in_errors=True) changes the human-readable error display; it does not make the default errors() output input-free. Neither option automatically sanitizes a custom message or context. Select the field locations and error categories a caller needs instead of logging whole payloads or secrets.
Catching ValidationError gives input failures a deliberate path while allowing unrelated defects to remain visible.
9. What a Successful Model Does Not Establish
This first model checks representations and presence. A title containing only spaces can still satisfy a plain str field. A negative number can satisfy a plain int field. We need additional constraints when those values are unacceptable.
Validation also cannot establish that a requester owns a document or that a measurement is true. Those questions require authorization or knowledge outside this record. In a later lesson, keep a Pydantic request for an agent tool separate from the permission check that decides whether the tool may act.
A successful validation describes the checked instance at that point. Ordinary Pydantic models can subsequently be changed. The constraints lesson explains assignment checks and why trusted update shortcuts are not fresh validation.
A clear contract names exactly what has been checked, so the next layer knows what remains its responsibility.
Check yourself
Questions on Parts 1 to 9
Question 1 of 6
Which result matches the declared representation policy?
Question data
A strict Pydantic model declares count: int. Its input dictionary contains {"count":"3"}.Try it with Botie
Build with Botie
Write and run Python