# Python serialization libraries

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

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [PyYAML](#pyyaml) | 1.3B | 3.0K | Sep 2025 | MIT |
| [pydantic](#pydantic) | 1.2B | 29.6K | Nov 2026 | MIT |
| [protobuf](#protobuf) | 783.8M | 72.2K | Sep 2026 | BSD-3-Clause |
| [tomlkit](#tomlkit) | 607.1M | 871 | Oct 2026 | MIT |
| [msgpack](#msgpack) | 234.9M | 2.1K | Oct 2026 | Apache-2.0 |
| [orjson](#orjson) | 223.6M | 8.3K | Oct 2026 | MPL-2.0 AND (Apache-2.0 OR MIT) |
| [cloudpickle](#cloudpickle) | 209.5M | 2.0K | Nov 2026 | BSD-3-Clause |
| [ruamel.yaml](#ruamel-yaml) | 182.8M | Not on GitHub | Jan 2026 | MIT |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[PyYAML](#pyyaml) has the most monthly downloads in this comparison, at 1.3B.

## Capabilities

| Library | Binary wire format | Comment-preserving edits |
| --- | --- | --- |
| [PyYAML](#pyyaml) | No | No |
| [pydantic](#pydantic) | No | No |
| [protobuf](#protobuf) | Yes | No |
| [tomlkit](#tomlkit) | No | Yes |
| [msgpack](#msgpack) | Yes | No |
| [orjson](#orjson) | No | No |
| [cloudpickle](#cloudpickle) | Yes | No |
| [ruamel.yaml](#ruamel-yaml) | No | Yes |

## Libraries

### PyYAML

[GitHub](https://github.com/yaml/pyyaml) · [PyPI](https://pypi.org/project/PyYAML) · [Docs](https://pyyaml.org/wiki/PyYAMLDocumentation)

Parses and emits YAML.

- Downloads / mo: 1.3B
- Stars: 3.0K
- Last release: 6.0.3
- License: MIT
- Capabilities: [From the PyYAML docs](https://pyyaml.org/wiki/PyYAMLDocumentation)

```sh
pip install PyYAML
```

**huggingface/huggingface_hub** (4.1K stars)

[huggingface/huggingface_hub](https://github.com/huggingface/huggingface_hub) 

```python
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()

```

[src/huggingface_hub/repocard_data.py](https://github.com/huggingface/huggingface_hub/blob/76aa429148a52fb29a7f49b7fa6f6221f1f8bb79/src/huggingface_hub/repocard_data.py) · [More projects using PyYAML →](https://dashboard.exa.ai/playground/search?q=PyYAML%20GitHub%20projects)

**Quickstart**

```python
import yaml

text = yaml.safe_dump({"name": "Ada", "active": True})
print(text)

```

From [__init__.py](https://github.com/yaml/pyyaml/blob/main/lib/yaml/__init__.py)

### pydantic

[GitHub](https://github.com/pydantic/pydantic) · [PyPI](https://pypi.org/project/pydantic) · [Docs](https://docs.pydantic.dev/latest/concepts/serialization/)

Validates data using Python type hints.

- Downloads / mo: 1.2B
- Stars: 29.6K
- Last release: 2.14.3
- License: MIT
- Capabilities: [From the pydantic docs](https://docs.pydantic.dev/latest/concepts/serialization/)

```sh
pip install pydantic
```

**fastapi/fastapi** (104.9K stars)

[fastapi/fastapi](https://github.com/fastapi/fastapi) 

```python
def serialize(
    self,
    value: Any,
    *,
    mode: Literal["json", "python"] = "json",
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    by_alias: bool = True,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
) -> Any:
    # What calls this code passes a value that already called
    # self._type_adapter.validate_python(value)
    return self._type_adapter.dump_python(
        value,
        mode=mode,
        include=include,
        exclude=exclude,
        by_alias=by_alias,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
    )

```

[fastapi/_compat/v2.py](https://github.com/fastapi/fastapi/blob/5add7a458d629b07311d48261f696b5ac2bb9a5f/fastapi/_compat/v2.py) · [More projects using pydantic →](https://dashboard.exa.ai/playground/search?q=pydantic%20GitHub%20projects)

**Quickstart**

```python
from pydantic import BaseModel

class User(BaseModel):
    name: str

print(User(name="Ada").model_dump_json())

```

From [README.md](https://docs.pydantic.dev/latest/concepts/serialization/)

### protobuf

[GitHub](https://github.com/protocolbuffers/protobuf) · [PyPI](https://pypi.org/project/protobuf) · [Docs](https://protobuf.dev/reference/python/python-generated/)

Implements Protocol Buffers, Google's data interchange format.

- Downloads / mo: 783.8M
- Stars: 72.2K
- Last release: 7.36.2
- License: BSD-3-Clause
- Capabilities: [From the protobuf docs](https://protobuf.dev/reference/python/python-generated/)

```sh
pip install protobuf
```

**quixio/quix-streams** (1.6K stars)

[quixio/quix-streams](https://github.com/quixio/quix-streams) 

```python
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

```

[quixstreams/models/serializers/protobuf.py](https://github.com/quixio/quix-streams/blob/e7fd055b09a0a6d458213be69c40064869ba3e82/quixstreams/models/serializers/protobuf.py) · [More projects using protobuf →](https://dashboard.exa.ai/playground/search?q=protobuf%20GitHub%20projects)

**Quickstart**

```python
from google.protobuf.struct_pb2 import Struct

message = Struct()
message["name"] = "Ada"
payload = message.SerializeToString()

```

From [README.md](https://protobuf.dev/reference/python/python-generated/)

### tomlkit

[GitHub](https://github.com/python-poetry/tomlkit) · [PyPI](https://pypi.org/project/tomlkit) · [Docs](https://tomlkit.readthedocs.io/en/latest/api/)

Edits TOML and preserves its style.

- Downloads / mo: 607.1M
- Stars: 871
- Last release: 0.15.2
- License: MIT
- Capabilities: [From the tomlkit docs](https://tomlkit.readthedocs.io/en/latest/api/)

```sh
pip install tomlkit
```

**dlt-hub/dlt** (6.1K stars)

[dlt-hub/dlt](https://github.com/dlt-hub/dlt) 

```python
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)

```

[dlt/common/configuration/providers/toml.py](https://github.com/dlt-hub/dlt/blob/efaf0e32d2ca3ac5f42653059065bb3ff8f972ec/dlt/common/configuration/providers/toml.py) · [More projects using tomlkit →](https://dashboard.exa.ai/playground/search?q=tomlkit%20GitHub%20projects)

**Quickstart**

```python
import tomlkit

document = tomlkit.document()
document["name"] = "Ada"
print(tomlkit.dumps(document))

```

From [README.md](https://tomlkit.readthedocs.io/en/latest/quickstart/)

### msgpack

[GitHub](https://github.com/msgpack/msgpack-python) · [PyPI](https://pypi.org/project/msgpack) · [Docs](https://msgpack-python.readthedocs.io/en/latest/api.html)

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
- Capabilities: [From the msgpack docs](https://msgpack-python.readthedocs.io/en/latest/api.html)

**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.

**Watch out for**

- **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.

```sh
pip install msgpack
```

**google/flax** (7.4K stars)

[google/flax](https://github.com/google/flax) 

```python
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)

```

[flax/serialization.py](https://github.com/google/flax/blob/204a819c2eb76281b47e4e4a967c578f5615705c/flax/serialization.py) · [More projects using msgpack →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20msgpack%20for%20object%20persistence%20dynamic%20function%20transfer%20model%20state%20and%20binary%20data%20encoding&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import msgpack

payload = msgpack.packb({"name": "Ada"})
print(msgpack.unpackb(payload))

```

From [README.md](https://msgpack-python.readthedocs.io/en/latest/api.html)

### orjson

[GitHub](https://github.com/ijl/orjson) · [PyPI](https://pypi.org/project/orjson) · [Docs](https://github.com/ijl/orjson/blob/main/README.md)

Encodes and decodes JSON with support for dataclasses, datetimes, and NumPy.

- Downloads / mo: 223.6M
- Stars: 8.3K
- Last release: 3.13.0
- License: MPL-2.0 AND (Apache-2.0 OR MIT)
- Capabilities: [From the orjson docs](https://github.com/ijl/orjson/blob/main/README.md)

```sh
pip install orjson
```

**zauberzeug/nicegui** (16.3K stars)

[zauberzeug/nicegui](https://github.com/zauberzeug/nicegui) 

```python
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')

```

[nicegui/json/orjson_wrapper.py](https://github.com/zauberzeug/nicegui/blob/884eb1c38e58f976bce451d4e19cf898b78dfefa/nicegui/json/orjson_wrapper.py) · [More projects using orjson →](https://dashboard.exa.ai/playground/search?q=orjson%20GitHub%20projects)

**Quickstart**

```python
import orjson

payload = orjson.dumps({"name": "Ada"})
print(orjson.loads(payload))

```

From [README.md](https://github.com/ijl/orjson/blob/main/README.md)

### cloudpickle

[GitHub](https://github.com/cloudpipe/cloudpickle) · [PyPI](https://pypi.org/project/cloudpickle) · [Docs](https://github.com/cloudpipe/cloudpickle/blob/main/README.md)

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
- Capabilities: [From the cloudpickle docs](https://github.com/cloudpipe/cloudpickle/blob/main/README.md)

**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.

**Watch out for**

- **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.

```sh
pip install cloudpickle
```

**dask/distributed** (1.7K stars)

[dask/distributed](https://github.com/dask/distributed) 

```python
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

```

[distributed/protocol/pickle.py](https://github.com/dask/distributed/blob/dc182bda54af488d029f2c40db0893d5f48e69d5/distributed/protocol/pickle.py) · [More projects using cloudpickle →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20cloudpickle%20for%20object%20persistence%20dynamic%20function%20transfer%20model%20state%20and%20binary%20data%20encoding&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import cloudpickle
import pickle

payload = cloudpickle.dumps(lambda value: value + 1)
restored = pickle.loads(payload)
print(restored(1))

```

From [README.md](https://github.com/cloudpipe/cloudpickle/blob/main/README.md)

### ruamel.yaml

[PyPI](https://pypi.org/project/ruamel.yaml) · [Docs](https://yaml.dev/doc/ruamel.yaml/basicuse/)

Parses and emits YAML with round-trip preservation of comments, flow style, and key order.

- Downloads / mo: 182.8M
- Last release: 0.19.1
- License: MIT
- Capabilities: [From the ruamel.yaml docs](https://yaml.dev/doc/ruamel.yaml/basicuse/)

```sh
pip install ruamel.yaml
```

**Quickstart**

```python
import sys
from ruamel.yaml import YAML

yaml = YAML()
yaml.dump({"name": "Ada"}, sys.stdout)

```

From [README.md](https://yaml.dev/doc/ruamel.yaml/basicuse/) · [Find projects using ruamel.yaml →](https://dashboard.exa.ai/playground/search?q=ruamel.yaml%20GitHub%20projects)

## FAQ

### Which Python serialization library should I use?

[orjson](#orjson) suits JSON with dataclasses, datetimes, and NumPy arrays. [ruamel.yaml](#ruamel-yaml) suits YAML files whose comments must survive a round trip. [msgpack](#msgpack) suits compact binary messages. [cloudpickle](#cloudpickle) suits shipping Python functions between processes.

### What is PyYAML?

[PyYAML](#pyyaml) is a YAML parser and emitter for Python. Loading and dumping objects does not preserve the comments in the original file.

### What is orjson?

[orjson](#orjson) is a JSON library with support for dataclasses, datetimes, and NumPy arrays. It returns bytes rather than a string.

### What is cloudpickle?

[cloudpickle](#cloudpickle) serializes Python functions and classes by value, including lambdas and interactive definitions. Loading may execute code. Only trusted data should be unpickled.

### What is tomlkit?

[tomlkit](#tomlkit) edits TOML documents and preserves their comments, indentation, whitespace, and element order.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python serialization libraries pickle cloudpickle dill msgpack code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
