How to Use Pickle to Save Objects in Python

Two rows of pickles
Paul Taylor / Getty Images

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, pickle is useful for saving identifiers and settings. The pickle module can store things such as data types such as booleans, strings, and byte arrays, lists, dictionaries, functions, and more.

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

Pickle Example Code in Python

To write an object to a file, you use code in the following syntax:

import pickle
object = Object()
filehandler = open(filename, 'w')
pickle.dump(object, filehandler)

Here's how a real-world example looks:

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)

The following code restores 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, reuse the original names, if you prefer.

This example uses distinct names for clarity.

Things to Remember About Pickle

Keep these things in mind when using the pickle module:

  • The pickle protocol is specific to Python – it's not guaranteed to be cross-language compatible. You most likely cannot transfer the information to make it useful in Perl, PHP, Java, or other languages.
  • There is also no guarantee of compatibility between different versions of Python. IThe incompatibility exists 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.

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

mla apa chicago
Your Citation
Lukaszewski, Al. "How to Use Pickle to Save Objects in Python." ThoughtCo, Feb. 12, 2018, Lukaszewski, Al. (2018, February 12). How to Use Pickle to Save Objects in Python. Retrieved from Lukaszewski, Al. "How to Use Pickle to Save Objects in Python." ThoughtCo. (accessed April 20, 2018).