The object you get back from unpickling has the same value and reference structure as
the original, but it is located at a different address in memory. This is true whether the
object is unpickled in the same or a future process. Again, the unpickled object is ==
but is not is:
C:\...\PP4E\Dbase> python
>>> import pickle
>>> f = open('temp', 'wb')
>>> x = ['Hello', ('pickle', 'world')] # list with nested tuple
>>> pickle.dump(x, f)
>>> f.close() # close to flush changes
>>>
>>> f = open('temp', 'rb')
>>> y = pickle.load(f)
>>> y
['Hello', ('pickle', 'world')]
>>>
>>> x == y, x is y # same value, diff objects
(True, False)
To make this process simpler still, the module in Example 17-1 wraps pickling and
unpickling calls in functions that also open the files where the serialized form of the
object is stored.
Example 17-1. PP4E\Dbase\filepickle.py
"Pickle to/from flat file utilities"
import pickle
def saveDbase(filename, object):
"save object to file"
file = open(filename, 'wb')
pickle.dump(object, file) # pickle to binary file
file.close() # any file-like object will do
def loadDbase(filename):
"load object from file"
file = open(filename, 'rb')
object = pickle.load(file) # unpickle from binary file
file.close() # re-creates object in memory
return object
To store and fetch now, simply call these module functions; here they are in action
managing a fairly complex structure with multiple references to the same nested
object—the nested list called L at first is stored only once in the file:
C:\...\PP4E\Dbase> python
>>> from filepickle import *
>>> L = [0]
>>> D = {'x':0, 'y':L}
>>> table = {'A':L, 'B':D} # L appears twice
>>> saveDbase('myfile', table) # serialize to file
1312 | Chapter 17: Databases and Persistence