Deserialize to objects while staying DRY
Desert is a Python library that generates serialization schemas for dataclasses and attrs classes, building upon the Marshmallow library. It aims to help developers write DRY (Don't Repeat Yourself) code by automatically deriving serialization/deserialization logic from class definitions. The library is actively maintained, with its current version being 2022.9.22.
Common errors
-
TypeError: An Optional type expects 1 subtype
cause Incorrect usage of `typing.Optional` (e.g., `Optional` instead of `Optional[str]`) or conflicts arising from custom fields and `desert`'s type introspection.fixAlways use `Optional[Type]` (e.g., `Optional[str]`) and verify that any custom fields define their types in a way `desert` can resolve. -
AttributeError: 'NoneType' object has no attribute 'load' (or similar errors during schema generation)
cause Desert failed to generate a valid schema for a dataclass, often due to unsupported type hints, especially those conditionally defined within `if typing.TYPE_CHECKING:` blocks.fixEnsure that type hints essential for schema generation are not hidden within `TYPE_CHECKING` blocks or use `from __future__ import annotations` and ensure type resolution works at runtime. -
Different schema classes are generated per reference of the same data class.
cause Under certain conditions, `desert` might generate multiple distinct schema instances for what is conceptually the same dataclass, leading to inconsistent behavior.fixWhen possible, explicitly create and reuse a single schema instance for a given dataclass to ensure consistency. Investigate how dataclass references are managed in complex scenarios.
Warnings
- breaking Python 3.6 support was dropped in version 2022.09.22 to allow updating internal dependencies.
- gotcha Desert does not support string annotations and forward references inside of functions, which can lead to unexpected behavior or failures in schema generation.
- gotcha The library may encounter crashes or unexpected behavior when dealing with optional types that use custom fields or type hints encapsulated within `TYPE_CHECKING` blocks.
Install
-
pip install desert -
poetry add desert
Imports
- desert
import desert
- dataclass
from dataclasses import dataclass
Quickstart
from dataclasses import dataclass
from typing import List
import desert
@dataclass
class Person:
name: str
age: int
@dataclass
class Car:
passengers: List[Person]
# Load some simple data types.
data = {'passengers': [{'name': 'Alice', 'age': 21}, {'name': 'Bob', 'age': 22}]}
# Create a schema for the Car class.
schema = desert.schema(Car)
# Load the data.
car = schema.load(data)
assert car == Car(passengers=[Person(name='Alice', age=21), Person(name='Bob', age=22)])