Introduction to Pydantic
Pydantic is a powerful data validation and settings management library for Python. It leverages Python type hints to ensure data integrity, making your code more robust and reliable. This tutorial will guide you through the basics of Pydantic, including installation, creating models, and validating data.
Why Use Pydantic?
Pydantic offers several benefits:
- Data Validation: Automatically validates data against defined schemas.
- Type Hints: Utilizes Python type hints for data validation.
- Error Handling: Provides clear error messages when data validation fails.
- Performance: Fast and efficient, suitable for high-performance applications.
Installation
You can install Pydantic using pip (or your favourite package manager):
pip install pydantic
Creating a Simple Model
Let's create a simple data model to represent a person with attributes like name, age, address, and active status.
from pydantic import BaseModel
class Person(BaseModel):
name: str
age: int
address: str
is_active: bool
Validating Data
Pydantic will automatically validate the data when you create an instance of the model. If the data does not match the model definition, Pydantic will raise an error.
from pydantic import ValidationError
try:
person = Person(name="John Doe", age=30, address="123 Main St", is_active=True)
print(person) # Prints: name='John Doe' age=30 address='123 Main St' is_active=True
except ValidationError as e:
print(e)
Handling Validation Errors
If the data provided does not match the expected types, Pydantic will raise a ValidationError
. This helps in catching errors early in the development process.
from pydantic import ValidationError
try:
person = Person(name="John Doe", age="thirty", address="123 Main St", is_active=True)
except ValidationError as e:
print(e.json()) # [{"type":"int_parsing","loc":["age"],
# "msg":"Input should be a valid integer, unable to parse string as an integer",
# "input":"thirty",...}]
Advanced Features
Pydantic also supports more advanced features like custom validators, settings management, and complex nested models.
Custom Validators
You can define custom validation logic using the @field_validator
decorator.
from pydantic import BaseModel, field_validator
class Person(BaseModel):
name: str
age: int
address: str
is_active: bool
@field_validator('age')
def age_must_be_positive(cls, value):
if value <= 0:
raise ValueError('Age must be positive')
return value
try:
person = Person(name="John Doe", age=-30, address="123 Main St", is_active=True)
except ValidationError as e:
print(e.json()) # Prints: [{"type":"value_error","loc":["age"],"msg":"Value error, Age must be positive","input":-30,"ctx":{"error":"Age must be positive"},...}]
Nested Models
Pydantic allows you to nest models within each other, making it easy to manage complex data structures.
class Address(BaseModel):
street: str
city: str
zipcode: str
class Person(BaseModel):
name: str
age: int
address: Address
is_active: bool
address = Address(street="123 Main St", city="Anytown", zipcode="12345")
person = Person(name="John Doe", age=30, address=address, is_active=True)
print(person) # Prints: name='John Doe' age=30 address=Address(street='123 Main St', city='Anytown', zipcode='12345') is_active=True
Conclusion
Pydantic is a versatile and powerful library that simplifies data validation and settings management in Python. By leveraging type hints, it ensures data integrity and provides clear error messages, making your code more reliable and easier to maintain.