msgspec

0.20.0 · active · verified Sun Mar 29

msgspec is a fast serialization and validation library, with builtin support for JSON, MessagePack, YAML, and TOML. It features high-performance encoders/decoders, zero-cost schema validation using Python type annotations, and a speedy `Struct` type. The library is actively maintained with frequent releases.

Warnings

Install

Imports

Quickstart

Defines a simple `User` struct, encodes it to JSON, and then decodes it back. It also demonstrates how `msgspec` handles type validation errors during decoding. Uses `msgspec.field(default_factory=set)` for mutable default values to prevent common Python footguns.

import msgspec

class User(msgspec.Struct):
    name: str
    age: int
    email: str | None = None
    groups: set[str] = msgspec.field(default_factory=set)

alice = User(name="alice", age=30, groups={"admin", "dev"})
print(f"Original User: {alice}")

# Encode to JSON
json_data = msgspec.json.encode(alice)
print(f"Encoded JSON: {json_data.decode()}")

# Decode from JSON
decoded_alice = msgspec.json.decode(json_data, type=User)
print(f"Decoded User: {decoded_alice}")

# Example of validation error
try:
    msgspec.json.decode(b'{"name":"bob","age":"25"}', type=User)
except msgspec.ValidationError as e:
    print(f"Validation Error: {e}")

view raw JSON →