16.01.2014 Views

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

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 s<strong>to</strong>red version; and when you assign an element <strong>to</strong> a key, it is s<strong>to</strong>red.<br />

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

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

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

appended <strong>to</strong> the copy. This modified version was not s<strong>to</strong>red!<br />

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

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

temporary variable <strong>to</strong> the retrieved copy, and then s<strong>to</strong>re 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 <strong>to</strong> Luther Blissett for pointing this out.<br />

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

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

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

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

these things, setting writeback <strong>to</strong> 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 s<strong>to</strong>re_person(db):<br />

"""<br />

Query user for data and s<strong>to</strong>re it in the shelf object<br />

"""

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

Saved successfully!

Ooh no, something went wrong!