Object Persistence Modules

Three modules compose the object persistence interface:

anydbm

Key-based string-only storage files.

pickle (and cPickle)

Serializes an in-memory object to/from file streams.

shelve

Key-based persistent object stores: pickles objects to/from anydbm files.

The shelve module implements persistent object stores. shelve in turn uses the pickle module to convert (serialize) in-memory Python objects to byte-stream strings and the anydbm module to store serialized byte-stream strings in access-by-key files. See also Section 1.25 later in the book (not part of the standard library).

anydbm and shelve Interfaces

DBM is an access-by-key filesystem: strings are stored and fetched by their string keys. The anydbm module selects the keyed-access file implementation in your Python interpreter and presents a dictionary-like API for scripts. A persistent object shelve is used like a simple anydbm file, except that the anydbm module is replaced by shelve, and the stored value can be almost any kind of Python object (but keys are still strings).

import shelve
import anydbm

Gets dbm, gbmd, bsddb... whatever is installed.

file = shelve.open('filename')
file = anydbm.open('filename', 'c')

Creates a new or opens an existing dbm file.

file['key1'] = value

Store: creates or changes the entry for 'key1'.

value = file['key2']

Fetch: loads the value for the 'key2' entry.

count = len(file)

Size: returns the number of entries stored.

index = file.keys( )

Index: fetches the stored keys list (can use in ...

Get Python Pocket Reference, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.