if key in db:
record = db[key] # update existing record
else: # or make/store new rec
record = Person(name='?', age='?') # eval: quote strings
for field in fieldnames:
currval = getattr(record, field)
newtext = input('\t[%s]=%s\n\t\tnew?=>' % (field, currval))
if newtext:
setattr(record, field, eval(newtext))
db[key] = record
db.close()
Notice the use of eval in this script to convert inputs (as usual, that allows any Python
object type, but it means you must quote string inputs explicitly) and the use of
setattr call to assign an attribute given its name string. When run, this script allows
any number of records to be added and changed; to keep the current value of a record’s
field, press the Enter key when prompted for a new value:
Key? => tom
[name]=Tom Doe
new?=>
[age]=50
new?=> 56
[job]=None
new?=>'mgr'
[pay]=65000.0
new?=> 90000
Key? => nobody
[name]=?
new?=>'John Doh'
[age]=?
new?=> 55
[job]=None
new?=>
[pay]=0
new?=>None
Key? =>
This script is still fairly simplistic (e.g., errors aren’t handled), but using it is much easier
than manually opening and modifying the shelve at the Python interactive prompt,
especially for nonprogrammers. Run the query script to check your work after an up-
date (we could combine query and update into a single script if this becomes too cum-
bersome, albeit at some cost in code and user-experience complexity):
Key? => tom
name => Tom Doe
age => 56
job => mgr
pay => 90000
Key? => nobody
name => John Doh
Step 4: Adding Console Interaction | 39