objectif
Stocker des objets Python sérialisés sur disque (usage local et sûr).
code minimal
import shelve, tempfile, os, pathlib
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, "db")
with shelve.open(path) as db:
db["x"] = {"n": 1}
with shelve.open(path) as db:
print(db["x"]["n"] == 1) # attendu: True
utilisation
import shelve, tempfile, os
with tempfile.TemporaryDirectory() as tmp:
p = os.path.join(tmp, "kv")
with shelve.open(p, writeback=False) as db:
db["a"] = [1]; print("a" in db)
variante(s) utile(s)
import shelve
print(hasattr(shelve, "open"))
notes
- shelve repose sur dbm; ne chargez pas des données non fiables.
- writeback=False recommandé pour limiter la mémoire.