diff --git a/docs/source/usage.rst b/docs/source/usage.rst index cf876624..4752de00 100644 --- a/docs/source/usage.rst +++ b/docs/source/usage.rst @@ -158,6 +158,40 @@ types. >>> msgspec.json.decode(b'[1, 2, "3"]', type=list[int], strict=False) [1, 2, 3] +.. _builtin-conversion: + +Converting to and from builtin types +------------------------------------ + +In some cases, ``msgspec`` will only be processing part of a message, +so full serialization to or from text or bytes isn't desirable. For +these situations, ``msgspec`` supports conversion to and from builtin +types which are otherwise handled (or created) by another library. + +"Decoding" is handled by :func:`~msgspec.convert`, while "encoding" is handled by +:func:`~msgspec.to_builtins` (note that the input/output in this example is a +Python dictionary, *not* an encoded string): + +.. code-block:: python + + >>> import msgspec + + >>> class User(msgspec.Struct): + ... name: str + ... groups: set[str] = set() + ... email: str | None = None + + >>> data = {"name": "bill", "groups": ["devops", "engineering"]} + + >>> # Convert already decoded data into typed structs + ... msgspec.convert(data, User) + User(name='bill', groups={'devops', 'engineering'}, email=None) + + >>> user = User(name="alice", groups={"admin", "engineering"}, email=None) + + >>> # Convert to builtin types for subsequent encoding + ... msgspec.to_builtins(user) + {'name': 'alice', 'groups': ['engineering', 'admin']} .. _JSON: https://json.org .. _MessagePack: https://msgpack.org diff --git a/msgspec/_core.c b/msgspec/_core.c index bfb73680..3b9732ee 100644 --- a/msgspec/_core.c +++ b/msgspec/_core.c @@ -7798,6 +7798,10 @@ PyDoc_STRVAR(struct_asdict__doc__, "\n" "Convert a struct to a dict.\n" "\n" +"This function converts all fields, regardless of the ``omit_defaults`` setting.\n" +"\n" +"Use ``to_builtins`` for recursive conversion with more encoding-like behavior.\n" +"\n" "Parameters\n" "----------\n" "struct: Struct\n" @@ -19995,7 +19999,10 @@ PyDoc_STRVAR(msgspec_to_builtins__doc__, "Convert a complex object to one composed only of simpler builtin types\n" "commonly supported by Python serialization libraries.\n" "\n" -"This is mainly useful for adding msgspec support for other protocols.\n" +"This is useful for adding msgspec support for other protocols, as well as\n" +"to handle cases where msgspec is only processing part of a data structure.\n" +"\n" +"This function respects the ``omit_defaults`` setting on structs.\n" "\n" "Parameters\n" "----------\n"