[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1
Python code Action Description
index = file.keys() Index Fetch the stored keys list (an iterable view)
found = 'key' in file Query See if there’s an entry for key
del file['key'] Delete Remove the entry for key
for key in file: Iterate Iterate over stored keys
file.close() Close Manual close, not always needed

Because shelves export a dictionary-like interface, too, this table is almost identical to
the DBM operation table. Here, though, the module name dbm is replaced by shelve,
open calls do not require a second c argument, and stored values can be nearly arbitrary
kinds of objects, not just strings. Keys are still strings, though (technically, keys are
always a str which is encoded to and from bytes automatically per UTF-8), and you
still should close shelves explicitly after making changes to be safe: shelves use dbm
internally, and some underlying DBMs require closes to avoid data loss or damage.


Recent changes: The shelve module now has an optional writeback ar-
gument; if passed True, all entries fetched are cached in memory, and
written back to disk automatically at close time. This obviates the need
to manually reassign changed mutable entries to flush them to disk, but
can perform poorly if many items are fetched—it may require a large
amount of memory for the cache, and it can make the close operation
slow since all fetched entries must be written back to disk (Python can-
not tell which of the objects may have been changed).
Besides allowing values to be arbitrary objects instead of just strings, in
Python 3.X the shelve interface differs from the DBM interface in two
subtler ways. First, the keys method returns an iterable view object (not
a physical list). Second, the values of keys are always str in your code,
not bytes—on fetches, stores, deletes, and other contexts, the str keys
you use are encoded to the bytes expected by DBM using the UTF-8
Unicode encoding. This means that unlike dbm, you cannot use bytes
for shelve keys in your code to employ arbitrary encodings.
Shelve keys are also decoded from bytes to str per UTF-8 whenever they
are returned from the shelve API (e.g., keys iteration). Stored values are
always the bytes object produced by the pickler to represent a serialized
object. We’ll see these behaviors in action in the examples of this
section.

Storing Built-in Object Types in Shelves


Let’s run an interactive session to experiment with shelve interfaces. As mentioned,
shelves are essentially just persistent dictionaries of objects, which you open and close:


C:\...\PP4E\Dbase> python
>>> import shelve

Shelve Files | 1317
Free download pdf