Pickle is an important module whenever you need persistence between user sessions. Whether your are programming for a database, game, forum, or some other application that must save information between sessions, you will find pickle helpful for saving identifiers and settings. As a module, pickle provides for the saving of Python objects between processes.
The concept of pickling is known variously as serialisation, marshalling, or flattening. The point is the same: Save an object to a file for later retrieval. Pickling accomplishes this simply by writing the object as one long stream of bytes. To write an object to a file, you would use code that fits the following syntax:
import pickle
object = Object()
filehandler = open(filename, 'w')
pickle.dump(object, filehandler)
A real-world example would look like this:
import pickle
import math
object_pi = math.pi
file_pi = open('filename_pi.obj', 'w')
pickle.dump(object_pi, file_pi)
This snippet writes the contents of object_pi to the file handler
file_pi, which in turn is bound to the file 'filename_pi.obj' in the
directory of execution.
To restore the value of the object to memory, load the object from the file. Assuming that pickle has not yet been imported for use, start by importing it:
import pickle
filehandler = open(filename, 'r')
object = pickle.load(filehandler)
Carrying on from our previous syntax, the following code would restore the value of pi:
import pickle
file_pi2 = open('filename_pi.obj', 'r')
object_pi2 = pickle.load(file_pi2)
The object is then ready for use once again, this time as 'object_pi2'.
You can, of course, re-use the original names, if necessary. I have
used distinct names here for exemplary reasons only.
