Skip to content

About

Base class with serialization methods for user-defined Python objects

Resources

Stars

0 stars

Watchers

6 watching

Forks

Repository files navigation

Tests Documentation PyPI PyPI downloads

serializable

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.

Install

python -m pip install serializable

Python 3.11 or later is required.

Quick start

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.

Documentation

The documentation covers, in reading order:

  1. Getting started: the example above, choosing a base class, and the format's limits.
  2. Save classes and files: constructor-based classes, JSON files, pickles and nested containers.
  3. Change field names: read data written before a constructor argument was renamed.
  4. API reference.

Development

./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 output

To 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.

License

Apache 2.0; see LICENSE.

About

Base class with serialization methods for user-defined Python objects

Resources

Stars

0 stars

Watchers

6 watching

Forks

Releases

Packages

Used by

Contributors

Languages