Note that we don’t need to reimport the Person class here in order to fetch its instances
from the shelve or run their methods. When instances are shelved or pickled, the un-
derlying pickling system records both instance attributes and enough information to
locate their classes automatically when they are later fetched (the class’s module simply
has to be on the module search path when an instance is loaded). This is on purpose;
because the class and its instances in the shelve are stored separately, you can change
the class to modify the way stored instances are interpreted when loaded (more on this
later in the book). Here is the shelve dump script’s output just after creating the shelve
with the maker script:
bob =>
Bob Smith 30000
sue =>
Sue Jones 40000
tom =>
Tom Doe 50000
Smith
Doe
As shown in Example 1-20, database updates are as simple as before (compare this to
Example 1-13), but dictionary keys become attributes of instance objects, and updates
are implemented by class method calls instead of hardcoded logic. Notice how we still
fetch, update, and reassign to keys to update the shelve.
Example 1-20. PP4E\Preview\update_db_classes.py
import shelve
db = shelve.open('class-shelve')
sue = db['sue']
sue.giveRaise(.25)
db['sue'] = sue
tom = db['tom']
tom.giveRaise(.20)
db['tom'] = tom
db.close()
And last but not least, here is the dump script again after running the update script;
Tom and Sue have new pay values, because these objects are now persistent in the
shelve. We could also open and inspect the shelve by typing code at Python’s interactive
command line; despite its longevity, the shelve is just a Python object containing Python
objects.
bob =>
Bob Smith 30000
sue =>
Sue Jones 50000.0
tom =>
Tom Doe 65000.0
Smith
Doe
Step 3: Stepping Up to OOP | 35