liveBook · Manning

Shelve

As explained in The Quick Python Book, Fourth Edition

shelve is a Python standard-library module that provides persistent dictionary-like storage for Python objects, typically backed by serialization.

shelve provides persistent, dictionary-like storage for Python objects. Instead of keeping every value in memory, it stores data in a file on disk while preserving key-based access. section 13.9

Use shelve when an application needs convenient access to parts of a large collection:

  • Open a shelf with shelve.open(); the address-book file is created if it does not already exist. section 13.9
  • Read and write entries with dictionary syntax, but use strings for keys. section 13.9
  • Close the shelf after updating it so the stored data can be reused later. section 13.9
  • Access individual pieces of a large file without reading or writing the entire collection. section 13.9

A persistent address book

import shelve book = shelve.open("addresses") book['flintstone'] = ('fred', '555-1234', '1233 Bedrock Place') book['rubble'] = ('barney', '555-4321', '1235 Bedrock Place') book.close() book = shelve.open("addresses") print(book['flintstone']) # ('fred', '555-1234', '1233 Bedrock Place') section 13.9

The shelf behaves like a persistent dictionary: values entered in one Python session remain available when the same shelf is opened again. It is convenient for object storage, though database applications may benefit most when many accesses target large files. section 13.9 section 13.11

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains opening, indexing, closing, reopening, and persistence through an address-book example, without implementation internals.
Examples
Demonstrates a string-keyed address book whose tuple values survive closing and reopening the shelf.
What it assumes
Assumes general Python and dictionary knowledge while demonstrating shelve through a small interactive address-book task.
What you can do after
Operate/configure a persistent shelf by opening it, assigning and retrieving entries, closing it, and reopening it later.
How it connects
Connects shelve with dictionaries, pickle-based object storage, file operations, and database-style access to large files.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.