- Email must be a valid format
- Age must be positive
- Username must be 3-20 characters
- Price can’t be negative
Field() function lets you add these constraints.
The Field function
ImportField from pydantic and use it to add constraints:
name must be 1-100 characters, and age must be between 1 and 120.
String constraints
Control string length and format:min_length- Minimum number of charactersmax_length- Maximum number of characterspattern- Regular expression pattern to match
Numeric constraints
Control number ranges:gt- Greater thange- Greater than or equal tolt- Less thanle- Less than or equal to
Default values with Field
Set defaults while also adding constraints:Field descriptions
Add descriptions for documentation:Another example
Common Usage
Custom validators (80/20 overview)
Sometimes built-in constraints aren’t enough. Pydantic supports custom validators for business logic:cls (the class, since there’s no instance yet during validation) and v (the value being validated). Return the value to accept it, or raise ValueError to reject it.
Custom validators let you:
- Add business-specific validation logic
- Transform values (like normalizing to lowercase)
- Validate things that built-in constraints can’t handle
Real-world example
Here’s a model for a payment form:Common patterns
Email validation
URL validation
Constrained lists
JSON Schema generation
Pydantic can generate JSON Schema from your models. This is useful for API documentation and integration with other tools:Learn more
##Class Attributes in Dataclasses and Pydantic ModelsInstance Attributes vs Class Attributes
Instance Attributes (Fields)
These are the attributes that represent the data of each object.Dataclass
name and age are instance attributes.
Pydantic Model
name and age are instance attributes (also called model fields in Pydantic).
Class Attributes
Class attributes belong to the class itself rather than individual objects. For both dataclasses and Pydantic models, useClassVar from the typing module to declare class attributes.
Class Attributes in Dataclasses
school is not part of the constructor.
Class Attributes in Pydantic
What Happens Without ClassVar?
If you omit ClassVar, the attribute becomes an instance attribute (field).
Dataclass
school becomes part of every object.
Pydantic
school is a model field, it is included in serialization.
Summary
Key Takeaways
- Instance attributes store data for each object.
- Class attributes are shared across all objects.
- In both dataclasses and Pydantic, use
ClassVarto declare class attributes. - Attributes declared with
ClassVar:- Are not included in the constructor.
- Are not serialized.
- Are shared by all instances.
- Without
ClassVar, both dataclasses and Pydantic treat the attribute as an instance field.
Rule of Thumb
- Use normal type annotations (
name: str) for object data. - Use
ClassVarfor constants or values shared across all instances.
Practice & Exercises
To reinforce what you’ve learned, practice with these interactive notebooks:Follow-Along Practice
Practice setting up numeric constraints, string constraints, descriptions, defaults using Field(), and implementing custom validators with @field_validator.💻 VS Code | 🚀 Colab | 📥 Download
Practice Exercises
Test your knowledge with hands-on exercises defining Field value ranges, metadata descriptions, and writing custom validation conditions.💻 VS Code | 🚀 Colab | 📥 Download
What’s next?
You know how to validate individual fields. Next, let’s learn how to handle complex data with nested models.Nested Models
Learn how to handle complex, nested data structures.