Saving and loading
Last updated
A library that forgets everything when the program stops isn't much use. In this lesson you'll write storage.py: every object turns itself into a dictionary with to_dict(), a class method from_dict() turns it back, a small factory makes the right kind of item from its kind, and a JsonStorage writes it all to a file, behind a Storage protocol that tests can swap for one in memory.
By the end of this lesson you can
- Turn objects into dictionaries JSON can hold, and back, with
to_dict()and a@classmethodfrom_dict() - Explain why JSON can't hold a
date, and store it as text - Load each item back as the right class with a factory
- Hide where data is kept behind a protocol (the repository pattern)
Objects out to dictionaries
JSON files (lesson 2.8) hold dictionaries, lists, text, numbers, true, false and null, but not your objects. So saving is two jobs: turn each object into a dictionary of plain values, then write the dictionaries out as JSON.
Each class does the first job for itself, with a to_dict() method. Items are dataclasses, so dataclasses.asdict() lists their fields for them, and LibraryItem.to_dict() adds the kind in front. Every kind of item inherits it, and each one's own fields come along:
library/items.py, lines 36–42def to_dict(self) -> dict[str, Any]: return {"kind": self.kind} | asdict(self) @classmethod def from_dict(cls, data: dict[str, Any]) -> Self: names = {f.name for f in fields(cls)} return cls(**{k: v for k, v in data.items() if k in names})
Member isn't a dataclass, so its to_dict() names its three values itself, and stores its policy by name. Press Run:
The "kind" is what lets a dictionary come back as the right class, in step 3.
JSON doesn't know dates
A loan holds dates. The wrong way: use asdict() for a loan too, and write it as JSON. Press Run:
The first print works, and shows datetime.date(2026, 3, 2) objects inside the dictionary. The second stops: TypeError: Object of type date is not JSON serializable. "Serializable" means "can be written out as text", and JSON has no type for dates.
So Loan.to_dict() writes each date as text with isoformat(): "2026-03-02", year first, so it also sorts properly. from_dict() reads it back with date.fromisoformat(). A loan that hasn't come back stores None, which JSON writes as null.
library/loans.py, lines 32–50def to_dict(self) -> dict[str, Any]: return { "item_id": self.item_id, "member_id": self.member_id, "lent_on": self.lent_on.isoformat(), "due_on": self.due_on.isoformat(), "returned_on": self.returned_on.isoformat() if self.returned_on else None, } @classmethod def from_dict(cls, data: dict[str, Any]) -> Self: back = data.get("returned_on") return cls( data["item_id"], data["member_id"], date.fromisoformat(data["lent_on"]), date.fromisoformat(data["due_on"]), date.fromisoformat(back) if back else None, )
Back in, as the right class
Loading goes the other way: a dictionary in, an object out. That's a second way to make an object, so it's a class method (lesson 3.4): Loan.from_dict(data) is called on the class and returns a new one. LibraryItem.from_dict is written once, in the parent, and works for every child: cls is whichever class it was called on, and it passes along only the keys that are that class's fields (so the kind is left out).
But which class? A saved item is just {"kind": "dvd", …}. A factory (lesson 4.16) answers that: one function that reads the kind, looks the class up in a dictionary, and makes one.
library/items.py, lines 103–111KINDS: dict[str, type[LibraryItem]] = {c.kind: c for c in (Book, ReferenceBook, DVD, Magazine)} def item_from_dict(data: dict[str, Any]) -> LibraryItem: """Makes the right kind of item from a saved dictionary: a factory.""" kind = data.get("kind") if kind not in KINDS: raise ValueError(f"unknown kind of item: {kind}") return KINDS[kind].from_dict(data)
KINDS is built from each class's own kind, so a new kind of item, say AudioBook, is one class and one name in that tuple. The loading code doesn't change. A kind it doesn't know is a ValueError, not something it guesses at.
A storage you can swap
The rest of the program shouldn't care where the library is kept: a JSON file today, maybe a database one day, and only memory in tests. So storage.py describes a repository (lesson 4.16) as a protocol: anything with save(library) and load(clock).
library/storage.py, lines 13–55class Storage(Protocol): """Anything that can save a library and load it back: a repository.""" def save(self, library: Library) -> None: ... def load(self, clock: Clock | None = None) -> Library: ... def to_data(library: Library) -> dict: return { "items": [item.to_dict() for item in library.catalogue], "members": [member.to_dict() for member in library.members()], "loans": [loan.to_dict() for loan in library.loans()], } def from_data(data: dict, clock: Clock | None = None) -> Library: library = Library(clock) library.restore( [item_from_dict(d) for d in data["items"]], [Member.from_dict(d) for d in data["members"]], [Loan.from_dict(d) for d in data["loans"]], ) return library class JsonStorage: """Keeps the library in a JSON file.""" def __init__(self, path: str | Path) -> None: self._path = Path(path) def save(self, library: Library) -> None: text = json.dumps(to_data(library), indent=2) # Write a new file, then swap it in, so a crash can't leave half a file. spare = self._path.with_suffix(".tmp") spare.write_text(text, encoding="utf-8") spare.replace(self._path) def load(self, clock: Clock | None = None) -> Library: if not self._path.exists(): return Library(clock) return from_data(json.loads(self._path.read_text(encoding="utf-8")), clock)
to_data gathers every item, member and loan as dictionaries, and from_data rebuilds a library from them with Library.restore(), which checks every loan's item and member exist. JsonStorage adds the file. It writes to a spare file first and then swaps it in with replace(), so if the program crashes halfway through writing, the old file is still whole. A missing file isn't an error: it's a new library.
This example saves to library.json in the page's folder and loads it back. Press Run, then look under the output: the page shows the file the run wrote.
The loaded library has the same loans (True), and d1 came back as a DVD, thanks to the factory. MemoryStorage, at the bottom of library/storage.py, keeps the same data in an attribute instead of a file. Nothing names the Storage protocol: both classes simply have the two methods, so either will do (lesson 4.14).
Check what you learned
On your computer, add to_dict() and from_dict() to your classes, write library/storage.py, and check a library saves and loads back the same. The reference's tests/test_storage.py uses pytest's tmp_path, a fresh empty folder for each test, so tests never touch your real library.json.
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- The Python Standard Library: json: the conversion table: which Python types JSON can hold
- dataclasses: asdict()
- datetime: date.isoformat() and date.fromisoformat()
- The Python Standard Library: pathlib: Path.write_text, Path.replace
- Martin Fowler: Repository