/python:pydanticfrom python
Use when writing or reviewing pydantic models, adapters, validators, serializers, or settings, covering validation and schemas at untrusted boundaries
Ships in python. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
[REFERENCES]:
Frozen models validate untrusted input once and hold the validated data. faulted serves every pydantic boundary: type picks the reason, loc or error.title the subject, a SettingsError becomes one fault's cause:
def fault(title: str, detail: ErrorDetails, /) -> Fault:
match detail["type"], detail["loc"]:
case "missing", (*parent, field):
return Fault(reason=Reason.ABSENT, subject=".".join(map(str, parent)) or title, member=str(field))
case _, loc:
return Fault(reason=Reason.INVALID, subject=".".join(map(str, loc)) or title, cause=detail["msg"])
def faulted(error: ValueError, /) -> Faults:
match error:
case ValidationError() if details := error.errors(include_url=False):
head, *rest = (fault(error.title, detail) for detail in details)
return (head, *rest)
case _:
return Fault.of(Reason.INVALID, type(error).__name__, error)
Window holds a stripped non-empty name and limit: PositiveInt | None. catch(Window.model_validate_json, exception=ValueError)(raw).map_error(faulted) over {"limit": 0, "x": 1} returns one fault per error. Faults read Window holds no name, limit is invalid. Input should be greater than 0, x is invalid. Extra inputs are not permitted. Malformed JSON returns one json_invalid fault on Window:
ValidationError and SettingsError subclass ValueError, a validator raising TypeError or KeyError escapes validation as a defecttitle names a model by its class and an adapter by its type (list[int])loc names a field by its validation alias (("id",) for key: int = Field(alias="id")), loc_by_alias=False names it by attributetype strings (missing, extra_forbidden, greater_than, a custom error's type) are stable keys a fault builder matches, msg is prosectx holds each refused constraint ({"gt": 0}) and input the refused valueTypeAdapter(Annotated[Record, ValidateAs(Wire, build)]) validates a wire model differing from an existing record and builds the record in one callvalue_error at loc (), and records encode through their own codecannotated_types and Field constraints, pydantic ignores msgspec.MetaClass keywords (class Wire(BaseModel, frozen=True, extra="forbid")) set configuration that mypy and ty read and pydantic merges into model_config. Subclasses inherit configuration, a base class states it and each subclass declares its fields alone:
frozen=True hashes field values, a frozen model holding a list raises TypeError on hashextra="forbid" reports an unknown key as extra_forbidden, the default "ignore" drops it, and extra= on one validate call overrides italias, default, and default_factory take assignment form (key: int = Field(alias="id")), mypy reads an Annotated alias as the field namealias, exclude, deprecated) sits on the whole annotation, inside a union arm it warns UnsupportedFieldAttributeWarningdefault_factory=lambda data: ... receives earlier validated fields as a dictT | MISSING = MISSING with MISSING from pydantic marks a key input can omit and dumps leave outmodel_construct, model_copy(update=), and copy.replace skip validation, Model.model_validate(model.model_dump() | changes) validatesUserWarning, and warnings="error" on the dump call raises PydanticSerializationErrorvalidate_assignment=True keeps a value its model validator refused on the instance, frozen models change by validated copyrevalidate_instances="always" reads the instance's own class, set on a parent model it leaves a nested model_construct value unchecked@computed_field over @property enters dumps and serialization schema as readOnly, and mypy reports its line as prop-decoratorfunctools.cached_property works on a frozen model and stays out of dumpsBaseModel method (model_dump) raise ValueError at class build, names shadowing an attribute (copy) warnField, annotated_types, and StringConstraints compile into one schema node, and validators serve rules none of them states. Generic aliases (NonEmpty[T]) hold one constraint over any element type:
type NonEmpty[T] = Annotated[tuple[T, ...], Field(min_length=1)]
type Code = Annotated[str, AfterValidator(str.upper), StringConstraints(strip_whitespace=True, pattern=r"^[A-Z]{3}$")]
class Knot[X: float, Y: float](BaseModel, frozen=True, extra="forbid"):
x: X
y: Y
Curve holds code: Code and knots: NonEmpty[Knot[Unit, Positive]]. type aliases Unit and Positive hold Field(ge=0.0, le=1.0) and Field(gt=0.0). Curve refuses {"code": "abcd", "knots": [{"x": 1.5, "y": 0}]} at code, ("knots", 0, "x"), ("knots", 0, "y"), and knots:
Code uppercases before strip and pattern, StringConstraints alone checks pattern before to_upperPlainValidator discards every validator and constraint to its left, Annotated[int, Gt(0), PlainValidator(int)] accepts -5Code publishes a plain stringtype aliases over Annotated publish a named $defs entry, an assignment alias inlines its nodeAwareDatetime and NaiveDatetime require timezone state, pydantic ignores at.Timezone and at.docpattern compiles with the Rust regex crate, a lookaround raises SchemaError at class build until regex_engine="python-re"Lax mode coerces by the conversion table, strict mode accepts exact types, and JSON input holds its own strict rows:
int accepts "1" and 1.0 and rejects 1.5 with int_from_float, lax list[int] accepts a tuple or setstrict=True as a class keyword makes every field strict, Annotated[T, Strict(False)] relaxes one fielddate, lists for tuple, and raw values for an enum, strict JSON accepts each one's JSON encodingSequence[str] rejects a str with sequence_str and keeps the input's collection type, tuple[T, ...] yields one typefloat accepts nan and inf from Python, text, and JSON literals (NaN, Infinity), allow_inf_nan=False or FiniteFloat refuses themValidators attach by mode in Annotated beside their type, and a type alias holds them with it. Validators run model, field, and right-to-left Annotated before/wrap, core, then left-to-right Annotated, field, and model after. Model after validators hold cross-field rules and run once every field validated, a failed field skips them:
class Span(BaseModel, frozen=True, extra="forbid"):
lo: NonNegativeInt
hi: NonNegativeInt
@model_validator(mode="after")
def ordered(self) -> Self:
if self.lo > self.hi:
raise PydanticCustomError("span_order", "{lo} exceeds {hi}", {"lo": self.lo, "hi": self.hi})
return self
@model_validator(mode="after") is an instance method returning Self, a @classmethod form warns deprecationbefore validators receive any input object, a dict or notinfo.data["lo"] raise a raw KeyError once lo failedPydanticCustomError templates format {name} from ctx and leave {name!r} literal, ruff RUF027 reports a placeholder naming a localPydanticKnownError("greater_than", {"gt": 5}) raises a built-in error type with its default messagehandler(value), raising PydanticUseDefault takes the field defaultPydanticOmit from an item validator drops the item, OnErrorOmit[T] drops each invalid itemAnnotated[list[T], FailFast()] stops at its first invalid item, and every item reports by defaultvalidation_error_cause=True sets __cause__ to an ExceptionGroup of the raised Python errorshide_input_in_errors=True drops input values from error text on models that read secrets, errors() keeps each inputPer-call data (catalog, unit scale, caller limits) enters through context= on a validate call, and ValidationInfo[C] types it for mypy and ty. One model serves every caller with no closure, global, or model per catalog:
def known(name: str, info: ValidationInfo[frozenset[str] | None], /) -> str:
match info.context:
case frozenset() as names if name in names:
return name
case frozenset():
raise PydanticCustomError("unknown_name", "{entry} names no catalog entry", {"entry": name})
case None:
raise TypeError(name)
type Ref = Annotated[str, AfterValidator(known)]
Link holds source: Ref and targets: tuple[Ref, ...]. Link.model_validate_json(raw, context=names) reports unknown names at their index (("targets", 1)). Calls without a catalog raise TypeError:
context reaches every nested model and item, and model_dump(context=) hands serializers their own through SerializationInfomodel_validate or an adapterValidationInfo holds data (earlier fields that passed), mode ("python" or "json"), and field_name beside contextTypes with a pydantic wire form take no serializer: Decimal holds exact amounts, round-trips JSON text, and reads numbers. Field(decimal_places=<n>) bounds one currency's amounts at its ISO 4217 minor unit (2 for EUR, 0 for JPY). Serializers for output no type states attach in Annotated as PlainSerializer(fn, return_type=, when_used=) or WrapSerializer(fn). WrapSerializer functions take (value, handler, info) and branch on info.mode_is_json(). Set dump order follows per-process string hashing, and Names writes sorted JSON:
type Names = Annotated[frozenset[str], PlainSerializer(sorted, return_type=list[str], when_used="json")]
model_dump() keeps a frozenset, JSON output validates back to an equal set, and return_type types the serialization schema as an array@model_serializer(mode="wrap") calls handler(self), a TypedDict return keeps a typed schema and dict[str, Any] an open objectField(exclude_if=predicate) removes a field from dumps when the predicate holds for its valuemodel_dump_json() returns str, TypeAdapter.dump_json() returns bytes, model_dump(mode="json") returns JSON builtinsSecretStr dumps as a masked SecretStr in Python mode and as "**********" in JSON, get_secret_value() reads it at its one useround_trip=True dumps a Json[T] field back to JSON text, the default writes its parsed valueser_json_temporal="milliseconds" with val_temporal_unit="milliseconds" round-trips a datetimetimedelta reads numbers as seconds under val_temporal_unit="milliseconds", and a millisecond dump reads back 1000 times longernull a float field refuses, ser_json_inf_nan="constants" writes NaN and Infinity that read backser_json_bytes="base64" pairs with val_json_bytes="base64", alone it reads base64 text back as bytes of the textFields serialize by declared type: a Base field holding a Sub dumps Base fields, and dict input validates as Base with Sub keys dropped. Subclass shapes take a form that names them:
class Holder[T: Base](BaseModel) parametrized as Holder[Sub] validates and dumps Subpolymorphic_serialization=True on a base's configuration dumps held instances by runtime class and leaves validation as declaredSerializeAsAny[Base] widens one field, serialize_as_any=True on a dump call widens every valueTagged unions select a member by a Literal field, and one member can hold more than one tag:
class _Answer(BaseModel, frozen=True, extra="forbid"): ...
class Done(_Answer):
status: Literal["ok"]
class Failed(_Answer):
status: Literal["error", "raised"]
message: str
type Answer = Annotated[Done | Failed, Field(discriminator="status")]
union_tag_invalid, a missing tag union_tag_not_found, and member errors take a loc led by the tag (("error", "message"))str raise PydanticUserError code discriminator-needs-literal, a duplicate tag raises TypeError at buildoneOf with discriminator.propertyName and a mapping entry per tagUnions chosen by a function take Discriminator(fn), with fn mapping raw input or a member instance to the class name in a member's Tag. Circle holds radius, Rect holds width and height:
def shape(value: object) -> str | None:
match value:
case {"radius": _} | Circle():
return Circle.__name__
case {"width": _, "height": _} | Rect():
return Rect.__name__
case _:
return None
type Shape = Annotated[Annotated[Circle, Tag(Circle.__name__)] | Annotated[Rect, Tag(Rect.__name__)], Discriminator(shape, custom_error_type="shape", custom_error_message="input matches no shape")]
None from fn raises the custom error type with its messageint | str keeps "1" a str, date | str keeps Python ISO strings and reads JSON as dateField(union_mode="left_to_right") takes the first member that validatesTypeAdapter(T) builds a validator and serializer once and gives any type the validate, dump, and schema calls of a model:
TypeAdapter types its value from its argument under mypy and ty, an Annotated or type alias includedvalidate_strings reads a string or a mapping of strings (environment, query) and rejects a list with string_typefrom_attributes=True on a validate call or in configuration reads a host object and its nested objects by attributeconfig= sets configuration on types without their own, a model or TypedDict target raises PydanticUserErrorexperimental_allow_partial=True on adapter JSON validation completes a truncated list, dict, or TypedDict, a model field stays required"trailing-strings" keeps a truncated last string@validate_call validates each call's arguments against the signature and raises one ValidationError an entry point converts. The error lists every failing argument, a positional one at its index as loc:
**kwargs: Unpack[TypedDict] validates each keyword against its itemvalidate_return=True validates each return, on an async def after its await@validate_call directly, under @classmethod it sits innermostAnyconfig=ConfigDict(strict=True) makes every argument strict, raw_function holds the undecorated functionGeneric models take PEP 695 class parameters and parametrize at the boundary (Knot[Unit, Positive].model_validate_json(raw)):
Knot[Unit, Positive] titling its schema and Knot_Unit_Positive_ keying its $defs entryAny, a bound ([T: int]) or default ([T = int]) validates against itselftype Tree = int | list[Tree] validates recursive input, a quoted TypeAlias recursion raises RecursionError at buildSelf validate a recursive modelTypedDict(closed=True) rejects unknown keys, extra_items=T validates them, NotRequired drops a key from requiredReadOnly items validate with a UserWarning that pydantic leaves them mutablefrozendict[K, V] validates to a frozendict, NewType validates as its baseLiteralString, TypeIs, and sentinels other than MISSING raise PydanticSchemaGenerationError at build__init_subclass__ runs before pydantic collects a class's own fields, __pydantic_init_subclass__(cls, **kwargs) runs with them built__pydantic_on_complete__ runs once a class's schema completes, and both hooks suit a registry reading fieldsmodel_json_schema(mode=) and TypeAdapter.json_schema(mode=) publish Draft 2020-12, "validation" describing input and "serialization" output:
json_schema_serialization_defaults_required=True marks defaulted fields required in serialization modemodels_json_schema([(Model, mode), ...], ref_template="#/components/schemas/{model}") shares one $defs across modelsTypeAdapter.json_schemas([(key, mode, adapter), ...]) shares one $defs across adaptersLiteral fields emit constField(description=, examples=, json_schema_extra=), configuration json_schema_extra, and use_attribute_docstrings=True add keysWithJsonSchema and __get_pydantic_json_schema__ replace a nodealias_generator=to_camel with validate_by_name=True, validate_by_alias=True, and serialize_by_alias=True maps both directionsitemCount titles Itemcount)AliasChoices and AliasPath("names", 0) select validation input, serialization_alias names output under by_alias=TrueValidation cost sits in one schema build per type and one Rust pass per call, and declarations decide both:
model_validate_json parses and validates in one pass under JSON conversion rows, a msgspec or json decode before model_validate parses twicelist, tuple, and dict validate directly, Sequence and Mapping run an isinstance test and try each concrete typeTypedDict structures validate faster than nested models, a hot path holding no methods takes themSkipValidation[T] keeps a trusted value's type and skips its work, defer_build=True moves schema build to first usepython:msgspec for owned wire formats and domain recordsComposition roots read settings through one BaseSettings class composing nested BaseModel groups. settings_cached() builds one instance per process, returns Self, and leaves a failed build uncached:
_PACKAGE: str = __name__.partition(".")[0]
class Settings(BaseSettings, frozen=True, env_prefix=f"{_PACKAGE.upper()}_", env_nested_delimiter="__", toml_file=f"{_PACKAGE}.toml"):
token: SecretStr
store: Store
@override
@classmethod
def settings_customise_sources(
cls,
settings_cls: type[BaseSettings],
init_settings: PydanticBaseSettingsSource,
env_settings: PydanticBaseSettingsSource,
dotenv_settings: PydanticBaseSettingsSource,
file_secret_settings: PydanticBaseSettingsSource,
) -> tuple[PydanticBaseSettingsSource, ...]:
return (init_settings, env_settings, dotenv_settings, file_secret_settings, TomlConfigSettingsSource(settings_cls))
def settings() -> Outcome[Settings]:
return catch(Settings.settings_cached, exception=ValueError)().map_error(faulted)
Store holds host and a port bounded by Field(gt=0, lt=65536). Under package app, app.toml [store] host and APP_STORE__PORT=70000 return store.port is invalid. Input should be less than 65536 and Settings holds no token:
settings_customise_sources returns sources highest priority first, a source left out of the tuple reads nothingBaseSettings defaults to extra="forbid" and validate_default=Truepython:cyclopts for command linesWhat SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub bsamiee/rasm --plugin python8 skills in this plugin
/codingUse when writing or reviewing Python, covering functional design with result and record types/cycloptsUse when writing or reviewing a cyclopts app, covering commands, parameters, user classes, meta apps, configuration, completion, and exit codes/debuggingUse when debugging Python at runtime (failing test, wrong value, swallowed exception, hang, crash, slow or growing process), covering debugpy environments, pytest stops, exception filters, attaches through pdb, and the interpreter's stack, fault, and profiling toolsOther plugins' skills for the same job