Use dataclasses and Pydantic models for data validation
✓Works with OpenClaudeYou are a Python developer specializing in modern data modeling. The user wants to create and validate data structures using both Python's built-in dataclasses and Pydantic models for type-safe, validated data handling.
What to check first
- Verify Python version is 3.7+ with
python --version(dataclasses added in 3.7) - Install Pydantic if not present:
pip install pydantic(for the Pydantic examples)
Steps
- Import
dataclassdecorator from thedataclassesmodule at the top of your file - Define a class and decorate it with
@dataclassto automatically generate__init__,__repr__, and__eq__methods - Declare class attributes with type hints; dataclass will use these as field definitions
- For basic validation beyond type hints, add a
__post_init__method to check field values after initialization - Import
BaseModelfrompydanticfor more robust validation with built-in error handling - Create a Pydantic model by subclassing
BaseModeland declaring typed attributes - Use field validators with
@field_validatordecorator (Pydantic v2) or@validator(v1) to add custom validation logic - Call the model constructor to trigger automatic validation; Pydantic raises
ValidationErroron invalid data
Code
from dataclasses import dataclass, field
from typing import Optional, List
from pydantic import BaseModel, field_validator, ValidationError
# === DATACLASS EXAMPLE ===
@dataclass
class Person:
name: str
age: int
email: Optional[str] = None
def __post_init__(self):
"""Validate after initialization"""
if self.age < 0:
raise ValueError("Age cannot be negative")
if self.email and "@" not in self.email:
raise ValueError("Invalid email format")
# Using dataclass
person1 = Person("Alice", 30, "alice@example.com")
print(person1) # Person(name='Alice', age=30, email='alice@example.com')
# === PYDANTIC MODEL EXAMPLE ===
class User(BaseModel):
username: str
age: int
email: str
tags: List[str] = field(default_factory=list)
@field_validator('age')
@classmethod
def age_must_be_positive(cls, v):
if v < 0:
raise ValueError('Age must be positive')
if v > 150:
raise ValueError('Age must be realistic')
return v
@field_validator('email')
@classmethod
def email_must_contain_at(cls, v):
if "@" not in v:
raise ValueError('Invalid email address')
return v
# Using Pydantic model with valid data
try:
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Python Skills
Other Claude Code skills in the same category — free to download.
Django Setup
Scaffold Django project with models, views, and URLs
Flask Setup
Scaffold Flask application with blueprints and extensions
FastAPI Setup
Scaffold FastAPI with async endpoints and auto-docs
Pytest Setup
Configure pytest with fixtures, plugins, and coverage
Python Venv
Set up Python virtual environments and dependency management
Poetry Setup
Set up Poetry for Python dependency and package management
Python Typing
Add comprehensive type hints and mypy configuration to Python code
Django REST Framework
Set up Django REST Framework with serializers and viewsets
Want a Python skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.