On this page
  1. dbm
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Opening Modes and Inspecting the Backend
  7. Gotchas & Boundaries
  8. Common Functions
  9. Constants & Attributes

dbm

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


Import

import dbm

Overview

Generic interface to lightweight, disk-backed key-value databases (dbm.sqlite3, dbm.ndbm, dbm.gnu, and pure-Python fallback dbm.dumb). Use dbm when you need fast persistent bytes/str key-value lookups without SQL schema design or pickle overhead.

Quick Start

import dbm
from pathlib import Path
import tempfile

with tempfile.TemporaryDirectory() as tmp:
    path = str(Path(tmp) / "store")
    with dbm.open(path, "c") as db:
        db["token"] = "abc123"
        assert db["token"] == b"abc123"   # values are always returned as bytes

Implementation Walkthrough

1. Opening Modes and Inspecting the Backend

dbm.open(file, flag="r") supports "r" (read-only), "w" (read/write existing), "c" (read/write, create if missing), and "n" (always create a fresh empty database). dbm.whichdb(path) reports which backend created an existing file:

import dbm
from pathlib import Path
import tempfile

with tempfile.TemporaryDirectory() as tmp:
    path = str(Path(tmp) / "kv")
    with dbm.open(path, "n") as db:
        db[b"k1"] = b"v1"
        db[b"k2"] = b"v2"
        keys = set(db.keys())

    assert keys == {b"k1", b"k2"}
    assert dbm.whichdb(path) is not None

Gotchas & Boundaries

Common Functions

Constants & Attributes

Linked from

Related notes