The pickle and cPickle Module

The pickle and cPickle modules serialize objects to and from files

  • To serialize, you 'pickle' an object
     import pickle
     p = pickle.Pickler(file)      # file is an open file object
     p.dump(obj)                   # Dump object
  • To unserialize, you 'unpickle' an object
     p = pickle.Unpickler(file)    # file is an open file 
     obj = p.load()                # Load object

Notes

  • Most built-in types can be pickled except for files, sockets, execution frames, etc...
  • The data-encoding is Python-specific.
  • Any file-like object that provides write(),read(), and readline() methods can be used as a file.
  • Recursive objects are correctly handled.
  • cPickle is like pickle, but written in C and is substantially faster.
  • pickle can be subclassed, cPickle can not.
<<< O'Reilly OSCON 2000, Advanced Python Programming, Slide 46
July 17, 2000, beazley@cs.uchicago.edu
>>>