User Tools

Site Tools


python:pickle

PICKLE

09.July.2009

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)

Example

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

#!/usr/bin/env python
 
# EXAMPLE OF PICKLE
#
# 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()
numberOb.set_number(23)
numberOb.get_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)
oFile.close()
 
 
# 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 )
iFile.close()
 
pprint.pprint(saved_obj)
 
# now, use further this as in the first lines of code
saved_obj.get_number()

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