PySerde: Serialization for Dataclasses
PySerde is a Python serialization/deserialization library built on top of dataclasses, inspired by Rust's Serde. It allows for declarative definition of data structures and automatically generates serialization and deserialization functions for various formats like JSON, YAML, TOML, and MessagePack. Currently at version 0.31.2, it maintains an active release cadence with frequent bug fixes and minor feature additions.
Warnings
- breaking PySerde version 0.31.2 and later requires Python 3.10 or newer. Attempting to install or use these versions on older Python interpreters will result in an installation error.
- gotcha To use serialization/deserialization for specific formats (e.g., YAML, TOML, faster JSON backends like `orjson`), you must install `pyserde` with the corresponding extras. The base `pip install pyserde` only includes JSON support via Python's standard `json` library.
- gotcha The `@serde` decorator is designed to be applied to `dataclasses.dataclass` (or `attrs` classes when using `serde_attrs`). It will not work on plain Python classes, as it relies on the metadata and structure provided by dataclasses.
- gotcha Advanced field options such as `skip_if_none`, `skip_if_default`, `flatten`, `skip_serializing`, and `skip_deserializing` were introduced in versions 0.29.0 and 0.30.0. If you rely on these specific features, ensure your `pyserde` installation is version 0.30.0 or later.
Install
-
pip install pyserde -
pip install 'pyserde[json,yaml,toml]' # Install with common backends
Imports
- serde
from serde import serde
- field
from serde import field
- to_json
from serde.json import to_json
- from_json
from serde.json import from_json
Quickstart
from dataclasses import dataclass
from serde import serde, field
from serde.json import to_json, from_json
@serde
@dataclass
class User:
name: str
age: int = field(default=30)
email: str | None = None
# Create an instance
user_instance = User(name="Alice", email="alice@example.com")
# Serialize to JSON string
json_string = to_json(user_instance)
print(f"Serialized JSON: {json_string}")
# Deserialize from JSON string
deserialized_user = from_json(User, json_string)
print(f"Deserialized User: {deserialized_user}")
# The @serde decorator also adds to_dict() and from_dict() methods directly to the class
user_dict = user_instance.to_dict()
print(f"Converted to dict: {user_dict}")
another_user = User.from_dict({"name": "Bob", "age": 25, "email": "bob@example.com"})
print(f"Created from dict: {another_user}")