Object Serialization
Picklable Types
Write and Read
  • cPickle has been removed in Python 3
  • #!/usr/bin/python
     
    import pickle
     
    f = open('temp.pkl', 'wb');
     
    l = list(range(10))
     
    pickle.dump(l, f, 0); #default, ASCII protocol
    #pickle.dump(l, f, 1); #old binary format
    #pickle.dump(l, f, 2); #efficient pickling of new-style classes
    #pickle.dump(l, f, -1); #highest available protocol
     
    f.close();
    
    f = open('temp.pkl', 'rb');
    
    l = pickle.load(f);
    
    print(l)
    
    f.close();
    		
    Pickle String
    #!/usr/bin/python
     
    import pickle
     
    l = list(range(10))
     
    s = pickle.dumps(l, 2);
    print(s)
     
    t = pickle.loads(s);
    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
  • #!/usr/bin/python
     
    class Vehicle(object):
     
        def __init__(self, brand):
            self.__brand = brand
     
        def __str__(self):
            return "Brand: %s" % self.__brand
     
        def __getstate__(self):
            print('Call __getstate__ for pickling ...')
            state = self.__dict__.copy()
            # Remove the unpicklable entries.
            #del state['file']
            return state
     
        def __setstate__(self, state):
            # Restore instance attributes
            print('Call __setstate__ for unpickling ...')
            self.__dict__.update(state)
            #self.__dict
     
    def main():
        v = Vehicle("Buick")
     
        import pickle
     
        # pickling
        f = open('temp.pkl', 'wb');
        pickle.dump(v, f, 0);
        f.close();
     
        # unpickling
        f = open('temp.pkl', 'rb');
        l = pickle.load(f);
        print(l);
        f.close();
     
        v2 = [Vehicle("Buick"), Vehicle("Honda")]
     
        # pickling
        f = open('temp.pkl', 'wb');
        pickle.dump(v2, f, 0);
        f.close();
     
        # unpickling
        f = open('temp.pkl', 'rb');
        l = pickle.load(f);
        for e in l:
            print(e)
        f.close();
     
    if __name__ == '__main__':
        main()
    		
    #!/usr/bin/python
    class MyRange:
        def __init__(self, start, stop, step):
            self.__sequence = range(start, stop, step);
     
        def __str__(self):
            s = '[';
            for i in self.__sequence:
                s = s + ' ' + str(i)
     
            return s + ' ]'
     
        def __getstate__(self):
            print('Call __getstate__ for pickling ...')
            state = self.__dict__.copy()
            print(state)
            # Remove the unpicklable entries.
            #del state['file']
            return state
     
        def __setstate__(self, state):
            # Restore instance attributes
            print('Call __setstate__ for unpickling ...')
            self.__dict__.update(state)
     
    def main():
        l = MyRange(0, 10, 1);
     
        import pickle
     
        # pickling
        f = open('temp.pkl', 'wb');
        pickle.dump(l, f, 0);
        f.close();
     
        # unpickling
        f = open('temp.pkl', 'rb');
        l = pickle.load(f);
        print(type(l), l);
        f.close();
     
    if __name__ == '__main__':
        main();
    		
    Reference