Pydantic Constraints and Validators
Field and Model Validation in Pydantic v2
BOTIE
Pydantic’s 2022 v2 design described a tree of validators and separate ways to apply custom checks. The resulting v2 interfaces distinguish checks on one field from checks on a completed model. This is a useful engineering distinction even without the library: a rule about one count needs that count, while a rule comparing two endpoints needs both endpoints.
The Endpoints Are Numbers. Is the Range Usable?
Botie is asked to collect readings within a declared range. The lower endpoint is larger than the upper endpoint. Both values are numbers, so a type check alone accepts their representations. We still have no usable interval.
Some rules concern one field, such as a positive count. Others concern a relationship, such as lower being smaller than upper. We will put each rule where its inputs are available, then decide how the caller receives a rejected request.
This workshop checks the interval and count only. Real Pydantic, nested fields and strict Python numeric types are tested in the coding challenges.
Step 1 of 1
Give Each Rule the Information It Needs
The capture request contains a name, a count and a nested bounds record.
| Requirement | Inputs needed | Where we declare it |
|---|---|---|
| Count is positive and no greater than the limit | count | Field constraints |
| Name contains text after stripping outer whitespace | name | A field validator |
| Lower endpoint is smaller than upper endpoint | bounds.lower and bounds.upper | A model validator on Bounds |
| Every omitted label list starts independently | No caller value was supplied | A default factory |
Count is positive and no greater than the limit
- Inputs needed
- count
- Where we declare it
- Field constraints
Name contains text after stripping outer whitespace
- Inputs needed
- name
- Where we declare it
- A field validator
Lower endpoint is smaller than upper endpoint
- Inputs needed
- bounds.lower and bounds.upper
- Where we declare it
- A model validator on Bounds
Every omitted label list starts independently
- Inputs needed
- No caller value was supplied
- Where we declare it
- A default factory
Give a Nested Record Its Own Contract
Both endpoints can be numbers and still form an unusable interval. The count has its own limit, independent of the interval width.
Check the Interval and Number of Readings
A capture asks for 4 readings between 2 and 9. The lower endpoint must be below the upper endpoint, and the count must be a whole number from 1 through 20.
BOTIE
The checked interval and count, or an error message
- lower
- 2
- upper
- 9
- count
- 4
Follow the operations
1. Capture interval
- lower
- 2
- upper
- 9
2. Check the capture interval
- lower
- 2
- upper
- 9
3. Requested number of readings
4
4. Check the capture count
4
5. Prepare the capture
- lower
- 2
- upper
- 9
- count
- 4
6. Result
- lower
- 2
- upper
- 9
- count
- 4
This workshop checks the interval and count only. Real Pydantic, nested fields and strict Python numeric types are tested in the coding challenges.
1. Give a Nested Record Its Own Contract
A capture request contains a bounds record with lower and upper endpoints. A nested dictionary keeps those values together, but it does not check them. Define Bounds as a BaseModel, then declare bounds: Bounds inside CaptureRequest.
When the outer model validates an ordinary input dictionary, Pydantic validates that nested record too. The returned request.bounds is a Bounds instance. Its fields can be accessed as request.bounds.lower and request.bounds.upper.
Define the nested class before the class that refers to it in these examples. This makes the dependency visible and avoids introducing forward references while we are learning the basic structure.
The nested contract belongs to the range itself. Another request can reuse it when it genuinely needs the same range rules.
2. Attach Simple Limits to Fields
Field adds constraints to a declaration. count: int = Field(gt=0, le=20) requires an integer greater than zero and no greater than the stated maximum. These comparisons have different boundaries; test a value exactly at each boundary as well as a value outside it.
The strict model configuration rejects text and booleans for this integer field. The float endpoints use strict float validation and allow_inf_nan=False. Strict floats can accept Python integers and produce float values, so strict does not mean that every field requires literal type identity. Nonfinite endpoints must be rejected because they would not describe this ordinary finite interval.
A constraint is a policy we chose for this capture service. A different service can legitimately allow an empty collection or a larger count. Keep the reason for each limit in the explanation and tests.
Capture count: a whole number above 0 and at most 20
Bounds: finite numeric endpoints
Relationship: lower < upperA field can have the right representation while lying outside its permitted range.
Check yourself
Questions on Parts 1 and 2
Question 1 of 2
What does the nested model declaration allow Pydantic to do?
Question data
A request field declares bounds: Bounds. Bounds declares lower: float and upper: float. The input bounds value is {"lower":2,"upper":9}.3. Normalize One Field with a Field Validator
A name consisting of spaces technically contains characters, but it does not identify this capture. We want to remove surrounding whitespace and reject a name that is then empty. A field validator receives that field’s value and returns its accepted or normalized replacement.
The @field_validator line decorates the method below it, telling Pydantic which field to process. mode="after" runs the method after the normal field validation, so value is already text here. @classmethod gives the method the class as cls. The method still needs to return the value it wants stored.
Raise ValueError for a deliberate input rejection. Do not raise ValidationError yourself. Pydantic collects appropriate validator failures into its structured validation error. A TypeError caused by a programming mistake inside a v2 validator is not automatically converted into ValidationError.
A validator is ordinary Python code with a specific role. A missing return or a bad function call is still a programming defect.
4. Compare Fields with a Model Validator
The relationship lower < upper cannot be decided from either endpoint alone. An after model validator receives the constructed Bounds instance and can compare its fields. It returns self when the relationship is acceptable and raises ValueError when it is not.
The Self return annotation describes an instance of the containing class. It does not perform validation. The comparison and the explicit raise enforce the relationship. Notice that the method is an instance method; it does not use the @classmethod decorator that our field validator used.
Keep validation free of external effects. A range check should not write a file or reserve equipment before another field has finished validating. Validating a request and carrying out the request remain separate operations.
Run the complete program and compare the accepted range with a reversed one.
Validate a Complete Capture Request
The name is normalized, the integer endpoints become floats, and the reversed range is reported at its nested location.
from typing import Self
from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator, model_validator
class Bounds(BaseModel):
model_config = ConfigDict(strict=True, extra='forbid')
lower: float = Field(allow_inf_nan=False)
upper: float = Field(allow_inf_nan=False)
@model_validator(mode='after')
def ordered(self) -> Self:
if self.lower >= self.upper:
raise ValueError('lower must be smaller than upper')
return self
class CaptureRequest(BaseModel):
model_config = ConfigDict(strict=True, extra='forbid')
name: str = Field(min_length=1)
count: int = Field(gt=0, le=20)
bounds: Bounds
labels: list[str] = Field(default_factory=list)
@field_validator('name', mode='after')
@classmethod
def clean_name(cls, value: str) -> str:
value = value.strip()
if not value:
raise ValueError('name must contain non-whitespace text')
return value
request = CaptureRequest.model_validate({'name': ' North ', 'count': 3, 'bounds': {'lower': 2, 'upper': 9}})
print(request.model_dump())
try:
CaptureRequest.model_validate({'name': 'South', 'count': 3, 'bounds': {'lower': 9, 'upper': 2}})
except ValidationError as error:
print([(item['loc'], item['type']) for item in error.errors()]){'name': 'North', 'count': 3, 'bounds': {'lower': 2.0, 'upper': 9.0}, 'labels': []}
[(('bounds',), 'value_error')]The range rule belongs to Bounds. The outer request reports that nested model’s failure instead of starting a capture.
5. Create Independent Defaults
A list is mutable. When a caller omits labels, we want a fresh list for that request. Field(default_factory=list) calls list to produce the default instead of expressing an accidentally shared object policy.
Pydantic does copy certain non-hashable defaults, so its field behavior is not identical to an ordinary function’s default argument. A default factory still states the intended construction clearly. The mutation lesson examines ordinary Python defaults and shallow copies in more detail.
Defaults are not validated by Pydantic unless default validation is enabled for the field or model. Keep a literal default valid, or deliberately enable validate_default when a generated/default value also needs to pass the contract.
The two model instances below do not acquire each other’s labels.
Add a Label to Only One Request
Both instances omit labels. Their default lists are independent.
from pydantic import BaseModel, Field
class Notes(BaseModel):
labels: list[str] = Field(default_factory=list)
first = Notes()
second = Notes()
first.labels.append('review')
print(first.labels)
print(second.labels)['review']
[]The second instance remains empty after the first one changes.
6. Return Input Errors without Swallowing Defects
A caller that accepts a batch can validate each record inside a narrow try block. Catch ValidationError for that record, record its position and the relevant field locations, then move on if partial acceptance is the stated policy. Keep successful validated records in a separate collection.
Do not catch every exception and call it an invalid row. A misspelled variable or a broken validator needs to be diagnosed as code, not presented as a producer’s bad input. TypeError escaping a v2 validator is one example of why the exception category matters.
Pydantic error details may include the submitted input. Our batch exercise returns row numbers and field paths rather than echoing whole records. A public application should choose its error response and logging policy with the data’s sensitivity in mind.
A useful batch report tells the producer what needs correction while keeping failures in the program visible to developers.
7. A Validated Instance Can Be Changed Later
Ordinary assignment is not revalidated by default. A model that passed when it was constructed can later receive an unsuitable attribute value. ConfigDict(validate_assignment=True) requests assignment validation, which can help with ordinary attribute updates.
That setting is not a general immutability or transaction guarantee. Mutating a nested list does not assign the attribute again. Complex model-level update checks also deserve tests for their failure-state behavior. For a critical update, construct and validate a complete candidate from fresh data before replacing the previous accepted value.
model_construct deliberately bypasses validation for trusted data. model_copy(update=...) also trusts the update rather than validating it. Do not use those methods to ingest a new external request. The small program below makes the bypass visible even on a class that validates ordinary assignment.
Choosing a trusted-data shortcut means the caller, not Pydantic, is responsible for that data.
Compare Ordinary Assignment with Trusted Updates
A simple positive-count rule illustrates the difference. The code catches its expected assignment error.
from pydantic import BaseModel, ConfigDict, Field, ValidationError
class OrdinaryCount(BaseModel):
count: int
class CheckedCount(BaseModel):
model_config = ConfigDict(validate_assignment=True)
count: int = Field(gt=0)
ordinary = OrdinaryCount(count=2)
ordinary.count = 'many'
print(type(ordinary.count).__name__)
checked = CheckedCount(count=2)
try:
checked.count = -1
except ValidationError:
print('assignment rejected')
print(type(CheckedCount.model_construct(count='many').count).__name__)
print(type(checked.model_copy(update={'count': 'many'}).count).__name__)str
assignment rejected
str
strThe final two values entered through deliberate validation bypasses. They are not evidence of successful count validation.
8. Keep the Contract within Its Scope
A well-formed capture request can still name a nonexistent sensor. Its requested interval might be inappropriate for the physical device. A requester might lack permission to start a capture. Those checks depend on information outside this schema.
The boundary contract gives later code a declared representation and local value rules. Authorization, current device state and the decision to perform the effect remain separate responsibilities. Keeping them separate also makes each one easier to test.
The workshop below exposes a few local range and count checks as building blocks. The Python exercises use real Pydantic, including a nested model and custom validators. The workshop is not a substitute implementation of the library.
Name the evidence precisely: this request satisfied these declared validation rules at this point in the program.
Check yourself
Questions on Parts 1 to 8
Question 1 of 7
Which failure is the custom validator addressing?
Question data
A Bounds model has finite lower and upper float fields. Its after model validator rejects lower >= upper. The supplied endpoints are lower=9 and upper=2.Try it with Botie
Build with Botie
Write and run Python