Skip to content
Back to skills

Msgspec

ASecurity

Use when working with msgspec, Struct, Meta, msgspec.json, msgspec.msgpack, tagged unions, enc_hook, dec_hook, convert(), or Litestar DTO shapes. Not for Pydantic or ORM models — use their stack-specific skill.

  • 19 stars
  • 0 votes
  • 0 copies
  • 3 views
  • Added September 6, 2026
ai-agentspythonrustgosqlrailsgitapiperformance

Works with

  • cli
  • api

Security analysis

A100/100

Pro scans all 4 files and shows the line behind each finding

Scanned December 6, 2026

npx -y skills add litestar-org/litestar-skills --skill msgspec --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Msgspec?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Msgspec
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/litestar-org-msgspec-litestar-skills/badge)](https://www.skillsdirectory.com/skills/litestar-org-msgspec-litestar-skills)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: msgspec
description: "Use when working with msgspec, Struct, Meta, msgspec.json, msgspec.msgpack, tagged unions, enc_hook, dec_hook, convert(), or Litestar DTO shapes. Not for Pydantic or ORM models — use their stack-specific skill."
---

# msgspec Skill

msgspec (`0.23.0`) is a high-performance Python library for serialization, deserialization, and typed validation.

## Code Style Rules

- Use PEP 604 unions (`T | None`), annotate every serialized field, and use `kw_only=True` for Structs with >2 fields.
- **No `from __future__ import annotations` in modules defining runtime-introspected Structs** unless all consumers resolve postponed annotations; consumer modules MAY use it.
- Configure wire names via `msgspec.field(name=...)` or Struct `rename=`; `msgspec.Meta` holds constraints and JSON Schema metadata, not field aliases.

## Quick Reference

### Struct Definition and Options

```python
import msgspec


class User(msgspec.Struct):
    id: int
    name: str
    email: str | None = None


class Event(msgspec.Struct, frozen=True, gc=False, cache_hash=True):
    """Strictly acyclic scalar fields make gc=False safe."""

    event_id: str
    event_type: str
    sequence: int


class Config(msgspec.Struct, kw_only=True, omit_defaults=True, repr_omit_defaults=True):
    host: str
    port: int = 5432
    ssl: bool = False


class Point(msgspec.Struct, array_like=True):
    x: float
    y: float


class ApiResponse(msgspec.Struct, rename="camel"):
    user_id: int
    created_at: str


class Resource(msgspec.Struct):
    resource_id: int = msgspec.field(name="id")
    tags: list[str] = msgspec.field(default_factory=list)


class StrictInput(msgspec.Struct, forbid_unknown_fields=True):
    name: str
    value: int
```

| `Struct` / `defstruct` Option | Default | Purpose |
| --- | --- | --- |
| `kw_only` / `frozen` / `cache_hash` | `False` | Keyword-only `__init__`, immutability + `__hash__`, cached hash |
| `gc` / `array_like` | `True` / `False` | Skip GC header (`gc=False`) or encode as tuple (`[x, y]`) on acyclic scalar Structs |
| `omit_defaults` / `repr_omit_defaults` | `False` | Omit fields matching default (or empty built-in `default_factory`) on wire / `repr()` |
| `forbid_unknown_fields` | `False` | Raise `ValidationError` on unknown keys in `decode()` / `convert()` |
| `rename` | `None` | `"lower"`, `"upper"`, `"camel"`, `"pascal"`, `"kebab"`, callable, or mapping |
| `tag` / `tag_field` | `None` | Discriminated union tag and discriminator key (defaults to `"type"`) |
| `eq` / `order` | `True` / `False` | Generate equality and ordering comparison methods |
| `weakref` / `dict` | `False` | Add `__weakref__` or `__dict__` (incompatible with `gc=False`) |

### Partial Updates (`UNSET`), Constraints (`Meta`), and Codecs

```python
import msgspec


class UserPatch(msgspec.Struct, kw_only=True, forbid_unknown_fields=True):
    name: str | msgspec.UnsetType = msgspec.UNSET
    email: str | None | msgspec.UnsetType = msgspec.UNSET


patch = msgspec.json.decode(b'{"email": null}', type=UserPatch)
assert patch.name is msgspec.UNSET
assert patch.email is None
assert msgspec.json.encode(patch) == b'{"email":null}'
```

- **Constraints (`Meta`)**: apply `Annotated[Type, Meta(...)]` (`gt`/`ge`, `lt`/`le`, `multiple_of`, `min_length`/`max_length`, `pattern`, `tz`); direct `Struct(...)` instantiation skips `Meta`, while `decode()` and `convert()` validate all rules. See [Meta Constraints Reference](references/constraints.md).
- **Codecs, `Raw`, `convert()`, `structs`, `inspect`, `defstruct`**: instantiate module-level `Encoder` / `Decoder` singletons. `0.23.0` accepts non-dict `Mapping`s (e.g. `MappingProxyType`) in `msgspec.convert(mapping, MyTypedDict)` and emits JSON Schema `"default"` for `dataclass`/`attrs` `default_factory` built-ins. See [Codecs, Converters & Inspection](references/codecs-and-converters.md).
- **Exception hierarchy**: `ValidationError -> DecodeError -> MsgspecError`; catch `ValidationError` before `DecodeError`.

### Centralized JSON Serialization (Match Your Stack)

Centralize serialization in `utils/serialization.py` rather than scattering raw `msgspec.json.encode` / `json.dumps` calls:

- **`sqlspec` in-stack**: re-export `from sqlspec.utils.serializers import from_json, to_json` (handles UUID, datetime, Enum, Decimal, Pydantic, dataclasses, attrs, and Structs).
- **No `sqlspec`**: wrap singleton `msgspec.json.Encoder()` / `Decoder()` in `utils/serialization.py`. See [Litestar Patterns](references/litestar-patterns.md) for `CamelizedBaseStruct`, `PatchBaseStruct`, and `MsgspecDTO`.

### Tagged Unions (Discriminated Unions)

```python
class CreateEvent(msgspec.Struct, tag="create", tag_field="event_type"):
    resource: str


class DeleteEvent(msgspec.Struct, tag="delete", tag_field="event_type"):
    resource: str
    soft: bool = True


Event = CreateEvent | DeleteEvent
```

All Struct variants in a union must share `tag_field`, unique tag values, and one tag type (`str` or `int`); use `msgspec.field(default_factory=...)` for mutable fields. See [Tagged Union Patterns](references/tagged-unions.md).

<workflow>

## Workflow

### Step 1: Define Structs and Constraints

Model wire shapes as `msgspec.Struct` (`kw_only=True` for >2 fields, `frozen=True` for value objects, `forbid_unknown_fields=True` at API boundaries). Apply field rules via reusable `Annotated[T, Meta(...)]` aliases.

### Step 2: Wire Codecs or Tagged Unions

Use centralized `utils/serialization.py` helpers (`sqlspec.utils.serializers` or module-level `Encoder`/`Decoder` singletons). Add `enc_hook`/`dec_hook` only for custom types not built into msgspec. Use tagged unions (`tag=...`, `tag_field=...`) for polymorphic payloads.

### Step 3: Convert and Validate

Use `decode()` or `convert()` at trust boundaries (`from_attributes=True` for attribute objects). Verify round-trip behavior, `ValidationError` paths, and tag dispatch.

</workflow>

<guardrails>

## Guardrails

- **Never put mutable containers (`dict`, `list`, `set`, `bytearray`) or arbitrary object references on `gc=False` / `array_like=True` Structs** — omitting the GC header can leak reference cycles. Also never combine `gc=False` with `weakref=True` or `dict=True`.
- **Use `msgspec.field(default_factory=...)` for empty mutable defaults** (never `= {}` or `= []` in docs/patterns; non-empty mutable defaults raise `TypeError`).
- **UTC timestamps & `to_builtins()`**: `msgspec.to_builtins()` and `msgspec.json` serialize UTC `datetime` with trailing `"Z"`, whereas `datetime.isoformat()` uses `"+00:00"`.
- **Exact `@dataclass` identity check in `convert()`**: with `from_attributes=False`, `msgspec.convert(sub_dc, BaseDC)` raises `ValidationError` on subclass instances; pass `from_attributes=True`, the exact runtime class, or `NamedDependency[SkipValidation[...]]` in Litestar DI.
- **No `rename` in `Meta`** — use `msgspec.field(name=...)` or Struct `rename=`. Do not mix `gt`/`ge` or `lt`/`le`, and avoid non-integral float `multiple_of`.
- **Annotate every field, reuse singleton codecs, and keep `strict=False` at trust boundaries only** — direct `Struct(...)` construction skips `Meta` validation.
- **Library/shared modules defining introspected Structs** avoid `from __future__ import annotations`; consumer modules MAY use it.
- **Prefer centralized `utils/serialization.py`** (`sqlspec.utils.serializers` when `sqlspec` is installed) over ad-hoc `msgspec.json.encode` / `json.dumps`.

</guardrails>

<validation>

### Validation Checkpoint

- [ ] All serialized Struct fields are annotated (`kw_only=True` for >2 fields, `forbid_unknown_fields=True` at API boundaries)
- [ ] `gc=False` / `array_like=True` is restricted to strictly acyclic scalar/tuple Structs without `weakref=True` or `dict=True`
- [ ] Mutable defaults use `msgspec.field(default_factory=...)` (never bare `= {}` / `= []`)
- [ ] Constraints use `Meta` (never pass a `rename` argument to `Meta`), and hooks only handle non-builtin types
- [ ] Object/subclass conversions pass `from_attributes=True` (or `SkipValidation` in Litestar DI), and JSON I/O goes through centralized `utils/serialization.py`
- [ ] Tagged unions share one `tag_field`, unique tags, and one tag value type

</validation>

<example>

## Example

**Task:** Define an event system with tagged unions, constraints, and JSON serialization.

```python
from datetime import UTC, datetime
from typing import Annotated
import uuid

import msgspec
from msgspec import Meta

NonEmptyStr = Annotated[str, Meta(min_length=1, max_length=255)]
PositiveInt = Annotated[int, Meta(gt=0)]


class UserCreatedEvent(msgspec.Struct, tag="user.created", tag_field="event_type", kw_only=True, gc=False):
    event_id: uuid.UUID
    user_id: PositiveInt
    email: NonEmptyStr
    occurred_at: datetime


class UserDeletedEvent(msgspec.Struct, tag="user.deleted", tag_field="event_type", kw_only=True, gc=False):
    event_id: uuid.UUID
    user_id: PositiveInt
    occurred_at: datetime
    reason: str | None = None


UserEvent = UserCreatedEvent | UserDeletedEvent

_encoder = msgspec.json.Encoder()
_decoder = msgspec.json.Decoder(UserEvent)


def encode_event(event: UserEvent) -> bytes:
    return _encoder.encode(event)


def decode_event(data: bytes) -> UserEvent:
    return _decoder.decode(data)


event = UserCreatedEvent(
    event_id=uuid.uuid4(),
    user_id=42,
    email="alice@example.com",
    occurred_at=datetime.now(UTC),
)
payload = encode_event(event)
recovered = decode_event(payload)
assert isinstance(recovered, UserCreatedEvent)
```

</example>

## References Index

- **[Codecs, Converters & Inspection](references/codecs-and-converters.md)** — `json`, `msgpack`, `yaml`, `toml`, `Raw`, `convert()` (`MappingProxyType`, `dataclass` identity), `to_builtins()` (`Z` suffix), `structs`, `inspect`, `defstruct`, `gc=False` safety.
- **[Meta Constraints Reference](references/constraints.md)** — Numeric, string, bytes, datetime, collection, and OpenAPI schema metadata parameters.
- **[Tagged Union Patterns](references/tagged-unions.md)** — Default/custom/integer/callable tags, `tag=False` opt-out, nested unions, API versioning.
- **[Litestar Patterns](references/litestar-patterns.md)** — `CamelizedBaseStruct`, `PatchBaseStruct`, centralized `utils/serialization.py`, `MsgspecDTO`, `SkipValidation`.

## Official References

- <https://msgspec.dev>
- <https://pypi.org/project/msgspec/0.23.0/>
- <https://github.com/msgspec/msgspec/tree/0.23.0>
- <https://github.com/msgspec/msgspec/blob/0.23.0/docs/changelog.md>

## Shared Styleguide Baseline

- [General Principles](../litestar-styleguide/references/general.md)
- [Python](../litestar-styleguide/references/python.md)

Files in this skill

  • SKILL.md16.4 KB
  • references/constraints.md6.3 KB
  • references/litestar-patterns.md6.6 KB
  • references/tagged-unions.md5.9 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.