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.

234 CHAPTER 10 ■ BATTERIES INCLUDED<br />

■Caution As you can see, the program specifies the file name C:\database.dat. If you, by any chance,<br />

have a database by that name that the shelve module can use, it will—and that database will be modified.<br />

So make sure that you use a file name for your database that isn’t in use already. After running this program,<br />

the proper file appears.<br />

The program shown in Listing 10-8 has several interesting features:<br />

• I have wrapped everything in functions to make the program more structured. (A possible improvement<br />

is to group those functions as the methods of a class.)<br />

• I have put the main program in the main function, which is called only if __name__ == '__main__'.<br />

That means you can import this as a module and then call the main function from another program.<br />

• I open a database (shelf) in the main function, and then pass it as a parameter to the other functions<br />

that need it. I could have used a global variable, too, because this program is so small, but it’s better to<br />

avoid global variables in most cases, unless you have a reason to use them.<br />

• After reading in some values, I make a modified version by calling strip and lower on them because<br />

if a supplied key is to match one stored in the database, the two must be exactly alike. If you always use<br />

strip and lower on what the user enters, you can allow him or her to be sloppy about using uppercase<br />

or lowercase letters and additional whitespace. Also, note that I’ve used capitalize when printing the<br />

field name.<br />

• I have used try and finally to ensure that the database is closed properly. You never know when<br />

something might go wrong (and you get an exception), and if the program terminates without closing<br />

the database properly, you may end up with a corrupt database file that is essentially useless. By using<br />

try and finally, you avoid that.<br />

So, let’s take this database out for a spin. Here is the interaction between the program and me:<br />

Enter command (? for help): ?<br />

The available commands are:<br />

store : Stores information about a person<br />

lookup : Looks up a person from ID number<br />

quit : Save changes and exit<br />

? : Prints this message<br />

Enter command (? for help): store<br />

Enter unique ID number: 001<br />

Enter name: Mr. Gumby<br />

Enter age: 42<br />

Enter phone number: 555-1234<br />

Enter command (? for help): lookup<br />

Enter ID number: 001<br />

What would you like to know? (name, age, phone) phone<br />

Phone: 555-1234<br />

Enter command (? for help): quit

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

Saved successfully!

Ooh no, something went wrong!