msgspec is a serialization and validation library for Python with schemas defined declaratively with type annotations (like dataclasses). Think of it as a pydantic alternative. And it has quite a few advantages:
Performance. In their benchmarks they claim to tear apart everything else, especially pydantic. And while Pydantic 2.0 with the core implemented on Rust is on horizon, it’s not clear when it will be finished, and I still expect msgspec to stay ahead.
No implicit type conversion. If the filed type is specified as
int
and you pass in a string, pydantic (by default) will try its best to convert the passed value to the int. While it is useful for some cases, like parsing URL or GET query parameters, most often you’ll use it for interacting with other APIs and providing your own API, and there types are better to be strict.Clean and consistent API. Pydantic has a relatively long history, and it has accumulated a fair share of bad decisions. Again, it’s something that the author wants to fix in pydantic 2.0, which isn’t clear when it will come out. Msgspec has a clean and functional API that doesn’t mess with your classes.
Out-of-the-box support for many formats: JSON, YAML, TOML, and MessagePack. And if you need more, there is a function that converts your data into JSON-compatible primitive types that you can then serialize as you want.
A nice bonus is the support for dataclass and TypedDict, so you can give it a try without rewriting the models you have.