04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

232 CHAPTER 10 ■ BATTERIES INCLUDED<br />

>>> import shelve<br />

>>> s = shelve.open('test.dat')<br />

>>> s['x'] = ['a', 'b', 'c']<br />

>>> s['x'].append('d')<br />

>>> s['x']<br />

['a', 'b', 'c']<br />

Where did the 'd' go?<br />

The explanation is simple: When you look up an element in a shelf object, the object is<br />

reconstructed from its stored version; and when you assign an element to a key, it is stored.<br />

What happened in the preceding example was the following:<br />

1. The list ['a', 'b', 'c'] was stored in s under the key 'x'.<br />

2. The stored representation was retrieved, a new list was constructed from it, and 'd' was<br />

appended to the copy. This modified version was not stored!<br />

3. Finally, the original is retrieved again—without the 'd'.<br />

To correctly modify an object that is stored using the shelve module, you must bind a<br />

temporary variable to the retrieved copy, and then store the copy again after it has been modified:<br />

>>> temp = s['x']<br />

>>> temp.append('d')<br />

>>> s['x'] = temp<br />

>>> s['x']<br />

['a', 'b', 'c', 'd']<br />

Thanks to Luther Blissett for pointing this out.<br />

From Python 2.4 onward, there is another way around this problem: Setting the writeback<br />

parameter of the open function to true. If you do, all of the data structures that you read from or<br />

assign to the shelf will be kept around in memory (cached) and only written back to disk when<br />

you close the shelf. If you’re not working with huge data, and you don’t want to worry about<br />

these things, setting writeback to true (and making sure you close your shelf at the end) may be<br />

a good idea.<br />

Example<br />

Listing 10-8 shows a simple database application that uses the shelve module.<br />

Listing 10-8. A Simple Database Application<br />

# database.py<br />

import sys, shelve<br />

def store_person(db):<br />

"""<br />

Query user for data and store it in the shelf object<br />

"""

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!