Shelf Storage (Persistent Dicts with shelve)
The `shelve` module combines `dbm` and `pickle`. It allows you to store arbitrary Python objects (lists, custom class instances, nested dicts) in a persistent key-value shelf on disk 📚.
import shelve, tempfile
with tempfile.TemporaryDirectory() as td:
shelf_path = f"{td}/app_shelf"
# Write complex object:
with shelve.open(shelf_path) as s:
s["user_prefs"] = {"theme": "dark", "fontSize": 14}
# Read back:
with shelve.open(shelf_path) as s:
print(f"Theme: {s['user_prefs']['theme']} 📚")
# 25. Shelf Storage (Persistent Dicts with shelve) The `shelve` module combines `dbm` and `pickle`. It allows you to store arbitrary Python objects (lists, custom class instances, nested dicts) in a persistent key-value shelf on disk 📚. ```python import shelve, tempfile with tempfile.TemporaryDirectory() as td: shelf_path = f"{td}/app_shelf" # Write complex object: with shelve.open(shelf_path) as s: s["user_prefs"] = {"theme": "dark", "fontSize": 14} # Read back: with shelve.open(shelf_path) as s: print(f"Theme: {s['user_prefs']['theme']} 📚") ``` Note: modifying mutable values inside a shelf (`s['list'].append(1)`) won't save automatically unless you pass `writeback=True` to `shelve.open()`! 📚 --- ### Question How does `shelve` improve upon raw `dbm` storage? 🧠- [ ] a. Values can be arbitrary pickle-serializable Python objects instead of raw bytes 📚 - [ ] b. It provides full SQL relational query support - [ ] c. It automatically runs in a distributed Redis cluster - [ ] d. It guarantees zero disk write operations --- ### Challenge Import `shelve` and `tempfile`. Open a shelf in a temp folder. Store `shelf['scores'] = [10, 20, 30]`. Close, reopen in read mode, and print `sum(shelf['scores'])`. 🎯 <details> <summary>Solution</summary> ```python import shelve, tempfile with tempfile.TemporaryDirectory() as td: path = f"{td}/test_shelf" with shelve.open(path) as s: s["scores"] = [10, 20, 30] with shelve.open(path) as s: print(sum(s["scores"])) ``` </details>