Any object that provides these attributes can be passed in to the file parameters. In
particular, file can be an instance of a Python class that provides the read/write meth-
ods (i.e., the expected file-like interface). This lets you map pickled streams to in-
memory objects with classes, for arbitrary use. For instance, the io.BytesIO class in the
standard library discussed in Chapter 3 provides an interface that maps file calls to and
from in-memory byte strings and is an alternative to the pickler’s dumps/loads string
calls.
This hook also lets you ship Python objects across a network, by providing sockets
wrapped to look like files in pickle calls at the sender, and unpickle calls at the receiver
(see “Making Sockets Look Like Files and Streams” on page 827 for more details). In
fact, for some, pickling Python objects across a trusted network serves as a simpler
alternative to network transport protocols such as SOAP and XML-RPC, provided that
Python is on both ends of the communication (pickled objects are represented with a
Python-specific format, not with XML text).
Recent changes: In Python 3.X, pickled objects are always represented
as bytes, not str, regardless of the protocol level which you request
(even the oldest ASCII protocol yields bytes). Because of this, files used
to store pickled Python objects should always be opened in binary mode.
Moreover, in 3.X an optimized _pickle implementation module is also
selected and used automatically if present. More on both topics later.
Pickling in Action
Although pickled objects can be shipped in exotic ways, in more typical use, to pickle
an object to a flat file, we just open the file in write mode and call the dump function:
C:\...\PP4E\Dbase> python
>>> table = {'a': [1, 2, 3],
'b': ['spam', 'eggs'],
'c': {'name':'bob'}}
>>>
>>> import pickle
>>> mydb = open('dbase', 'wb')
>>> pickle.dump(table, mydb)
Notice the nesting in the object pickled here—the pickler handles arbitrary structures.
Also note that we’re using binary mode files here; in Python 3.X, we really must, because
the pickled representation of an object is always a bytes object in all cases. To unpickle
later in another session or program run, simply reopen the file and call load:
C:\...\PP4E\Dbase> python
>>> import pickle
>>> mydb = open('dbase', 'rb')
>>> table = pickle.load(mydb)
>>> table
{'a': [1, 2, 3], 'c': {'name': 'bob'}, 'b': ['spam', 'eggs']}
Pickled Objects | 1311