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.
pip install pyserdeVerified import paths — ran on the pinned version, not inferred.
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.
Upgrade your Python interpreter to 3.10+ to use the latest versions of pyserde.
Install `pyserde` with the necessary extras, e.g., `pip install 'pyserde[json,yaml,orjson]'`.
Ensure your classes are defined as dataclasses (or `attrs` classes) before applying `@serde`.
Upgrade `pyserde` to 0.30.0 or later to utilize all advanced field customization options.
rustup component add rust-src
from pyserde import serde, field, to_json, from_json
from dataclasses import dataclass
from pyserde import serde, to_json
@serde
@dataclass
class MyData:
value: int
data = MyData(value=1)
print(to_json(data))from dataclasses import dataclass
from datetime import datetime
from pyserde import serde, field, to_json
@serde
@dataclass
class Event:
timestamp: datetime = field(
serializer=lambda dt: dt.isoformat(),
deserializer=lambda s: datetime.fromisoformat(s)
)
event = Event(timestamp=datetime.now())
print(to_json(event))