Such refactoring (restructuring) of code is common as class hierarchies grow and evolve.
In fact, as is, we still can’t give someone a raise if his pay is zero (Bob is out of luck);
we probably need a way to set pay, too, but we’ll leave such extensions for the next
release. The good news is that Python’s flexibility and readability make refactoring
easy—it’s simple and quick to restructure your code. If you haven’t used the language
yet, you’ll find that Python development is largely an exercise in rapid, incremental,
and interactive programming, which is well suited to the shifting needs of real-world
projects.
Adding Persistence
It’s time for a status update. We now have encapsulated in the form of classes custom-
izable implementations of our records and their processing logic. Making our class-
based records persistent is a minor last step. We could store them in per-record pickle
files again; a shelve-based storage medium will do just as well for our goals and is often
easier to code. Example 1-18 shows how.
Example 1-18. PP4E\Preview\make_db_classes.py
import shelve
from person import Person
from manager import Manager
bob = Person('Bob Smith', 42, 30000, 'software')
sue = Person('Sue Jones', 45, 40000, 'hardware')
tom = Manager('Tom Doe', 50, 50000)
db = shelve.open('class-shelve')
db['bob'] = bob
db['sue'] = sue
db['tom'] = tom
db.close()
This file creates three class instances (two from the original class and one from its
customization) and assigns them to keys in a newly created shelve file to store them
permanently. In other words, it creates a shelve of class instances; to our code, the
database looks just like a dictionary of class instances, but the top-level dictionary is
mapped to a shelve file again. To check our work, Example 1-19 reads the shelve and
prints fields of its records.
Example 1-19. PP4E\Preview\dump_db_classes.py
import shelve
db = shelve.open('class-shelve')
for key in db:
print(key, '=>\n ', db[key].name, db[key].pay)
bob = db['bob']
print(bob.lastName())
print(db['tom'].lastName())
34 | Chapter 1: A Sneak Preview