$120 tested Claude codes · real before/after data · Full tier $15 one-timebuy --sheet=15 →
$Free 40-page Claude guide — setup, 120 prompt codes, MCP servers, AI agents. download --free →
clskills.sh — terminal v2.4 — 2,347 skills indexed● online
[CL]Skills_
PythonbeginnerNew

Python Dataclass

Share

Use dataclasses and Pydantic models for data validation

Works with OpenClaude

You 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

  1. Import dataclass decorator from the dataclasses module at the top of your file
  2. Define a class and decorate it with @dataclass to automatically generate __init__, __repr__, and __eq__ methods
  3. Declare class attributes with type hints; dataclass will use these as field definitions
  4. For basic validation beyond type hints, add a __post_init__ method to check field values after initialization
  5. Import BaseModel from pydantic for more robust validation with built-in error handling
  6. Create a Pydantic model by subclassing BaseModel and declaring typed attributes
  7. Use field validators with @field_validator decorator (Pydantic v2) or @validator (v1) to add custom validation logic
  8. Call the model constructor to trigger automatic validation; Pydantic raises ValidationError on 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

Quick Info

CategoryPython
Difficultybeginner
Version1.0.0
AuthorClaude Skills Hub
pythondataclasspydantic

Install command:

curl -o ~/.claude/skills/python-dataclass.md https://claude-skills-hub.vercel.app/skills/python/python-dataclass.md

Related Python Skills

Other Claude Code skills in the same category — free to download.

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.