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, in the Designing an access layer for shelve section.

Under the hood, the shelve module is using the dbm module to do the real work of opening a file and mapping from a key to a 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 or an exception will be raised.
  • 'n' is a new, empty shelf; any previous version will be overwritten.

It's absolutely essential to close a shelf to be sure that it is properly persisted to disk. The shelf is not a context manager itself, but the contextlib.closing() function should always be used to make sure that the shelf is closed. For more information on context managers, see Chapter 6, Using Callables and Contexts.

Under some circumstances, we might also want to explicitly synchronize a shelf to a disk without closing the file. The shelve.sync() method will persist changes prior to a close. An idealized life cycle looks something like the following code:

import shelve 
from contextlib import closing 
from pathlib import Path

db_path = Path.cwd() / "data" / "ch11_blog"
with closing(shelve.open(str(db_path))) as shelf:
process(shelf)

We've opened a shelf and provided that open shelf to some function that does the real work of our application. When this process is finished, the context will ensure that the shelf is closed. If the process() function raises an exception, the shelf will still be properly closed.

Let's see how to design shelvable objects.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset