Claude Code for shelve: Python Persistent Key-Value Store — Claude Skills 360 Blog
Blog / AI / Claude Code for shelve: Python Persistent Key-Value Store
AI

Claude Code for shelve: Python Persistent Key-Value Store

Published: September 25, 2028
Read time: 5 min read
By: Claude Skills 360

Python’s shelve module provides a persistent dictionary backed by dbm that stores arbitrary picklable Python objects. import shelve. open: db = shelve.open("mystore") — creates/opens mystore.db (or platform-specific suffix); db["key"] = obj; obj = db["key"]; del db["key"]; db.close(). Context manager: with shelve.open("store") as db: — auto-closes. flag: "c" (default) create-or-open; "r" read-only; "n" always create fresh; "w" open existing for write. writeback: shelve.open("store", writeback=True) — tracks and re-writes mutable values (e.g. lists) automatically on sync()/close(); without writeback, you must re-assign: db["k"] = db["k"] after mutation. sync: db.sync() — flush pending writeback changes. keys/values/items: list(db.keys()) → list of str keys. "key" in db — membership test. get: db.get("key", default). update: db.update({"a": 1, "b": 2}). pop: db.pop("key", default). Shelf is not thread-safe; use a lock for concurrent access. Values must be picklable. Claude Code generates persistent caches, CLI session stores, incremental job result databases, and offline object stores.

CLAUDE.md for shelve

## shelve Stack
- Stdlib: import shelve
- Open:   with shelve.open("store") as db:
- Write:  db["key"] = {"any": "picklable", "value": True}
- Read:   val = db.get("key", default)
- Mutate: db["k"] = db["k"]; db["k"].append(x)  # or use writeback=True
- Keys:   list(db.keys())

shelve Persistent Store Pipeline

# app/shelveutil.py — open, CRUD, batch, TTL cache, typed store, migration
from __future__ import annotations

import shelve
import threading
import time
from contextlib import contextmanager
from dataclasses import dataclass, asdict, field
from pathlib import Path
from typing import Any, Callable, Generator, Generic, Iterable, Iterator, TypeVar

V = TypeVar("V")


# ─────────────────────────────────────────────────────────────────────────────
# 1. Safe open helper
# ─────────────────────────────────────────────────────────────────────────────

@contextmanager
def open_shelf(
    path: str | Path,
    flag: str = "c",
    writeback: bool = False,
) -> Generator[shelve.Shelf, None, None]:
    """
    Open a shelf as a context manager, ensuring close() on exit.

    flag: "c" create/open (default), "r" read-only, "n" new, "w" open existing.
    writeback: if True, mutable items are tracked and re-written on sync/close.

    Example:
        with open_shelf("session") as db:
            db["user"] = {"name": "Alice", "visits": 0}
    """
    db = shelve.open(str(path), flag=flag, writeback=writeback)
    try:
        yield db
    finally:
        db.close()


# ─────────────────────────────────────────────────────────────────────────────
# 2. CRUD helpers
# ─────────────────────────────────────────────────────────────────────────────

def shelf_get(path: str | Path, key: str, default: Any = None) -> Any:
    """
    Read a single value from a shelf.

    Example:
        user = shelf_get("session", "user")
    """
    with open_shelf(path, "r") as db:
        return db.get(key, default)


def shelf_set(path: str | Path, key: str, value: Any) -> None:
    """
    Write a single value to a shelf (creates if absent).

    Example:
        shelf_set("session", "user", {"name": "Bob"})
    """
    with open_shelf(path) as db:
        db[key] = value


def shelf_delete(path: str | Path, key: str) -> bool:
    """
    Delete a key from a shelf. Returns True if key existed.

    Example:
        shelf_delete("session", "temp_token")
    """
    with open_shelf(path) as db:
        if key in db:
            del db[key]
            return True
    return False


def shelf_keys(path: str | Path) -> list[str]:
    """Return all keys in a shelf."""
    with open_shelf(path, "r") as db:
        return list(db.keys())


def shelf_update(path: str | Path, data: dict[str, Any]) -> None:
    """
    Write multiple key-value pairs to a shelf at once.

    Example:
        shelf_update("config", {"debug": True, "timeout": 30})
    """
    with open_shelf(path) as db:
        db.update(data)


def shelf_load(path: str | Path) -> dict[str, Any]:
    """
    Load all key-value pairs from a shelf into a plain dict.

    Example:
        data = shelf_load("config")
    """
    with open_shelf(path, "r") as db:
        return dict(db.items())


def shelf_dump(path: str | Path, data: dict[str, Any], clear: bool = False) -> None:
    """
    Write all entries from data into a shelf.
    If clear=True, remove all existing keys first.

    Example:
        shelf_dump("config", {"key": "val"}, clear=True)
    """
    flag = "n" if clear else "c"
    with open_shelf(path, flag) as db:
        db.update(data)


# ─────────────────────────────────────────────────────────────────────────────
# 3. TTL-aware shelf cache
# ─────────────────────────────────────────────────────────────────────────────

@dataclass
class _TTLEntry:
    value: Any
    expires_at: float  # unix timestamp; 0 = never


class ShelfCache:
    """
    Persistent key-value cache with optional TTL (time-to-live) per entry.
    Backed by shelve; thread-safe via a reentrant lock.

    Example:
        cache = ShelfCache("cache/results")
        cache.set("expensive_key", result, ttl=3600)   # expire in 1 hour
        val = cache.get("expensive_key")
        if val is None:
            val = compute()
            cache.set("expensive_key", val, ttl=3600)
    """

    def __init__(self, path: str | Path, writeback: bool = False) -> None:
        self._path = str(path)
        self._writeback = writeback
        self._lock = threading.RLock()

    def get(self, key: str, default: Any = None) -> Any:
        """Return cached value or default (None if expired)."""
        with self._lock, open_shelf(self._path, "r") as db:
            entry: _TTLEntry | None = db.get(key)
            if entry is None:
                return default
            if entry.expires_at and time.time() > entry.expires_at:
                return default
            return entry.value

    def set(self, key: str, value: Any, ttl: float | None = None) -> None:
        """Store value with optional TTL seconds."""
        expires_at = time.time() + ttl if ttl else 0.0
        with self._lock, open_shelf(self._path) as db:
            db[key] = _TTLEntry(value=value, expires_at=expires_at)

    def delete(self, key: str) -> bool:
        with self._lock, open_shelf(self._path) as db:
            if key in db:
                del db[key]
                return True
        return False

    def clear_expired(self) -> int:
        """Remove all expired entries. Returns count removed."""
        now = time.time()
        removed = 0
        with self._lock, open_shelf(self._path) as db:
            expired = [k for k, v in db.items()
                       if isinstance(v, _TTLEntry) and v.expires_at and now > v.expires_at]
            for k in expired:
                del db[k]
                removed += 1
        return removed

    def keys(self) -> list[str]:
        with self._lock, open_shelf(self._path, "r") as db:
            return list(db.keys())

    def __contains__(self, key: str) -> bool:
        return self.get(key) is not None


# ─────────────────────────────────────────────────────────────────────────────
# 4. Typed shelf
# ─────────────────────────────────────────────────────────────────────────────

class TypedShelf(Generic[V]):
    """
    A shelf wrapper that encodes/decodes values via a transform function pair.
    Useful for storing dataclasses or other typed objects as plain dicts.

    Example:
        @dataclass
        class Job:
            id: str
            status: str
            result: Any = None

        store = TypedShelf[Job](
            "jobs",
            encode=lambda j: asdict(j),
            decode=lambda d: Job(**d),
        )
        store.set("job-1", Job(id="job-1", status="pending"))
        job = store.get("job-1")
    """

    def __init__(
        self,
        path: str | Path,
        encode: Callable[[V], Any],
        decode: Callable[[Any], V],
    ) -> None:
        self._path = str(path)
        self._encode = encode
        self._decode = decode

    def get(self, key: str, default: V | None = None) -> V | None:
        with open_shelf(self._path, "r") as db:
            raw = db.get(key)
            return self._decode(raw) if raw is not None else default

    def set(self, key: str, value: V) -> None:
        with open_shelf(self._path) as db:
            db[key] = self._encode(value)

    def delete(self, key: str) -> bool:
        with open_shelf(self._path) as db:
            if key in db:
                del db[key]
                return True
        return False

    def all(self) -> dict[str, V]:
        with open_shelf(self._path, "r") as db:
            return {k: self._decode(v) for k, v in db.items()}

    def keys(self) -> list[str]:
        with open_shelf(self._path, "r") as db:
            return list(db.keys())


# ─────────────────────────────────────────────────────────────────────────────
# 5. Migration / inspection helpers
# ─────────────────────────────────────────────────────────────────────────────

def shelf_migrate(
    src: str | Path,
    dst: str | Path,
    transform: Callable[[str, Any], tuple[str, Any] | None],
) -> int:
    """
    Copy entries from src shelf to dst shelf, applying transform(key, value).
    Return (new_key, new_value) to copy, None to skip an entry.
    Returns number of entries written.

    Example:
        # Rename a key and drop entries where value is None
        def xform(k, v):
            if v is None:
                return None
            return k.removeprefix("old_"), v
        shelf_migrate("store_v1", "store_v2", xform)
    """
    written = 0
    with open_shelf(src, "r") as src_db, open_shelf(dst) as dst_db:
        for key in list(src_db.keys()):
            result = transform(key, src_db[key])
            if result is not None:
                new_key, new_value = result
                dst_db[new_key] = new_value
                written += 1
    return written


# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    import tempfile
    from dataclasses import dataclass as dc, asdict

    print("=== shelve demo ===")

    with tempfile.TemporaryDirectory() as tmpdir:
        store_path = Path(tmpdir) / "demo"

        # ── basic CRUD ─────────────────────────────────────────────────────────
        print("\n--- basic CRUD ---")
        shelf_update(str(store_path), {
            "user:1": {"name": "Alice", "score": 100},
            "user:2": {"name": "Bob",   "score": 85},
            "config": {"debug": False, "version": "1.2"},
        })
        print(f"  keys: {shelf_keys(str(store_path))}")
        print(f"  user:1: {shelf_get(str(store_path), 'user:1')}")
        shelf_set(str(store_path), "user:1", {"name": "Alice", "score": 110})
        print(f"  updated user:1: {shelf_get(str(store_path), 'user:1')}")
        shelf_delete(str(store_path), "user:2")
        print(f"  after delete: {shelf_keys(str(store_path))}")

        # ── writeback ─────────────────────────────────────────────────────────
        print("\n--- writeback ---")
        with open_shelf(str(store_path), writeback=True) as db:
            db["items"] = [1, 2, 3]
            db["items"].append(4)   # writeback tracks this mutation
        print(f"  items after writeback: {shelf_get(str(store_path), 'items')}")

        # ── ShelfCache TTL ─────────────────────────────────────────────────────
        print("\n--- ShelfCache ---")
        cache = ShelfCache(Path(tmpdir) / "cache")
        cache.set("result", {"data": [1, 2, 3]}, ttl=60)
        print(f"  hit: {cache.get('result')}")
        print(f"  miss: {cache.get('missing', 'default')!r}")
        # Simulate expiry
        cache.set("old", "stale", ttl=0.001)
        time.sleep(0.01)
        print(f"  expired: {cache.get('old')!r}")
        removed = cache.clear_expired()
        print(f"  cleared {removed} expired entries")

        # ── TypedShelf ─────────────────────────────────────────────────────────
        print("\n--- TypedShelf ---")
        @dc
        class Task:
            id: str
            status: str
            priority: int = 0

        task_store: TypedShelf[Task] = TypedShelf(
            Path(tmpdir) / "tasks",
            encode=lambda t: asdict(t),
            decode=lambda d: Task(**d),
        )
        task_store.set("t1", Task(id="t1", status="pending", priority=1))
        task_store.set("t2", Task(id="t2", status="done",    priority=2))
        for k, v in task_store.all().items():
            print(f"  {k}: {v}")

        # ── migration ──────────────────────────────────────────────────────────
        print("\n--- shelf_migrate ---")
        def _upgrade(k: str, v: Any) -> tuple[str, Any] | None:
            if k.startswith("user:"):
                uid = k.split(":")[1]
                return f"u{uid}", {**v, "active": True}
            return None
        written = shelf_migrate(str(store_path), str(Path(tmpdir) / "store_v2"), _upgrade)
        print(f"  migrated {written} entries")
        print(f"  new store: {shelf_load(str(Path(tmpdir) / 'store_v2'))}")

    print("\n=== done ===")

For the dbm alternative — dbm is the lower-level module that shelve builds on; dbm.open() returns a bytes-key → bytes-value mapping without automatic pickling, so you must serialize/deserialize values yourself — use dbm directly when you need raw bytes storage with minimal overhead, when you’re storing string or bytes values only, or when you want to control serialization format (JSON, msgpack) instead of pickle; use shelve when you want to store arbitrary Python objects with zero serialization boilerplate. For the sqlite3 alternative — sqlite3 stores data in a relational table with full SQL query support, ACID transactions, concurrent reads, and a stable on-disk format readable by any SQLite-compatible tool — use sqlite3 when you need queries on stored data, multi-process access, data durability guarantees, or when the store must be inspectable with external tools; use shelve for simple single-process persistent caches or session stores where the only access pattern is get / set by string key and you want Python objects stored without schema design. The Claude Skills 360 bundle includes shelve skill sets covering open_shelf() context manager, shelf_get()/shelf_set()/shelf_delete()/shelf_keys()/shelf_update()/shelf_load()/shelf_dump() CRUD helpers, ShelfCache TTL-aware persistent cache with clear_expired(), TypedShelf[V] generic typed wrapper with encode/decode, and shelf_migrate() versioned data migration helper. Start with the free tier to try persistent cache patterns and shelve pipeline code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free