Logo vun Pydantic

Pydantic

Organisatioun
CodeAtCode
pydantic

Use when validating and serializing Python data with Pydantic v2 - models, field and model validators, constrained and special types, TypeAdapter, discriminated unions, BaseSettings, or FastAPI integration

Iwwersiicht

EditeurCodeAtCode
Repositoryoss-ai-skills
Skill-Nummpydantic
Stären
30
Forks
3
Matgeliwwert Fichieren
6
LizenzGPL-3.0
Linken
  • Instruktiounen am Markdown-Format

    Eng SKILL.md-Datei, déi de Modell bei Bedarf luet, soudatt nëmmen Token ufalen, wann eng Ufro tatsächlech dozou passt.

  • Funktionéiert mat all LLM

    KI-Skills si reng Markdown, keen ubidderspezifesche Code. Dofir funktionéiert dëse Skill mat GPT, Claude, Gemini, Grok oder engem lokale Modell.

  • 6 matgeliwwert Dateien

    Skripten, Virlagen a Referenzen, déi de Modell beim Schaffe liese kann. D'Dateie kënnen nëmme gelies ginn a ginn ni ausgeféiert.

  • Open Source

    Vum CodeAtCode op GitHub verëffentlecht. Liest de Quelltext, ier Dir de Skill installéiert.

Installatioun

Installéiert de KI-Skill Pydantic an TypingMind, fir e mat all LLM ze benotzen, oder füügt en an en anere KI-Agent an, deen SKILL.md liest.

1

An TypingMind installéieren

TypingMind installéiert e Skill direkt aus sengem GitHub-Dossier — dobäi gëtt SKILL.md gelies, d'Ressourcedateie gi gebëndelt an d'Resultat gëtt lokal gespäichert.

  1. Maacht d'App op a gitt op Plugins → Skills.
  2. Wielt „Vun GitHub installéieren“.
  3. Pecht d'URL vum Skill-Dossier hei drënner an a bestätegt.
    https://github.com/CodeAtCode/oss-ai-skills/tree/master/frameworks/pydantic
  4. Aktivéiert de Skill an all Chat, an deem Dir e benotze wëllt.
Plugins → Skills → Skill afügen → Vu GitHub-URL, pecht dann d'URL vum Dossier an a klickt op Weider.
2

An engem anere KI-Agent installéieren

All KI-Agent, deen d'Format Agent Skills liest, kann dëse Skill benotzen — kopéiert den Dossier an de Skill-Verzeechnes vun deem KI-Agent.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/CodeAtCode/oss-ai-skills.git /tmp/oss-ai-skills
mkdir -p .claude/skills
cp -r /tmp/oss-ai-skills/frameworks/pydantic .claude/skills/pydantic
Start Claude Code nom Kopéieren nei, fir datt den neie Skill erkannt gëtt.

An TypingMind benotzen

Aktivéiert Pydantic an engem Chat vun TypingMind, an de Modell iwwerhëlt de Rescht. Den Numm an d'Beschreiwung stinn am System-Prompt. Soubal eng Ufro dozou passt, luet de Modell déi komplett Instruktioune selwer — Dir musst de Skill ni manuell opruffen, an et fale keng Token un, bis en tatsächlech benotzt gëtt.

De Modell luet Pydantic automatesch, soubal eng Ufro dozou passt.

Funktionéiert mat all KI-Modell

KI-Skills si reng Markdown-Instruktiounen amplaz vun ubidderspezifeschem Code. Dofir ass Pydantic net un de Modell gebonnen, fir deen de Skill geschriwwe gouf. Installéiert en eemol an TypingMind a benotzt e mat GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder engem lokale Modell, deen Dir selwer bedreift — alles mat Ären eegenen API-Keys.

  • Gëtt nëmme gelueden, wann et néideg ass

    De System-Prompt enthält nëmmen den Numm an d'Beschreiwung. D'Instruktioune gi bei der éischter passender Ufro gelueden, soudatt en onbenotzte Skill näischt kascht.

  • De Modell am lafende Chat wiesselen

    Well de Skill aus Instruktiounen amplaz vu Code besteet, funktionéiert en och no engem Modellwiessel — den nächste Modell liest déi selwecht SKILL.md-Datei.

Skill-Instruktiounen

Dëst ass den Inhalt vu SKILL.md, deen de Modell luet. Liest e virun der Installatioun — e Skill besteet aus Instruktiounen, déi Äre Modell befollegt.

Objective: Use this skill to prevent data-validation gaps and serialization bugs by enforcing boundary-level validation, Field constraints over manual checks, and v2 migration patterns that avoid silent coercion failures.

Pydantic

Data validation using Python type annotations.

Overview

Pydantic provides data validation and settings management using Python type hints. Validates at runtime and generates JSON Schema.

Source: https://docs.pydantic.dev/ | https://github.com/pydantic/pydantic

Installation

bash
pip install pydantic          # Core
pip install pydantic[email]   # Email validation
pip install pydantic orjson   # Best performance
pip install pydantic-settings # Settings management

Quick Start

python
from pydantic import BaseModel, Field

class User(BaseModel):
    id: int
    name: str
    email: str
    age: int | None = None

# Validation + coercion
user = User(id="1", name="John", email="john@example.com")  # id coerced to int

# From dict/JSON
user = User.model_validate({"id": 2, "name": "Jane", "email": "jane@example.com"})
user = User.model_validate_json('{"id": 3, "name": "Bob", "email": "bob@example.com"}')

# Serialization
data = user.model_dump()           # dict
json_str = user.model_dump_json()  # JSON string

Field Constraints

Compact examples—see validators.md for full reference.

python
from pydantic import BaseModel, Field
from typing import Optional, List

class ConstrainedModel(BaseModel):
    # Strings
    name: str = Field(min_length=1, max_length=100)
    username: str = Field(pattern=r'^[a-zA-Z0-9_]+$')
    
    # Numbers
    age: int = Field(ge=0, le=150)
    price: float = Field(gt=0)
    
    # Collections
    tags: List[str] = Field(min_length=1)
    
    # Optional
    nickname: Optional[str] = Field(default=None, max_length=50)

Validators

See validators.md for comprehensive patterns.

python
from pydantic import BaseModel, field_validator, model_validator, Field
import re

class ValidatedModel(BaseModel):
    username: str
    password: str
    
    @field_validator('username')
    @classmethod
    def validate_username(cls, v: str) -> str:
        if len(v) < 3:
            raise ValueError('Username must be at least 3 characters')
        return v.strip().lower()
    
    @model_validator(mode='after')
    def validate_password_strength(self):
        if len(self.password) < 8:
            raise ValueError('Password too short')
        if not re.search(r'[A-Z]', self.password):
            raise ValueError('Password needs uppercase')
        return self

v1 → v2 Migration Checklist

Critical: v2 changes can silently break v1 code. Check each item.

v1v2Symptom
@validator@field_validatorImport error; validator deprecated
@validator(..., each_item=True)@field_validator with PlainSerializerList validation fails
@root_validator@model_validator(mode='before'/'after')root_validator removed; need mode
class Configmodel_config = ConfigDict(...)Config class ignored
.dict().model_dump()Method not found
.json().model_dump_json()Method not found
.parse_obj().model_validate()Method not found
.parse_raw().model_validate_json()Method not found
.schema().model_json_schema()Method not found
Field(..., regex=r'...')Field(pattern=r'...')regex removed
Field(..., min_length=...)Field(min_length=...)Works (unchanged)
copy(update={...})model_copy(update={...})copy is shallow; use model_copy
allow_population_by_field_namepopulate_by_nameConfig key renamed
orm_modefrom_attributesConfig key renamed
Optional[X] = None default behaviorDefaults no longer filled for NoneNone stays None, not replaced

Source: https://docs.pydantic.dev/latest/migration/

Serialization Performance

Measure before optimizing: use timeit or a profiler on model_dump() for deeply nested models.

python
from pydantic import BaseModel
from typing import Optional, List
import time

class NestedModel(BaseModel):
    data: dict
    items: List[str]

class DeepModel(BaseModel):
    level1: NestedModel
    level2: NestedModel
    level3: NestedModel

model = DeepModel(
    level1=NestedModel(data={}, items=[]),
    level2=NestedModel(data={}, items=[]),
    level3=NestedModel(data={}, items=[])
)

# Measure
start = time.perf_counter()
for _ in range(10000):
    model.model_dump()
print(f"Time: {time.perf_counter() - start:.3f}s")

Guidance:

  • model_dump() vs dict(model): model_dump() is O(1) per field; dict(model) triggers reflection O(fields) each call. Always use model_dump().
  • model_dump(mode="json"): Use when the consumer is JSON (serializes datetime, decimals, etc. to JSON-native types).
  • exclude_none=True: Omits fields with None value. Use when you want to hide nulls.
  • exclude_unset=True: Omits fields that were never explicitly set (even if they have defaults). Usually what you want for partial updates.
  • Deeply nested models: The hot spot. Profile first; consider selective include/exclude or flattening.

Django Integration

See django.md for detailed patterns.

python
from pydantic import BaseModel, ConfigDict
from myapp.models import User as UserModel

class UserPydantic(BaseModel):
    model_config = ConfigDict(from_attributes=True)
    
    id: int
    username: str
    email: str

# Accept ORM objects
user_orm = UserModel.objects.get(id=1)
user_py = UserPydantic.model_validate(user_orm)  # from_attributes=True enables this

# DjangoChoices for enum validation
from django.db import models

class Status(models.TextChoices):
    PENDING = "pending"
    ACTIVE = "active"

# Must be TextChoices, not plain str for enum validation
from pydantic import BaseModel

class Task(BaseModel):
    status: Status  # Works with TextChoices

Pitfalls:

  • Unsaved instances: Validating an unsaved Django model instance may fail if validators expect id or other DB-generated fields.
  • Lazy model fields: Use DjangoGetter wrapper for lazy evaluation of related fields (avoids N+1 queries).

When Not to Use a Strict Model

Not every case benefits from Pydantic's coercion:

  • Internal dataclasses: Where data is already validated at the boundary, coercion surprises hurt more than help. Use @dataclass or plain classes internally.
  • Boundary discipline: Validate external input ONCE at the boundary. Internal call sites should not re-validate—pass typed data directly.
  • Performance-critical paths: If validation is not needed (e.g., internal cache hits), skip Pydantic overhead.
python
# Good: Validate at boundary
def handle_request(raw_data: dict):
    user = User.model_validate(raw_data)  # Boundary
    process_user(user)  # Internal—no re-validation

def process_user(user: User):
    # Use user directly; trust the type
    send_email(user.email)

# Bad: Re-validating internally
def process_user_bad(raw_data: dict):
    user = User.model_validate(raw_data)
    # ...
    user_again = User.model_validate(user.model_dump())  # Unnecessary

Best Practices

  1. Use Field(default_factory=...) for mutable defaults

    python
    class Model(BaseModel):
        tags: List[str] = Field(default_factory=list)  # Good
        # tags: List[str] = []  # Bad in v2
  2. Separate schemas for operations

    python
    class UserBase(BaseModel):
        email: str
    
    class UserCreate(UserBase):
        username: str
        password: str
    
    class UserResponse(UserBase):
        id: int
        model_config = ConfigDict(from_attributes=True)
  3. Validate once at the boundary (see above)

Common Issues

Mutable Defaults

python
# v2 error: mutable default
class BadModel(BaseModel):
    items: list = []

# Fix: use default_factory
class GoodModel(BaseModel):
    items: list = Field(default_factory=list)

Performance

  • Use Pydantic v2 (parsing is 10-100x faster than v1)
  • Use orjson for serialization: model_config = ConfigDict(json_loads=orjson.loads, json_dumps=orjson.dumps)
  • Measure model_dump() on deeply nested models first

Deep Dives

Load these reference files on demand:

  • validators.md — Field/model validators, custom types, error handling, TypeAdapter, discriminated unions
  • types-and-defaults.md — Field aliases, naming conventions, constrained types, special types (email, URL, UUID, secrets, enums)
  • config-and-settings.md — Model configuration, strict mode, multi-environment settings, BaseSettings

References

Matgeliwwert Fichieren

De Modell liest dës Dateie bei Bedarf, wärend de Skill gelueden ass. Si ginn als liesbar Dateie bereetgestallt a ginn ni ausgeféiert.

Heefeg gestallte Froen

Wat mécht de KI-Skill Pydantic?

Use when validating and serializing Python data with Pydantic v2 - models, field and model validators, constrained and special types, TypeAdapter, discriminated unions, BaseSettings, or FastAPI integration

Firwat Pydantic op TypingMind benotzen?

Well Dir en eemol installéiert a mat all Modell benotze kënnt. Pydantic besteet aus einfachem Markdown amplaz vun ubidderspezifeschem Code. Dee selwechte Skill funktionéiert also mat GPT-5, Claude, Gemini, Grok oder engem lokale Modell – an Dir kënnt de Modell matzen am Chat wiesselen, ouni datt de Skill ophält ze funktionéieren. TypingMind benotzt Är eegen API-Schlësselen, sou datt Dir d'Ubidder direkt bezuelt amplaz vun engem Abonnement pro Benotzerplaz. Är Skills a Chats bleiwen an Ärem eegene Späicher.

Wéi installéieren ech Pydantic an TypingMind?

Maacht an TypingMind Plugins → Skills → Vu GitHub installéieren op a setzt https://github.com/CodeAtCode/oss-ai-skills/tree/master/frameworks/pydantic an. TypingMind liest d'Datei SKILL.md, bündelt déi zougehéiereg Dateien an installéiert dat Ganzt als Skill, deen Dir pro Chat aktivéiere kënnt.

Wéi eng KI-Modeller kënnen Pydantic benotzen?

All Modell, deen Dir an TypingMind verbënnt. KI-Skills sinn einfach Markdown-Instruktiounen an net ubidderspezifesche Code. Dofir kënne GPT, Claude, Gemini, Grok a lokal Modeller dëse Skill lueden, wann eng Ufro dozou passt.

Wéi vill KI-Modeller kann ech mat Pydantic benotzen?

Esou vill Dir wëllt. Soulaang e Modell Skills ënnerstëtzt, kënnt Dir Pydantic domat benotzen – GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama a méi – alles op TypingMind mat Ären eegenen API-Schlësselen.

Ass de KI-Skill Pydantic gratis?

Jo. De Skill gëtt vum CodeAtCode ënner der Lizenz GPL-3.0 op GitHub publizéiert. Dir bezuelt nëmmen Ären eegene KI-Ubidder fir d'Token, déi Dir benotzt.

Wat si KI-Skills?

E KI-Skill ass e weiderverwendbaart Pak vun Instruktiounen, dat engem KI-Modell bäibréngt, wéi en eng bestëmmt Aufgab erfëllt. E follegt dem oppenen Agent Skills-Format: eng Datei SKILL.md mat engem Numm an enger Beschreiwung, plus all Scripten, Virlagen oder Referenzdateien, déi de Modell eventuell brauch. De Modell liest d'Instruktiounen eréischt, wann Är Ufro zum Skill passt. En installéierte Skill kascht also näischt, bis e benotzt gëtt.

Wéi ënnerscheede sech KI-Skills vu Plugins oder MCP-Serveren?

E Plugin oder MCP-Server gëtt engem Modell nei Tools, déi en opruffe kann – Code, deen iergendwou leeft an e Resultat zeréckgëtt. E KI-Skill gëtt dem Modell dogéint Wëssen an eng Virgoensweis: wéi en eng Aufgab ugeet, wéi eng Schrëtt en nokënnt a wéi eng gutt Ausgab ausgesäit. Skills bestinn aus einfachem Markdown, brauche kee Server, keen API-Schlëssel a keng Lafzäitëmfeld a funktionéiere mat all Modell.

All weisen

Elo Ären eegene KI-Workspace ariichten

Abonnéiert Iech op eisen Newsletter, fir iwwer nei Funktiounen an zukünfteg Gewënnspiller informéiert ze ginn 👇