pydantic
БесплатноБез исполняемых скриптовНе проверенPydantic is a Python data validation and serialization library, based on type hints. Use this skill whenever you need to do relatively complex data modeling…
от pydantic★ 162 звезды на GitHubОб этом скилле
Pydantic Validation
In a nutshell, Pydantic is dataclasses with runtime validation. It leverages type hints to understand how validation (and serialization) should be performed. It is mostly useful when dealing with external untrusted data, for example when defining an HTTP API.
It is generally not recommended to use Pydantic to define classes that are instantiated within the user code. By doing so, you will lose flexibility (e.g. you cannot use types not supported by Pydantic, and it is harder to perform post-init changes). It is usually better to use vanilla classes (or standard library dataclasses) in this case, as a static type checker will already catch type mismatches.
Basic usage
Here is a simple example of using a Pydantic model:
from datetime import date
from pydantic import BaseModel, Field
class Person(BaseModel):
name: str
age: int = Field(description='The age of the person')
birthdate: date | None = None
p = Person(name='John', age=20, birthdate='1970-01-01')
Pydantic coerces compatible input: the ISO date string '1970-01-01' is parsed into a date.
Constraints and field metadata
The Field() function is used to provide metadata and constraints.
You need to distinguish two types of metadata:
- field specific metadata: metadata such as
deprecatedandalias, that only have meaning when attached to a field. - type specific metadata: this includes constraints such as
gt,max_length, and also metadata that affects the JSON Schema (e.g.description,title).
Model fields are declared with Field() using the assignment form:
from pydantic import BaseModel, Field
class User(BaseModel):
first_name: str = Field(alias='name')
or using the annotated pattern:
from typing import Annotated
from pydantic import BaseModel, Field
class Model(BaseModel):
value: Annotated[int, Field(deprecated=True)] = 1
The annotated pattern has some advantages:
- Using the
f: <type> = Field()form (no default) can be confusing and might trick users into thinkingfhas a default value, while in reality the field is still required. - You can provide an arbitrary amount of metadata elements for a field. As shown in the example above,
the
Field()function only supports a limited set of constraints/metadata, and you may have to use different Pydantic utilities such asWithJsonSchemain some cases.
But note that:
You should use the assignment form for metadata that has a meaning for static type checkers. This includes:
alias,defaultanddefault_factory.field specific metadata can only be used on the "top-level" type. A common pitfall is to do the following:
from typing import Annotated from pydantic import BaseModel, Field class Model(BaseModel): field_bad: Annotated[int, Field(deprecated=True)] | None = None field_ok: Annotated[int | None, Field(deprecated=True)] = Nonefield specific metadata should apply to the whole union in this example.
Constraints
As much as possible, use the "built-in" validation constraints, instead of defining custom validators:
from typing import Annotated
from annotated_types import Gt # annotated_types is an alternative to the `Field()` function.
from pydantic import BaseModel, field_validator
class Model(BaseModel):
constrained_int_ok: Annotated[int, Gt(1)] # This is good
constrained_int_bad: int
@field_validator('constrained_int_bad') # This is bad
@classmethod
def validate(cls, v: int) -> int:
if not v > 1:
raise ValueError('Value is not greater than 1')
return v
Sometimes, constraints can't be expressed using the Field() function. For example, string constraints such
as strip_whitespace, to_upper, to_lower and ascii_only can only be specified using pydantic.StringConstraints:
from typing import Annotated
from pydantic import BaseModel, StringConstraints
class Model(BaseModel):
# Do this instead of a validator calling s.strip():
a: Annotated[str, StringConstraints(strip_whitespace=True)]
https://pydantic.dev/docs/validation/latest/api/pydantic/standard_library_types/ is the canonical documentation for all supported standard library types and their constraints.
Validators
In some cases, you may have to use custom validators. As much as possible, use after validators. Because they run after Pydantic validation, the value is already the field's type. If you use before validators, the input data can literally be anything, so it is more error-prone (especially for model validators, the input isn't necessarily a dict, it can also be an arbitrary object).
If possible, prefer using the annotated pattern for validators:
from typing import Annotated
from pydantic import AfterValidator, BaseModel, field_validator
def is_even(value: int) -> int:
if value % 2
Установить pydantic в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл pydantic?
Pydantic is a Python data validation and serialization library, based on type hints. Use this skill whenever you need to do relatively complex data modeling using Pydantic, e.g. when adding constraints, defining a model hierarchy with subclasses, etc.
Как установить скилл pydantic?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл pydantic запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic