Book Image

Mastering Object-oriented Python

By : Steven F. Lott, Steven F. Lott
Book Image

Mastering Object-oriented Python

By: Steven F. Lott, Steven F. Lott

Overview of this book

Table of Contents (26 chapters)
Mastering Object-oriented Python
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Some Preliminaries
Index

Creating a shelf


The first part of creating a shelf is done using a module-level function, shelve.open(), to create a persistent shelf structure. The second part is closing the file properly so that all changes are written to the underlying filesystem. We'll look at this in a more complete example later.

Under the hood, the shelve module is using the dbm module to do the real work of opening a file and mapping from key to value. The dbm module itself is a wrapper around an underlying DBM-compatible library. Consequently, there are a number of potential implementations for the shelve features. The good news is that the differences among the dbm implementations are largely irrelevant.

The shelve.open() module function requires two parameters: the filename and the file access mode. Often, we want the default mode of 'c' to open an existing shelf or create one if it doesn't exist. The alternatives are for specialized situations:

  • 'r' is a read-only shelf

  • 'w' is a read-write shelf that must exist...