serializable saves Python objects as JSON or pickles and reconstructs the same
classes, including nested objects. Subclass DataclassSerializable for a
dataclass, or Serializable for a class whose constructor arguments describe
its state. It is the serialization layer of the OpenVax libraries:
varcode and
vaxrank results,
pyensembl genomes and
sercol collections all save and reload
through it.
python -m pip install serializablePython 3.11 or later is required.
from dataclasses import dataclass
from serializable import DataclassSerializable
@dataclass
class Point(DataclassSerializable):
x: float
y: float
point = Point(1.0, 2.0)
restored = Point.from_json(point.to_json())
print(point.to_dict())
print(restored)
print(restored == point){'x': 1.0, 'y': 2.0}
Point(x=1.0, y=2.0)
True
to_dict() gives the constructor fields; to_json() also records the class
and its module so from_json() can rebuild it. The dataclass keeps its own
generated constructor, equality, representation and hashing. The recorded module and
class must be importable when loading, so load data only from sources you
trust. A class or function defined inside another function can't be looked
up again, so serializing it raises ValueError.
The documentation covers, in reading order:
- Getting started: the example above, choosing a base class, and the format's limits.
- Save classes and files: constructor-based classes, JSON files, pickles and nested containers.
- Change field names: read data written before a constructor argument was renamed.
- API reference.
./develop.sh # strict editable install with dev dependencies into .venv
./format.sh # ruff format
./lint.sh # ruff check, ruff format --check and mypy
./test.sh # pytest with coverage
python -m pip install -r requirements-docs.txt
./docs.sh # mkdocs build --strict, then a rendered-link check
python scripts/check_docs_examples.py # run docs examples, compare outputTo install a checkout into another environment, use a strict editable install so type checkers in projects which depend on serializable can find it:
python -m pip install -C editable_mode=strict -e .Rerun that after adding or renaming a file in serializable/, or after
deleting the checkout's build/ directory, which is where the installed link
tree lives. Edits to existing files are picked up immediately.
Every PR bumps serializable/version.py. Maintainers release with
./deploy.sh from a clean master.
Apache 2.0; see LICENSE.