User Tools

Site Tools




The pickle module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure.
The pickle module has an optimized module called cPickle (written in C, that can be up to 1000 times faster than pickle, but it doesn't support subclassing of the Pickler() and Unpickler() classes).

What can pickled and unpickled?

The following types can be pickled:

  • None, True, and False
  • integers, long integers, floating point numbers, complex numbers
  • normal and Unicode strings
  • tuples, lists, sets, and dictionaries containing only picklable objects
  • functions defined at the top level of a module
  • built-in functions defined at the top level of a module
  • classes that are defined at the top level of a module
  • instances of such classes whose dict or setstate() is picklable (see section The pickle protocol for details)


To exemplify, we'll build a class with some simple methods, and then work with pickling on it:

#!/usr/bin/env python
# Cristian Navalici ncristian [ at ] lemonsoftware [.] eu
import pickle
import pprint
class Number():
    '''test class'''
    def __init__(self):
        '''Initialization method'''
        self.number = 1
    def set_number(self, value):
        self.number = int(value)
    def get_number(self):
        print "Number was %d" % self.number
# initialize a class object and then set a number
numberOb = Number()
raw_input("Press a key to continue with dumps")
# dumps - prints on the screen
print "-----------------------------"
print "dumps() in action "
pickles = pickle.dumps(numberOb)
print pickles
# now, write to a file
raw_input("Press a key to continue with writing to a file")
oFile = open('data.pkl', 'wb')
pickle.dump(numberOb, oFile)
# read back from the file
raw_input("Press a key to continue with reading from the file")
iFile = open('data.pkl', 'rb')
saved_obj = pickle.load(iFile )
# now, use further this as in the first lines of code

python/pickle.txt · Last modified: 2013/03/16 17:40 (external edit)