On this page
  1. shelve
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Mutating Nested Objects Safely
  7. Gotchas & Boundaries
  8. Common Functions
  9. Classes & Objects

shelve

Prev: selectors | Up: stdlib_module | Next: shlex
Rel: pickle, copyreg, marshal, dbm, sqlite3
Ref: docs.python.org — shelve
Tags: #public #python3 #stdlib


Import

import shelve

Overview

Persistent, dictionary-like key-value store backed by dbm files and pickle serialization. Use shelve for quick local persistence of arbitrary Python objects keyed by strings when setting up sqlite3 tables feels heavier than needed.

Quick Start

import shelve
from pathlib import Path
import tempfile

with tempfile.TemporaryDirectory() as tmp:
    db_path = str(Path(tmp) / "cache")
    with shelve.open(db_path) as db:
        db["user:1"] = {"name": "Ada", "roles": ["admin"]}

    with shelve.open(db_path) as db:
        assert db["user:1"]["name"] == "Ada"

Implementation Walkthrough

1. Mutating Nested Objects Safely

By default, shelve does not detect in-place mutations to mutable values (like db["tags"].append("new")). Either reassign the key explicitly or open with writeback=True (and call db.sync()):

import shelve
from pathlib import Path
import tempfile

with tempfile.TemporaryDirectory() as tmp:
    db_path = str(Path(tmp) / "prefs")
    with shelve.open(db_path) as db:
        db["tags"] = ["python"]
        # Explicit read-modify-write avoids writeback memory overhead
        tags = db["tags"]
        tags.append("stdlib")
        db["tags"] = tags

    with shelve.open(db_path) as db:
        assert db["tags"] == ["python", "stdlib"]

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes