Yet another serialization library on top of dataclasses
npx @tessl/cli install tessl/pypi-pyserde@0.25.0A comprehensive Python serialization library built on dataclasses that enables automatic conversion of Python objects to and from multiple data formats including JSON, YAML, TOML, MessagePack, and Pickle. Inspired by Rust's serde, it provides a decorator-based approach with extensive type system support and high-performance serialization.
pip install pyserdepip install pyserde[all] for all formatsfrom serde import serde, to_dict, from_dict, to_json, from_jsonFormat-specific imports:
from serde.json import to_json, from_json
from serde.yaml import to_yaml, from_yaml
from serde.toml import to_toml, from_toml
from serde.msgpack import to_msgpack, from_msgpack
from serde.pickle import to_pickle, from_picklefrom serde import serde, to_dict, from_dict
from serde.json import to_json, from_json
@serde
class Person:
name: str
age: int
email: str | None = None
# Create an instance
person = Person(name="Alice", age=30, email="alice@example.com")
# Serialize to JSON
json_data = to_json(person)
# '{"name":"Alice","age":30,"email":"alice@example.com"}'
# Deserialize from JSON
person_copy = from_json(Person, json_data)
# Person(name='Alice', age=30, email='alice@example.com')
# Serialize to dictionary
dict_data = to_dict(person)
# {'name': 'Alice', 'age': 30, 'email': 'alice@example.com'}
# Deserialize from dictionary
person_from_dict = from_dict(Person, dict_data)pyserde uses a code generation approach for high performance:
The fundamental serialization and deserialization functionality that powers all format-specific modules. Provides the @serde decorator and core conversion functions.
def serde(
_cls: Any = None,
rename_all: Optional[str] = None,
reuse_instances_default: bool = True,
convert_sets_default: bool = False,
serializer: Optional[SerializeFunc] = None,
deserializer: Optional[DeserializeFunc] = None,
tagging: Tagging = DefaultTagging,
type_check: TypeCheck = strict,
serialize_class_var: bool = False,
class_serializer: Optional[ClassSerializer] = None,
class_deserializer: Optional[ClassDeserializer] = None,
deny_unknown_fields: bool = False,
) -> Any: ...
def to_dict(
o: Any,
c: Optional[type[Any]] = None,
reuse_instances: Optional[bool] = None,
convert_sets: Optional[bool] = None,
skip_none: bool = False,
) -> dict[Any, Any]: ...
def from_dict(cls: type[T], o: dict[str, Any], reuse_instances: Optional[bool] = None) -> T: ...
def to_tuple(
o: Any,
c: Optional[type[Any]] = None,
reuse_instances: Optional[bool] = None,
convert_sets: Optional[bool] = None,
skip_none: bool = False,
) -> tuple[Any, ...]: ...
def from_tuple(cls: type[T], o: Any, reuse_instances: Optional[bool] = None) -> T: ...Serialization and deserialization functions for specific data formats including JSON, YAML, TOML, MessagePack, and Pickle.
# JSON
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: ...
def from_json(
c: type[T],
s: AnyStr,
de: type[Deserializer[AnyStr]] = JsonDeserializer,
**opts: Any
) -> T: ...
# YAML
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: ...
def from_yaml(
c: type[T],
s: str,
de: type[Deserializer[str]] = YamlDeserializer,
**opts: Any
) -> T: ...
# TOML
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: ...
def from_toml(
c: type[T],
s: str,
de: type[Deserializer[str]] = TomlDeserializer,
**opts: Any
) -> T: ...Advanced field-level configuration for custom serialization behavior, field renaming, skipping, and custom serializers.
def field(
default=...,
default_factory=...,
init: bool = True,
repr: bool = True,
hash: bool | None = None,
compare: bool = True,
metadata: dict | None = None,
rename: str | None = None,
serializer: Callable | None = None,
deserializer: Callable | None = None,
flatten: bool = False,
skip: bool = False,
skip_if: Callable | None = None,
skip_if_false: bool = False,
skip_if_default: bool = False,
) -> Any: ...Advanced type system features including union type handling with different tagging strategies and configurable type checking modes.
# Tagging strategies
class ExternalTagging: ...
class InternalTagging: ...
class AdjacentTagging: ...
class Untagged: ...
# Type checking modes
class TypeCheck: ...
strict: TypeCheck
disabled: TypeCheck
coerce: TypeCheckComprehensive type introspection and compatibility utilities for working with Python's type system, generics, and complex nested types.
def is_union(typ) -> bool: ...
def is_opt(typ) -> bool: ...
def is_list(typ) -> bool: ...
def is_dict(typ) -> bool: ...
def get_origin(typ): ...
def get_args(typ): ...Tools for debugging and inspecting generated serialization code.
def inspect(cls: type[Any]) -> None:
"""
Inspect a pyserde class and print generated code.
Parameters:
- cls: Pyserde-decorated class to inspect
"""from typing import TypeVar, Protocol, Callable, Any
T = TypeVar('T')
class SerializeFunc(Protocol):
def __call__(self, obj: Any) -> Any: ...
class DeserializeFunc(Protocol):
def __call__(self, cls: type, obj: Any) -> Any: ...
class ClassSerializer(Protocol):
def serialize(self, obj: Any) -> Any: ...
class ClassDeserializer(Protocol):
def deserialize(self, cls: type, data: Any) -> Any: ...
class Tagging:
"""Base class for union tagging strategies."""
class TypeCheck:
"""Type checking configuration."""
class SerdeError(Exception):
"""Base exception for serde errors."""
class SerdeSkip(Exception):
"""Exception to skip field serialization."""