Pydantic Class in Python: A Detailed Explanation
Introduction to Pydantic
Pydantic is a powerful Python library used for data validation and settings management. It leverages Python type hints to enforce data types and automatically validate and parse inputs. Pydantic is widely used in FastAPI and other modern Python applications where strict data validation is needed.
At the core of Pydantic is the BaseModel class, which allows developers to define data models with built-in validation.
1. Defining a Pydantic Class (BaseModel)
A Pydantic class is defined by inheriting from pydantic.BaseModel. Each attribute in the class is declared with a type hint, which Pydantic enforces.
Example: Basic Usage
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str
age: int
email: str
# Creating an instance
user = User(id=1, name="Alice", age=25, email="alice@example.com")
print(user)
Output:
id=1 name='Alice' age=25 email='alice@example.com'
Key Features in This Example:
- The
Userclass enforces the specified types (intforidandage,strfornameandemail). - When an instance of
Useris created, Pydantic validates the input data. - If invalid data is passed, Pydantic raises an exception.
2. Automatic Type Conversion and Validation
Pydantic automatically converts compatible data types.
Example: Automatic Type Conversion
user = User(id="123", name="Bob", age="30", email="bob@example.com")
print(user)
Output:
id=123 name='Bob' age=30 email='bob@example.com'
- The
idandagefields were passed as strings, but Pydantic converted them into integers.
Example: Validation Failure
user = User(id=1, name="Charlie", age="twenty-five", email="charlie@example.com")
Error Output:
ValidationError: 1 validation error for User
age
value is not a valid integer (type=type_error.integer)
- Since
"twenty-five"is not an integer, Pydantic raises aValidationError.
3. Adding Default Values and Optional Fields
You can define default values and optional fields using Python's Optional from typing.
Example: Defaults and Optional Fields
from typing import Optional
class User(BaseModel):
id: int
name: str
age: int = 18 # Default value
email: Optional[str] = None # Optional field
# Creating instances
user1 = User(id=2, name="David") # Uses default age=18, email=None
user2 = User(id=3, name="Emma", age=22, email="emma@example.com")
print(user1)
print(user2)
Output:
id=2 name='David' age=18 email=None
id=3 name='Emma' age=22 email='emma@example.com'
Key Features:
agehas a default value of18.emailis optional, and defaults toNoneif not provided.
4. Custom Validation Using Validators
Pydantic allows defining custom validation logic using @validator.
Example: Custom Validation
from pydantic import validator
class User(BaseModel):
id: int
name: str
age: int
email: str
@validator("age")
def validate_age(cls, value):
if value < 18:
raise ValueError("Age must be 18 or older")
return value
# Valid User
user = User(id=4, name="Frank", age=21, email="frank@example.com")
# Invalid User (raises an error)
user_invalid = User(id=5, name="Grace", age=16, email="grace@example.com")
Error Output:
ValidationError: 1 validation error for User
age
Age must be 18 or older (type=value_error)
5. Nested Models
Pydantic supports nested models, allowing complex data structures.
Example: Using Nested Models
from typing import List
class Address(BaseModel):
street: str
city: str
zip_code: str
class User(BaseModel):
id: int
name: str
address: Address # Nested Model
# Creating an instance
address = Address(street="123 Main St", city="New York", zip_code="10001")
user = User(id=6, name="Hannah", address=address)
print(user)
Output:
id=6 name='Hannah' address=Address(street='123 Main St', city='New York', zip_code='10001')
Key Features:
- The
Usermodel includes anAddressobject. - Pydantic automatically validates the nested fields.
6. Serialization & Conversion
Pydantic models can be easily converted to JSON or dictionaries.
Example: Convert to Dictionary
user_dict = user.dict()
print(user_dict)
Output:
{
"id": 6,
"name": "Hannah",
"address": {
"street": "123 Main St",
"city": "New York",
"zip_code": "10001"
}
}
Example: Convert to JSON
user_json = user.json()
print(user_json)
Output:
{"id":6,"name":"Hannah","address":{"street":"123 Main St","city":"New York","zip_code":"10001"}}
7. Performance Optimization with @dataclass Mode
For better performance, you can use Pydantic’s dataclass mode.
Example: Using @dataclass Mode
from pydantic.dataclasses import dataclass
@dataclass
class User:
id: int
name: str
age: int
user = User(id=7, name="Ivy", age=23)
print(user)
@dataclassmode makes Pydantic models more lightweight while still enabling validation.
8. Parsing Raw Data (JSON, Dictionaries)
Pydantic models can parse raw JSON data.
Example: Parsing JSON
json_data = '{"id": 8, "name": "Jack", "age": 30, "email": "jack@example.com"}'
user = User.parse_raw(json_data)
print(user)
Example: Parsing Dictionary
dict_data = {"id": 9, "name": "Kim", "age": 28, "email": "kim@example.com"}
user = User.parse_obj(dict_data)
print(user)
Conclusion
Pydantic simplifies data validation and serialization in Python by enforcing types using type hints. It offers:
- Automatic type conversion
- Custom validation with
@validator - Nested models
- Easy JSON and dict serialization
- Performance optimizations with
@dataclassmode
Pydantic is widely used in frameworks like FastAPI and configuration management systems due to its robust validation capabilities.
- Get link
- X
- Other Apps
- Get link
- X
- Other Apps
Comments
Post a Comment