Choose DBM or Relational Persistence
Core idea
dbm exposes persistent key-value storage with byte keys and byte values. Open mode c creates a database if absent; r opens an existing database read-only. Use an explicit encoding for text. SQLite provides relational queries, constraints and transaction controls. Choose based on data relationships, querying, concurrency and durability requirements rather than assuming that a dict-like interface has all database guarantees.
import dbmfrom tempfile import TemporaryDirectoryfrom pathlib import Pathwith TemporaryDirectory() as folder: path = str(Path(folder)/'settings') with dbm.open(path, 'c') as store: store[b'mode'] = 'آماده'.encode('utf-8') with dbm.open(path, 'r') as store: print(store[b'mode'].decode('utf-8')) print(store.get(b'missing', b'none'))Reopening retrieves the encoded value. get supplies an explicit missing-key default.
Query multiple relational records
import sqlite3from contextlib import closingwith closing(sqlite3.connect(":memory:", autocommit=False)) as db: db.execute('CREATE TABLE bins (zone TEXT, qty INTEGER)') db.executemany('INSERT INTO bins VALUES (?,?)', [('east',3),('east',4),('west',2)]) print(db.execute('SELECT zone, sum(qty) FROM bins GROUP BY zone ORDER BY zone').fetchall())SQL groups rows and sums quantities by zone; a DBM caller would need to implement that grouping itself.
Common mistake
DBM backends differ in file formats, locking and available features. Do not assume portability or multi-key atomic updates. Never use mode n on an existing store unless deliberate replacement is intended. Store only trusted data in pickle-based persistence.
Practice
Persist two byte keys in a private temporary store and reopen read-only. Explain when a relational query over several records would justify SQLite instead.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
DBM and persistence trade-offs
Check your understanding of dbm and persistence trade-offs.
What is printed?
import dbmfrom tempfile import TemporaryDirectoryfrom pathlib import Pathwith TemporaryDirectory() as d: with dbm.open(str(Path(d)/'data'),'c') as store: store[b'x']=b'7' print(type(store[b'x']).__name__)What is printed?
import dbmfrom tempfile import TemporaryDirectoryfrom pathlib import Pathwith TemporaryDirectory() as d: with dbm.open(str(Path(d)/'data'),'c') as store: print(store.get(b'x', b'fallback'))Which mode opens an existing DBM store read-only?
Which requirement favors SQLite over a simple DBM store?