Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
Python serialization libraries convert Python objects into text or bytes, such as JSON, YAML, TOML, or a binary format, and load them back. A schema-based format generates message classes from a definition rather than encoding arbitrary values as they are. These libraries let services, configuration tools, and data pipelines store and exchange structured data.
Popularity
PyYAML has the most monthly downloads in this comparison, at 1.3B.
def to_yaml(self, line_break=None, original_order: list[str] | None = None) -> str:
"""Dumps CardData to a YAML block for inclusion in a README.md file.
Args:
line_break (str, *optional*):
The line break to use when dumping to yaml.
original_order (`list[str]`, *optional*):
If provided, reorder the metadata fields to match this list before dumping.
Any keys not in `original_order` are appended after the listed keys, preserving
their existing relative order. Useful for round-tripping a YAML block without
shuffling its keys.
Returns:
`str`: CardData represented as a YAML block.
"""
if original_order:
original_order_set = set(original_order)
self.__dict__ = {
k: self.__dict__[k]
for k in original_order + [k for k in self.__dict__ if k not in original_order_set]
if k in self.__dict__
}
return yaml_dump(self.to_dict(), sort_keys=False, line_break=line_break).strip()
def __call__(
self, value: Union[Dict, Message], ctx: SerializationContext
) -> Union[str, bytes]:
if isinstance(value, self._msg_type):
msg = value
else:
try:
msg = ParseDict(
cast(Dict[str, Any], value),
self._msg_type(),
ignore_unknown_fields=self._ignore_unknown_fields,
)
except TypeError as exc:
raise SerializationError(
"Value to serialize must be of type "
f"`{self._msg_type}` or dict, not `{type(value)}`."
) from exc
except ParseError as exc:
raise SerializationError(str(exc)) from exc
if self._schema_registry_serializer is not None:
try:
return self._schema_registry_serializer(msg, ctx)
except (SchemaRegistryError, _SerializationError) as exc:
raise SerializationError(str(exc)) from exc
try:
return msg.SerializeToString(deterministic=self._deterministic)
except EncodeError as exc:
raise SerializationError(str(exc)) from exc
def write_toml(self) -> None:
assert (
len(self._toml_paths) == 1
), "Will not write configs when more than one toml path was resolved. Found paths: " + str(
self._toml_paths
)
with open(self._toml_paths[0], "w", encoding="utf-8") as f:
tomlkit.dump(self._config_toml, f)
msgpack
Encodes and decodes data using the MessagePack serialization format.
Downloads / mo
234.9M
Stars
2.1K
Last release
1.2.4
License
Apache-2.0
Strengths
Decodes multiple streamed objects.Use Unpacker with a stream or feed it successive byte buffers.
Supports custom data hooks.Pair a default encoder with object_hook to restore custom values.
Limitations
Default map keys are restricted.Use string or byte keys unless strict_map_key is disabled.
Arrays decode as lists.Set use_list=False to decode arrays as tuples.
def msgpack_serialize(pytree, in_place: bool = False) -> bytes:
"""Save data structure to bytes in msgpack format.
Low-level function that only supports python trees with array leaves,
for custom objects use ``to_bytes``. It splits arrays above MAX_CHUNK_SIZE into
multiple chunks.
Args:
pytree: python tree of dict, list, tuple with python primitives
and array leaves.
in_place: boolean specifying if pytree should be modified in place.
Returns:
msgpack-encoded bytes of pytree.
"""
if not in_place:
pytree = jax.tree_util.tree_map(lambda x: x, pytree)
pytree = _np_convert_in_place(pytree)
pytree = _chunk_array_leaves_in_place(pytree)
return msgpack.packb(pytree, default=_msgpack_ext_pack, strict_types=True)
orjson
Encodes and decodes JSON with support for dataclasses, datetimes, and NumPy.
def dumps(obj: Any,
sort_keys: bool = False,
separators: tuple[str, str] | None = None, *,
indent: bool = False) -> str:
"""Serializes a Python object to a JSON-encoded string.
By default, this function supports serializing NumPy arrays, which Python's json module does not.
Uses package ``orjson`` internally.
"""
# note that parameters `sort_keys` and `separators` are required by AsyncServer's # internal calls, which match Python's default `json.dumps` API. assert separators is None or separators == (',', ':'), \
f'NiceGUI JSON serializer only supports Python\'s default JSON separators "," and ":", but got {separators} instead.'
opts = ORJSON_OPTS
# flag for sorting by object keys if sort_keys:
opts |= orjson.OPT_SORT_KEYS
# flag for pretty-printing with indentation if indent:
opts |= orjson.OPT_INDENT_2
return orjson.dumps(obj, option=opts, default=_orjson_converter).decode('utf-8')
cloudpickle
Serializes Python functions and classes, including interactive definitions, by value.
Downloads / mo
209.5M
Stars
2.0K
Last release
3.1.3
License
BSD-3-Clause
Strengths
Serializes lambdas and interactive definitions.Transfer functions and classes defined in scripts, notebooks or interactive sessions.
Can include module definitions.Register a module for by-value serialization when imports will be unavailable.
Limitations
Python versions must match.Send objects only between the exact same Python version.
Long-term storage is unsupported.Use this serializer for object transfer rather than archival storage.
def dumps(x, *, buffer_callback=None, protocol=HIGHEST_PROTOCOL):
"""Manage between cloudpickle and pickle
1. Try pickle
2. If it is short then check if it contains __main__
3. If it is long, then first check type, then check __main__
"""
buffers = []
dump_kwargs = {"protocol": protocol or HIGHEST_PROTOCOL}
if dump_kwargs["protocol"] >= 5 and buffer_callback is not None:
dump_kwargs["buffer_callback"] = buffers.append
try:
try:
result = pickle.dumps(x, **dump_kwargs)
except Exception:
f = io.BytesIO()
pickler = _DaskPickler(f, **dump_kwargs)
buffers.clear()
pickler.dump(x)
result = f.getvalue()
if b"__main__" in result or (
getattr(inspect.getmodule(x), "__name__", None)
in cloudpickle.list_registry_pickle_by_value()
):
if len(result) < 1000 or not _always_use_pickle_for(x):
buffers.clear()
result = cloudpickle.dumps(x, **dump_kwargs)
except Exception:
try:
buffers.clear()
result = cloudpickle.dumps(x, **dump_kwargs)
except Exception:
logger.exception("Failed to serialize %s.", x)
raise
if buffer_callback is not None:
for b in buffers:
buffer_callback(b)
return result
ruamel.yaml
Parses and emits YAML with round-trip preservation of comments, flow style, and key order.
orjson suits JSON with dataclasses, datetimes, and NumPy arrays. ruamel.yaml suits YAML files whose comments must survive a round trip. msgpack suits compact binary messages. cloudpickle suits shipping Python functions between processes.
PyYAML is a YAML parser and emitter for Python. Loading and dumping objects does not preserve the comments in the original file.
orjson is a JSON library with support for dataclasses, datetimes, and NumPy arrays. It returns bytes rather than a string.
cloudpickle serializes Python functions and classes by value, including lambdas and interactive definitions. Loading may execute code. Only trusted data should be unpickled.
tomlkit edits TOML documents and preserves their comments, indentation, whitespace, and element order.
For coding agents
Found your serialization library? Help your agent use it.
Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.