Object Serialization
Picklable Types
- 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 the result of calling __getstate__() is picklable (see section The pickle protocol for details).
Write and Read
#!/usr/bin/python
import cPickle
f = open('temp.pkl', 'wb');
l = range(10);
cPickle.dump(l, f, 0); #default, ASCII protocol
#cPickle.dump(l, f, 1); #old binary format
#cPickle.dump(l, f, 2); #efficient pickling of new-style classes
#cPickle.dump(l, f, -1); #highest available protocol
f.close();
#!/usr/bin/python
import cPickle
f = open('temp.pkl', 'rb');
l = cPickle.load(f);
print l;
f.close();
Pickle String
#!/usr/bin/python
import cPickle
l = range(10);
s = cPickle.dumps(l);
t = cPickle.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 cPickle
# pickling
f = open('temp.pkl', 'wb');
cPickle.dump(v, f, 0);
f.close();
# unpickling
f = open('temp.pkl', 'rb');
l = cPickle.load(f);
print(l);
f.close();
v2 = [Vehicle("Buick"), Vehicle("Honda")]
# pickling
f = open('temp.pkl', 'wb');
cPickle.dump(v2, f, 0);
f.close();
# unpickling
f = open('temp.pkl', 'rb');
l = cPickle.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 cPickle
# pickling
f = open('temp.pkl', 'wb');
cPickle.dump(l, f, 0);
f.close();
# unpickling
f = open('temp.pkl', 'rb');
l = cPickle.load(f);
print(l);
f.close();
if __name__ == '__main__':
main();
Reference