jcrist / msgspec

A fast serialization and validation library, with builtin support for JSON, MessagePack, YAML, and TOML
https://jcristharif.com/msgspec/
BSD 3-Clause "New" or "Revised" License
2.44k stars 75 forks source link

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

Open Lance-Drane opened 7 months ago

Lance-Drane commented 7 months ago

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.

fungs commented 4 months ago

Possible duplicate of https://github.com/jcrist/msgspec/issues/615, if I understand it correctly?