C:\...\PP4E\Dbase>python
>>> from filepickle import *
>>> table = loadDbase('myfile') # reload/unpickle
>>> table
{'A': [0], 'B': {'y': [0], 'x': 0}}
>>> table['A'][0] = 1 # change shared object
>>> saveDbase('myfile', table) # rewrite to the file
C:\...\PP4E\Dbase>python
>>> from filepickle import *
>>> print(loadDbase('myfile')) # both L's updated as expected
{'A': [1], 'B': {'y': [1], 'x': 0}}
Besides built-in types like the lists, tuples, and dictionaries of the examples so far, class
instances may also be pickled to file-like objects. This provides a natural way to associate
behavior with stored data (class methods process instance attributes) and provides a
simple migration path (class changes made in module files are automatically picked up
by stored instances). Here’s a brief interactive demonstration:
>>> class Rec:
def __init__(self, hours):
self.hours = hours
def pay(self, rate=50):
return self.hours * rate
>>> bob = Rec(40)
>>> import pickle
>>> pickle.dump(bob, open('bobrec', 'wb'))
>>>
>>> rec = pickle.load(open('bobrec', 'rb'))
>>> rec.hours
40
>>> rec.pay()
2000
We’ll explore how this works in more detail in conjunction with shelves later in this
chapter—as we’ll see, although the pickle module can be used directly this way, it is
also the underlying translation engine in both shelves and ZODB databases.
In general, Python can pickle just about anything, except for:
- Compiled code objects: functions and classes record just their names and those of
their modules in pickles, to allow for later reimport and automatic acquisition of
changes made in module files. - Instances of classes that do not follow class importability rules: in short, the class
must be importable on object loads (more on this at the end of the section “Shelve
Files” on page 1315). - Instances of some built-in and user-defined types that are coded in C or depend
upon transient operating system states (e.g., open file objects cannot be pickled).
A PicklingError is raised if an object cannot be pickled. Again, we’ll revisit the pickler’s
constraints on pickleable objects and classes when we study shelves.
Pickled Objects | 1313