jcrist / msgspec

A fast serialization and validation library, with builtin support for JSON, MessagePack, YAML, and TOML

Home Page:https://jcristharif.com/msgspec/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Could msgspec be used to specify expected output types when encoding?

Lance-Drane opened this issue · comments

Question

This is something I'm not sure should be a feature request.

Validating data against a schema as you're encoding it is more niche than validating data as you're decoding it, but there are certain usecases where this could be valuable. For example, imagine a library which handles everything from encoding/decoding to the transport layer, but allows for users to specify input/output typings that msgspec can handle and requires that users type annotate a function (for the purposes of generating a schema), in a similar fashion to a REST API. The library would then check to see that the user's return value function matches the return type annotation of their function, and would ideally do type validation through msgspec.

The API could look similar to the decoder's API, i.e. encoder.encode(12, type=int, strict=True) would validate but encoder.encode("blue", type=int, strict=True) would raise a validation error.

This is something that Pydantic supports, but this is due to them needing to construct a core_schema as they build the serialized instance.