msgspec
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
- breaking msgspec 0.19.0 dropped support for Python 3.8. Users on Python 3.8 or older must upgrade their Python version or stay on msgspec < 0.19.0.
- breaking In msgspec 0.19.0, the `encode_into` method (an advanced API) now expands the buffer if it's smaller than the offset, which is a breaking change for specific buffer management use cases.
- deprecated The `from_builtins` method was removed in msgspec 0.19.0. Users should now use `msgspec.convert` for similar functionality.
- gotcha When using `msgspec.msgpack` to decode into `memoryview` objects, the original input message buffer will be kept in memory as long as the `memoryview` is alive. This can lead to unexpectedly high memory usage if not carefully managed, especially with large messages or long-lived `memoryview` instances.
- gotcha Mutable default values (e.g., `list`, `set`, `dict`) on `msgspec.Struct` fields will be shared across all instances if not defined using `msgspec.field(default_factory=...)`. This is a common Python pitfall.
- gotcha The `msgspec.structs.fields()` function can be significantly slower (up to 20x) than `dataclasses.fields()` because it re-inspects type annotations on every invocation. Avoid frequent calls to `msgspec.structs.fields()` in performance-critical loops.
- breaking In msgspec 0.7.0, the `nogc` struct option was renamed to `gc`. To disable garbage collection for a Struct instance, you must now specify `gc=False` instead of `nogc=True`.
Install
-
pip install msgspec -
pip install msgspec[yaml,toml]
Imports
- Struct
from msgspec import Struct
- field
from msgspec import field
- json
import msgspec.json
- msgpack
import msgspec.msgpack
- yaml
import msgspec.yaml
- toml
import msgspec.toml
Quickstart
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}")