Object Serialization
Picklable Types
Write and Read
  1. #!/usr/bin/python
  2.  
  3. import cPickle
  4.  
  5. f = open('temp.pkl', 'wb');
  6.  
  7. l = range(10);
  8.  
  9. cPickle.dump(l, f, 0); #default, ASCII protocol
  10. #cPickle.dump(l, f, 1); #old binary format
  11. #cPickle.dump(l, f, 2); #efficient pickling of new-style classes
  12. #cPickle.dump(l, f, -1); #highest available protocol
  13.  
  14. f.close();
  1. #!/usr/bin/python
  2.  
  3. import cPickle
  4.  
  5. f = open('temp.pkl', 'rb');
  6.  
  7. l = cPickle.load(f);
  8.  
  9. print l;
  10.  
  11. f.close();
Pickle String
  1. #!/usr/bin/python
  2.  
  3. import cPickle
  4.  
  5. l = range(10);
  6.  
  7. s = cPickle.dumps(l);
  8.  
  9. t = cPickle.loads(s);
  10. print t;
Define picklable class
  • __getstate__, if the class defines the method __getstate__(), it is called and the return state is pickled as the contents for the instance, if there is no __getstate__() method, the instance's __dict__ is pickled
  • __setstate__, if the class also defines the method __setstate__(), it is called with the unpickled state, if there is no __setstate__() method, the pickled state must be a dictionary and its items are assigned to the new instance's dictionary
    1. #!/usr/bin/python
    2.  
    3. class Vehicle(object):
    4.  
    5. def __init__(self, brand):
    6. self.__brand = brand
    7.  
    8. def __str__(self):
    9. return "Brand: %s" % self.__brand
    10.  
    11. def __getstate__(self):
    12. print('Call __getstate__ for pickling ...')
    13. state = self.__dict__.copy()
    14. # Remove the unpicklable entries.
    15. #del state['file']
    16. return state
    17.  
    18. def __setstate__(self, state):
    19. # Restore instance attributes
    20. print('Call __setstate__ for unpickling ...')
    21. self.__dict__.update(state)
    22. #self.__dict
    23.  
    24. def main():
    25. v = Vehicle("Buick")
    26.  
    27. import cPickle
    28.  
    29. # pickling
    30. f = open('temp.pkl', 'wb');
    31. cPickle.dump(v, f, 0);
    32. f.close();
    33.  
    34. # unpickling
    35. f = open('temp.pkl', 'rb');
    36. l = cPickle.load(f);
    37. print(l);
    38. f.close();
    39.  
    40. v2 = [Vehicle("Buick"), Vehicle("Honda")]
    41.  
    42. # pickling
    43. f = open('temp.pkl', 'wb');
    44. cPickle.dump(v2, f, 0);
    45. f.close();
    46.  
    47. # unpickling
    48. f = open('temp.pkl', 'rb');
    49. l = cPickle.load(f);
    50. for e in l:
    51. print(e)
    52. f.close();
    53.  
    54. if __name__ == '__main__':
    55. main()
    1. #!/usr/bin/python
    2. class MyRange:
    3. def __init__(self, start, stop, step):
    4. self.__sequence = range(start, stop, step);
    5. def __str__(self):
    6. s = '[';
    7. for i in self.__sequence:
    8. s = s + ' ' + str(i)
    9.  
    10. return s + ' ]'
    11.  
    12. def __getstate__(self):
    13. print('Call __getstate__ for pickling ...')
    14. state = self.__dict__.copy()
    15. print(state)
    16. # Remove the unpicklable entries.
    17. #del state['file']
    18. return state
    19.  
    20. def __setstate__(self, state):
    21. # Restore instance attributes
    22. print('Call __setstate__ for unpickling ...')
    23. self.__dict__.update(state)
    24.  
    25. def main():
    26. l = MyRange(0, 10, 1);
    27.  
    28. import cPickle
    29.  
    30. # pickling
    31. f = open('temp.pkl', 'wb');
    32. cPickle.dump(l, f, 0);
    33. f.close();
    34.  
    35. # unpickling
    36. f = open('temp.pkl', 'rb');
    37. l = cPickle.load(f);
    38. print(l);
    39. f.close();
    40.  
    41. if __name__ == '__main__':
    42. main();
    Reference