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).
The following types can be pickled:
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()