How to Use Pickle to Save Objects in Python

Here's How to Save Objects in Python With Pickle Modules

Pickle, which is part of the Python library by default, is an important module whenever you need persistence between user sessions. As a module, pickle provides for the saving of Python objects between processes

Whether you 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.

The pickle module can store things like data types (e.g. booleans, strings, byte arrays), lists, dictionaries, functions, and more.

Note: The concept of pickling is also known as serialization, marshaling, or flattening. However, the point is always the same: to save an object to a file for later retrieval. Pickling accomplishes this simply by writing the object as one long stream of bytes. 

Pickle Example Code in Python

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) 

Here's how a real-world example may look:

 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.

Things to Remember About Pickle

Keep these in mind when using the pickle module:

  • The pickle protocol is specific to Python - it's not guaranteed to be cross-language compatible. This means you most likely can not transfer the information to make it useful in Perl, PHP, Java, etc.
  • There is also no guarantee of compatibility between different versions of Python. This is because not every Python data structure can be serialized by the module
  • By default, the latest version of the pickle protocol is used. It remains that way unless you manually change it

Where to Get More Information on Pickle

For a lot more information and example code on using pickle in Python, I highly recommend reading Mark Pilgrim's Chapter 13: Serializing Python Objects of Dive Into Python 3.

Tip: Also see how to use shelve to save objects in Python for another method of maintaining object continuity.