Yet another serialization library on top of dataclasses
—
pyserde provides dedicated modules for serializing to and from specific data formats. Each format module follows the same pattern with to_format and from_format functions, plus optional serializer classes for advanced usage.
JSON format support with both Python's standard json module and optional orjson for performance.
def to_json(
obj: Any,
cls: Optional[Any] = None,
se: type[Serializer[str]] = JsonSerializer,
reuse_instances: bool = False,
convert_sets: bool = True,
skip_none: bool = False,
**opts: Any,
) -> str:
"""
Serialize object to JSON string. orjson will be used if available.
Parameters:
- obj: Object to serialize
- cls: Optional class hint for serialization
- se: Serializer class to use (JsonSerializer by default)
- reuse_instances: Whether to reuse object instances
- convert_sets: Whether to convert sets to lists
- skip_none: Whether to skip None values
- **opts: Additional arguments passed to json.dumps() or orjson.dumps()
Returns:
JSON string representation
"""
def from_json(
c: type[T],
s: AnyStr,
de: type[Deserializer[AnyStr]] = JsonDeserializer,
**opts: Any
) -> T:
"""
Deserialize JSON string to object. orjson will be used if available.
Parameters:
- c: Target class type
- s: JSON string or bytes to deserialize
- de: Deserializer class to use (JsonDeserializer by default)
- **opts: Additional arguments passed to json.loads() or orjson.loads()
Returns:
Instance of class c populated from JSON data
"""
class JsonSerializer(Serializer[str]):
"""JSON serializer class for advanced usage."""
@classmethod
def serialize(cls, obj: Any, **opts: Any) -> str: ...
class JsonDeserializer(Deserializer[AnyStr]):
"""JSON deserializer class for advanced usage."""
@classmethod
def deserialize(cls, data: AnyStr, **opts: Any) -> Any: ...YAML format support using PyYAML library for human-readable configuration files.
def to_yaml(
obj: Any,
cls: Optional[Any] = None,
se: type[Serializer[str]] = YamlSerializer,
reuse_instances: bool = False,
convert_sets: bool = True,
skip_none: bool = False,
**opts: Any,
) -> str:
"""
Serialize object to YAML string.
Parameters:
- obj: Object to serialize
- cls: Optional class hint for serialization
- se: Serializer class to use (YamlSerializer by default)
- reuse_instances: Whether to reuse object instances
- convert_sets: Whether to convert sets to lists
- skip_none: Whether to skip None values
- **opts: Additional arguments passed to yaml.safe_dump()
Returns:
YAML string representation
"""
def from_yaml(
c: type[T],
s: str,
de: type[Deserializer[str]] = YamlDeserializer,
**opts: Any
) -> T:
"""
Deserialize YAML string to object.
Parameters:
- c: Target class type
- s: YAML string to deserialize
- de: Deserializer class to use (YamlDeserializer by default)
- **opts: Additional arguments passed to yaml.safe_load()
Returns:
Instance of class c populated from YAML data
"""
class YamlSerializer(Serializer[str]):
"""YAML serializer class for advanced usage."""
@classmethod
def serialize(cls, obj: Any, **opts: Any) -> str: ...
class YamlDeserializer(Deserializer[str]):
"""YAML deserializer class for advanced usage."""
@classmethod
def deserialize(cls, data: str, **opts: Any) -> Any: ...TOML format support for configuration files, using tomli and tomli-w libraries.
def to_toml(
obj: Any,
cls: Optional[Any] = None,
se: type[Serializer[str]] = TomlSerializer,
reuse_instances: bool = False,
convert_sets: bool = True,
skip_none: bool = True,
**opts: Any,
) -> str:
"""
Serialize object to TOML string.
Parameters:
- obj: Object to serialize
- cls: Optional class hint for serialization
- se: Serializer class to use (TomlSerializer by default)
- reuse_instances: Whether to reuse object instances
- convert_sets: Whether to convert sets to lists
- skip_none: Whether to skip None values (defaults to True for TOML)
- **opts: Additional arguments passed to tomli_w.dumps()
Returns:
TOML string representation
"""
def from_toml(
c: type[T],
s: str,
de: type[Deserializer[str]] = TomlDeserializer,
**opts: Any
) -> T:
"""
Deserialize TOML string to object.
Parameters:
- c: Target class type
- s: TOML string to deserialize
- de: Deserializer class to use (TomlDeserializer by default)
- **opts: Additional arguments passed to tomllib.loads()
Returns:
Instance of class c populated from TOML data
"""
class TomlSerializer(Serializer[str]):
"""TOML serializer class for advanced usage."""
@classmethod
def serialize(cls, obj: Any, **opts: Any) -> str: ...
class TomlDeserializer(Deserializer[str]):
"""TOML deserializer class for advanced usage."""
@classmethod
def deserialize(cls, data: str, **opts: Any) -> Any: ...Efficient binary serialization using MessagePack format for performance-critical applications.
def to_msgpack(
obj: Any,
cls: Optional[Any] = None,
se: type[Serializer[bytes]] = MsgPackSerializer,
named: bool = True,
ext_dict: Optional[dict[type[Any], int]] = None,
reuse_instances: bool = False,
convert_sets: bool = True,
**opts: Any,
) -> bytes:
"""
Serialize object to MessagePack bytes.
Parameters:
- obj: Object to serialize
- cls: Optional class hint for serialization
- se: Serializer class to use (MsgPackSerializer by default)
- named: If True, encode as dict; if False, encode as tuple for compact output
- ext_dict: Optional dict mapping types to extension type codes
- reuse_instances: Whether to reuse object instances
- convert_sets: Whether to convert sets to lists
- **opts: Additional arguments passed to msgpack.packb()
Returns:
MessagePack binary data
"""
def from_msgpack(
c: type[T],
s: bytes,
de: type[Deserializer[bytes]] = MsgPackDeserializer,
named: bool = True,
ext_dict: Optional[dict[int, type[Any]]] = None,
skip_none: bool = False,
**opts: Any,
) -> T:
"""
Deserialize MessagePack bytes to object.
Parameters:
- c: Target class type
- s: MessagePack binary data to deserialize
- de: Deserializer class to use (MsgPackDeserializer by default)
- named: If True, decode from dict; if False, decode from tuple
- ext_dict: Optional dict mapping extension type codes to types
- skip_none: Whether to skip None values
- **opts: Additional arguments passed to msgpack.unpackb()
Returns:
Instance of class c populated from MessagePack data
"""
class MsgPackSerializer(Serializer[bytes]):
"""MessagePack serializer class for advanced usage."""
@classmethod
def serialize(
cls,
obj: Any,
use_bin_type: bool = True,
ext_type_code: Optional[int] = None,
**opts: Any
) -> bytes: ...
class MsgPackDeserializer(Deserializer[bytes]):
"""MessagePack deserializer class for advanced usage."""
@classmethod
def deserialize(
cls,
data: bytes,
raw: bool = False,
use_list: bool = False,
**opts: Any
) -> Any: ...Python pickle format support for complete Python object serialization.
def to_pickle(
obj: Any,
cls: Optional[Any] = None,
se: type[Serializer[bytes]] = PickleSerializer,
reuse_instances: bool = False,
convert_sets: bool = True,
skip_none: bool = False,
**opts: Any,
) -> bytes:
"""
Serialize object to pickle bytes.
Parameters:
- obj: Object to serialize
- cls: Optional class hint for serialization
- se: Serializer class to use (PickleSerializer by default)
- reuse_instances: Whether to reuse object instances
- convert_sets: Whether to convert sets to lists
- skip_none: Whether to skip None values
- **opts: Additional arguments passed to pickle.dumps()
Returns:
Pickle binary data
"""
def from_pickle(
c: type[T],
data: bytes,
de: type[Deserializer[bytes]] = PickleDeserializer,
**opts: Any
) -> T:
"""
Deserialize pickle bytes to object.
Parameters:
- c: Target class type
- data: Pickle binary data to deserialize
- de: Deserializer class to use (PickleDeserializer by default)
- **opts: Additional arguments passed to pickle.loads()
Returns:
Instance of class c populated from pickle data
"""
class PickleSerializer(Serializer[bytes]):
"""Pickle serializer class for advanced usage."""
@classmethod
def serialize(cls, obj: Any, **opts: Any) -> bytes: ...
class PickleDeserializer(Deserializer[bytes]):
"""Pickle deserializer class for advanced usage."""
@classmethod
def deserialize(cls, data: bytes, **opts: Any) -> Any: ...from serde import serde
from serde.json import to_json, from_json
@serde
class Config:
host: str
port: int
debug: bool = False
config = Config("localhost", 8080, True)
json_str = to_json(config)
# '{"host":"localhost","port":8080,"debug":true}'
config_copy = from_json(Config, json_str)
# Config(host='localhost', port=8080, debug=True)from serde import serde
from serde.yaml import to_yaml, from_yaml
@serde
class DatabaseConfig:
host: str
port: int
username: str
password: str
db_config = DatabaseConfig("db.example.com", 5432, "admin", "secret")
yaml_str = to_yaml(db_config)
# host: db.example.com
# port: 5432
# username: admin
# password: secret
db_config_copy = from_yaml(DatabaseConfig, yaml_str)from serde import serde
from serde.msgpack import to_msgpack, from_msgpack
@serde
class Sensor:
id: int
temperature: float
humidity: float
timestamp: int
sensor = Sensor(1, 23.5, 45.0, 1640995200)
msgpack_data = to_msgpack(sensor) # Binary data
sensor_copy = from_msgpack(Sensor, msgpack_data)from serde import serde
from serde.json import to_json, from_json
from serde.yaml import to_yaml, from_yaml
from serde.toml import to_toml, from_toml
@serde
class AppConfig:
name: str
version: str
settings: dict
config = AppConfig("MyApp", "1.0.0", {"debug": True})
# Same object can be serialized to multiple formats
json_data = to_json(config)
yaml_data = to_yaml(config)
toml_data = to_toml(config)
# And deserialized from any format
config_from_json = from_json(AppConfig, json_data)
config_from_yaml = from_yaml(AppConfig, yaml_data)
config_from_toml = from_toml(AppConfig, toml_data)Install with Tessl CLI
npx tessl i tessl/pypi-pyserde