PySerde: Serialization for Dataclasses

0.31.2 · active · verified Sun Apr 12

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

Install

Imports

Quickstart

Decorate a dataclass with `@serde` to enable serialization and deserialization. Use format-specific functions like `to_json` and `from_json` from `serde.json`. The `@serde` decorator also adds `to_dict()` and `from_dict()` methods directly to the class for generic dictionary conversion.

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}")

view raw JSON →