liveBook · Manning

Shelve.open

As explained in The Quick Python Book, Fourth Edition

shelve.open is the shelve module function that opens or creates a file-backed shelf and returns a shelf object.

shelve.open opens an existing shelf or creates its backing file when needed, returning a shelf object that behaves like a persistent dictionary. section 13.9

Use the returned shelf much like a dictionary, with these important differences:

  • Assign, look up, delete, test membership, and inspect keys with ordinary dictionary-style operations. section 13.9
  • Use only strings as keys; stored values can be structured objects such as tuples. section 13.9
  • Keep data on disk rather than loading the entire shelf into memory, accessing file contents as needed. section 13.9
  • Call close when the session ends so the shelf file is properly closed. section 13.9

Persistent address book

Open an address book, assign records by last name, close it, and reopen it later. A lookup such as book['flintstone'] returns the previously stored tuple, making the shelf act like a persistent dictionary. section 13.9

import shelve
book = shelve.open("addresses") 

Start a shelf with import shelve and book = shelve.open("addresses"). section 13.9

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains creation, dictionary operations, string-key restrictions, disk storage, and closing, but does not detail implementation internals.
Examples
Uses an address book keyed by last name, with tuple records containing names, phone numbers, and addresses.
What it assumes
Assumes familiarity with Python dictionaries and the interactive shell while demonstrating shelf behavior through an address-book task.
What you can do after
Operate it via Python's shelve module to create, update, close, reopen, and query persistent dictionary-like data.
How it connects
Connects persistent storage with dictionaries, file access, key assignment, lookup, deletion, membership, and serialization-like object storage.

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.