232 CHAPTER 10 BATTERIES INCLUDED >>> import (Web design company)

232 CHAPTER 10 BATTERIES INCLUDED >>> import shelve >>> s = shelve.open(’test.dat’) >>> s[’x'] = [’a', ‘b’, ‘c’] >>> s[’x'].append(’d') >>> s[’x'] [’a', ‘b’, ‘c’] Where did the ‘d’ go? The explanation is simple: When you look up an element in a shelf object, the object is reconstructed from its stored version; and when you assign an element to a key, it is stored. What happened in the preceding example was the following: 1. The list [’a', ‘b’, ‘c’] was stored in s under the key ‘x’. 2. The stored representation was retrieved, a new list was constructed from it, and ‘d’was appended to the copy. This modified version was not stored! 3. Finally, the original is retrieved again without the ‘d’. To correctly modify an object that is stored using the shelve module, you must bind a temporary variable to the retrieved copy, and then store the copy again after it has been modified: >>> temp = s[’x'] >>> temp.append(’d') >>> s[’x'] = temp >>> s[’x'] [’a', ‘b’, ‘c’, ‘d’] Thanks to Luther Blissett for pointing this out. From Python 2.4 onward, there is another way around this problem: Setting the writeback parameter of the open function to true. If you do, all of the data structures that you read from or assign to the shelf will be kept around in memory (cached) and only written back to disk when you close the shelf. If you re not working with huge data, and you don t want to worry about these things, setting writeback to true (and making sure you close your shelf at the end) may be a good idea. Example Listing 10-8 shows a simple database application that uses the shelve module. Listing 10-8. A Simple Database Application # database.py import sys, shelve def store_person(db): “”" Query user for data and store it in the shelf object “”"
Note: In case you are looking for affordable and reliable webhost to host and run your j2ee application check Vision J2ee Web Hosting services.

Comments are closed.