liveBook · Manning

Shelf object

As explained in The Quick Python Book, Fourth Edition

A shelf object is a file-backed mapping that stores picklable Python objects under string keys and retrieves them through dictionary-like operations.

A shelf object is a persistent, file-backed mapping returned by shelve.open. It behaves like a dictionary while storing data on disk instead of keeping the entire dataset in memory. section 13.9

Use shelf objects like dictionaries, with a few important differences:

  • Assign and retrieve values, delete entries, test membership, and call keys(). section 13.9
  • Use only strings as keys, although stored values may be picklable Python objects. section 13.9
  • Let shelve perform file access when needed, supporting fast lookups and datasets too large to fit in memory. section 13.9
  • Close the shelf when finished so the persistent mapping can be reopened later. section 13.9

Persisting an address book

Open an address-book shelf, assign entries under string keys, close it, and reopen it in another session. Looking up book['flintstone'] returns the stored tuple. section 13.9

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

Start a shelf by importing shelve and opening a named file. section 13.9

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains operations, string-key restrictions, persistence, on-demand file access, and lookup advantages without detailing storage internals.
Examples
Demonstrates a persistent address book with tuple values, string keys, reopening, lookup, and explicit closing.
What it assumes
Assumes familiarity with Python dictionaries and objects while establishing disk persistence through shelve.open.
What you can do after
Operate a persistent mapping with shelve.open, dictionary operations, lookups, and close.
How it connects
Connects dictionaries, pickling, file-backed storage, and large-dataset access.

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.