/python:msgspecfrom python
Use when declaring msgspec records or codecs, covering struct options, constraints, validation, hooks, and conversion
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.
None: SKILL.md is the whole skill.
Subclasses inherit every struct option, one base class declares encoding options every union member shares:
class Event(msgspec.Struct, frozen=True, kw_only=True, forbid_unknown_fields=True, rename="camel", tag_field="kind", tag=str.lower): ...
Closed(Event, frozen=True, kw_only=True) decodes {"kind": "closed", "itemId": 1}, unknown keys fail (Object contains unknown field `extra`):
tag=True and tag callables read __qualname__, a nested class tags as Outer.Inner<Member>.value, a StrEnum member passes type checkers and raises TypeError at class creation__init_subclass__ runs before __struct_fields__ exists, and a class keyword msgspec lacks raises TypeErrorStruct, dict, TypedDict, dataclass)str, enum, datetime, UUID, Decimal, bytes), and Literal["a"] | str decodesOptions beyond frozen and kw_only change encoding or memory under a condition:
| [INDEX] | [OPTION] | [EFFECT] | [CONDITION] |
|---|---|---|---|
| [01] | rename= | Wire names by convention or mapping | Callables returning None keep a name, field(name=...) wins |
| [02] | forbid_unknown_fields=True | Decode refuses keys a record lacks | Schema emits additionalProperties: false |
| [03] | omit_defaults=True | Encode drops fields at their default | frozendict() default omits, default_factory=frozendict encodes |
| [04] | array_like=True | Positional array on the wire | Error paths read $[<index>] |
| [05] | cache_hash=True | Hash computed once | Requires frozen=True |
| [06] | gc=False | GC skips instances with containers | dict=True or weakref=True raises ValueError, a cycle leaks |
Constraints take limits from the module that states them:
type Finite = Annotated[float, msgspec.Meta(ge=-sys.float_info.max, le=sys.float_info.max)]
type Key = Annotated[str, msgspec.Meta(pattern=r"^[a-z][a-z0-9_]*$")]
Finite refuses nan and inf from convert, and JSON decodes refuse an overflowing number without a constraint (Number out of range):
gt=0.0 accepts every subnormal, ge=sys.float_info.min excludes themmax_length counts code points on str and bytes on bytes, a limit a host states in bytes bounds the encoded textAnnotated layers, a second raises TypeError, and one Meta holding gt and ge fails type checkerspattern searches anywhere in a value, ^ and $ anchor itint and float raise TypeError at first decode or convert, Decimal bounds go in __post_init__convert over to_builtins reruns every constraint and __post_init__ once, and one merge with a decoded object patches any record:
def patched[S: msgspec.Struct](record: S, raw: bytes, /) -> Outcome[S]:
try:
return Ok(msgspec.convert(msgspec.to_builtins(record) | msgspec.json.decode(raw, type=dict[str, object]), type(record)))
except msgspec.DecodeError as error:
return Error(Fault.of(Reason.INVALID, type(record).__name__, error))
Over a rename="camel" record, {"closingNote": null} clears closing_note, absent keys keep their field, and {"title": ""} fails at $.title. Python name closing_note fails under forbid_unknown_fields=True and drops unread without it:
structs.force_setattr(self, "<field>", <canonical>) in frozen __post_init__ gives decode, convert, replace, ==, and cache_hash one formcopy.deepcopy runs __post_init__, copy.copy skips it, and convert(record, T) returns record uncheckedstructs.replace takes **changes: Any, a change of wrong type passes type checkers and runtime__post_init__ errors besides TypeError and ValueError (KeyError) propagate raw from decode and convertint passed to a float field encodes as 1 where a decoded record writes 1.0T | UnsetType = UNSET tells absence from null, encode and to_builtins drop it, structs.asdict keeps it, and is UNSET narrows its typeReaders and writers on different record releases exchange data when every change keeps the old shape decodable:
forbid_unknown_fields off, the option refuses new fields (Expected `array` of at most length 2)field(name="<wire>"), and a wire rename is a new fieldInvalid value 'c' - at `$.kind`), and readers add a new member before any writer sends itRecords declaring only fields a consumer reads skip the rest of a document unallocated, msgspec.Raw fields hold bytes undecoded:
class Routed(msgspec.Struct, frozen=True, kw_only=True):
topic: str
body: msgspec.Raw
ROUTED = msgspec.json.Decoder(Routed)
ROUTED refuses a malformed body unbuilt, encoders write its bytes verbatim, and msgspec.json.decode(routed.body, type=T) decodes it for known T. Format modules (json, msgpack, yaml, toml) share one encoder and decoder API:
bytes(<record>.body) copies a body out, Raw.copy() detaches it from its source buffer, and convert refuses a Raw targetEncoder.encode_lines and Decoder.decode_lines write and read newline-delimited JSON, refused lines fail at $[<line>]msgspec.yaml needs PyYAML, msgspec.toml decodes through tomllib and encodes through tomli_worder="deterministic" sorts dict keys and set items a default encode writes in per-process hash order, "sorted" adds struct fieldsencode_into(value, buffer, offset) returns None and resizes buffer to end at its last written byte, -1 appendsSequence and Mapping annotations decode to list and dictdecimal_format writes Decimal as "string", "number", or a callable's str, and Decoder(float_hook=Decimal) reads untyped floats exactlyNaN and infinities encode as JSON null, and a float field refuses null on decodeenc_hook receives values msgspec cannot encode, dec_hook annotations it cannot decode, and both raise NotImplementedError for unsupported types. TEXTUAL serves enc_hook, dec_hook, and schema_hook for types with a text form:
TEXTUAL: frozendict[type, frozendict[str, str]] = frozendict({Path: frozendict({"type": "string"}), IPv4Address: frozendict({"type": "string", "format": "ipv4"})})
def encoded(value: object, /) -> str:
if not isinstance(value, tuple(TEXTUAL)):
raise NotImplementedError(type(value))
return str(value)
def decoded(kind: type, raw: object, /) -> object:
if kind not in TEXTUAL:
raise NotImplementedError(kind)
if not isinstance(raw, str):
raise TypeError(f"Expected `str`, got `{type(raw).__name__}`")
return kind(raw)
def schema(kind: type, /) -> dict[str, object]:
if (node := TEXTUAL.get(kind)) is None:
raise NotImplementedError(kind)
return dict(node)
Encoder(enc_hook=encoded) writes and Decoder(<Record>, dec_hook=decoded) reads every Path and IPv4Address field, a new type adds one entry:
enc_hook receives subclass instances isinstance matches (PosixPath for Path), dec_hook any wire type (IPv4Address(5) builds 0.0.0.5)ValueError and TypeError from a hook report at their path (Octet 256 (> 255) not permitted in '10.0.0.256' - at `$.host`)NotImplementedError and every other class propagate raw, and a ValidationError from a convert inside dec_hook loses its pathDecimal, datetime, UUID) never reach dec_hookNone aloneRecords holding live handles (host objects, open resources) encode each as an extension value naming its side-table index, and decode resolves it. linked adds one entry per distinct handle during one encode and returns the table as a tuple beside the bytes:
LINK = 1
def linked[H: Hashable](kind: type[H], record: msgspec.Struct, /) -> tuple[bytes, tuple[H, ...]]:
table: dict[H, int] = {}
def referenced(value: object, /) -> msgspec.msgpack.Ext:
if not isinstance(value, kind):
raise NotImplementedError(type(value))
return msgspec.msgpack.Ext(LINK, table.setdefault(value, len(table)).to_bytes(4))
return msgspec.msgpack.encode(record, enc_hook=referenced, order="deterministic"), tuple(table)
def resolved[H: Hashable](handles: tuple[H, ...], code: int, data: memoryview, /) -> H | msgspec.msgpack.Ext:
return handles[int.from_bytes(data)] if code == LINK else msgspec.msgpack.Ext(code, bytes(data))
On linked output, msgspec.msgpack.decode(data, type=<Record>, ext_hook=partial(resolved, handles)) returns a record holding the same handles. A second table of equal length rebinds every field to its handles:
-1 for timestamps)ext_hook result of another class at their path (Expected `Handle`, got `Other` - at `$.handle`)ext_hook raises propagate raw, and a table shorter than its indexes raises IndexError past a DecodeError catchLINK decode as msgspec.msgpack.Ext values, as in a decode with no ext_hookMessagePack differs from JSON on integers, binary, datetimes, UUIDs, and non-finite floats:
-2**63 to 2**64 - 1 raise OverflowError, and JSON writes them wholebytes fields refuse str items, and a memoryview target views bin data in the input buffer, which the view keeps alivedatetime encodes as the timestamp extension, and naive datetime as ISO textEncoder(uuid_format="bytes") writes a UUID as its 16 bytes, an option the JSON encoder lacksNaN and infinities encode as floats and decode back unchangedconvert and every decoder coerce by input and target, and strict=False on either adds the text and number coercions a text source needs:
| [INDEX] | [INPUT] | [TARGET] | [STRICT] | [LAX] |
|---|---|---|---|---|
| [01] | "1", "1.0" | int | Refused | 1 |
| [02] | 1.0 | int | Refused | 1 |
| [03] | "true", "0" | bool | Refused | True, False |
| [04] | 1 | float | 1.0 | 1.0 |
| [05] | "nan", "inf" | float | Refused | nan, inf |
| [06] | 60, "60" | datetime, timedelta | Refused | UTC epoch seconds, seconds |
| [07] | 1 | str | Refused | Refused |
| [08] | "1.5", 1.5 | int | Refused | Refused |
Lax unions holding str keep text ("1" into int | str stays "1"), and Finite refuses the nan and inf lax text yields. Options decide which names, keys, and native values a conversion reads:
rename fails as a missing fieldfrom_attributes=True reads Python names through nested objectsstr_keys=True decodes text keys into int or UUID keys, and builtin_types passes listed native values throughto_builtins applies renames, tags, omitted defaults, and UNSET, and writes Decimal, datetime, UUID, bytes as text strict convert readsstructs.asdict copies Python names one level deepmsgspec.inspect.type_info resolves a type once into a node tree holding wire names, defaults, tags, and expanded Meta constraints. One walk over the tree derives what each shape consumer reads (environment names, flags, columns). leaves lists every field path by wire name with its node:
def leaves(info: msgspec.inspect.Type, prefix: tuple[str, ...] = (), /) -> tuple[tuple[tuple[str, ...], msgspec.inspect.Type], ...]:
match info:
case msgspec.inspect.StructType(fields=fields):
return tuple(*leaves(field.type, (*prefix, field.encode_name)) for field in fields)
case msgspec.inspect.Metadata(type=inner):
return leaves(inner, prefix)
case _:
return ((prefix, info),)
Under rename="camel", leaves(msgspec.inspect.type_info(<Record>)) yields (("dataStore", "port"), IntType(...)). One convert(..., strict=False) coerces text values nested at those paths. forbid_unknown_fields=True refuses unknown keys at their parent (Object contains unknown field `prt` - at `$.dataStore`):
IntType(ge=1, le=65535)), and schema or extra keys wrap it in the Metadata node leaves unwrapsUnionType holding NoneType(), and a tagged union as UnionType of StructType nodes holding tag_field and tagmulti_type_info((A, B)) analyzes types together and shares one node per recordmsgspec.json.schema(T) and schema_components(types, ref_template=) emit JSON Schema 2020-12 from the declarations decode reads. schema_hook supplies the node of each type dec_hook serves:
(HOST,), COMPONENTS = msgspec.json.schema_components((Host,), schema_hook=schema, ref_template="#/components/schemas/{name}")
Over Host with address: IPv4Address and port bounded by Meta(ge=1, le=65535), HOST is {"$ref": "#/components/schemas/Host"}. COMPONENTS holds Host for an OpenAPI components table, address as an ipv4 node and port with minimum and maximum:
Meta constraints, tags as one-value enum, defaults, and required follow the declaration, and docstrings become descriptionanyOf with a discriminator mapping each tag to its member__post_init__ rules and hook logic stay out of the schemaschema_hook raise TypeError, and Meta(extra_json_schema=...) on an alias supplies one type's nodeDecoders expand type aliases, PEP 695 parameters, and unquoted forward references at first use, and unparametrized parameters decode as their bound. Forms msgspec reads in part take a replacement:
| [INDEX] | [FORM] | [BEHAVIOR] | [REPLACEMENT] |
|---|---|---|---|
| [01] | PEP 696 default [T = int] | Unparametrized T decodes as Any | Parametrized target (Box[int]) |
| [02] | Recursive type alias | RecursionError at type analysis | Recursive struct field |
| [03] | ReadOnly TypedDict item | TypeError at type analysis | Frozen struct |
| [04] | TypedDict closed=True, extra_items= | Extra keys dropped unvalidated | forbid_unknown_fields=True |
What 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