How to serialize a Python class?


Object serialization and deserialization are a routine aspect of any non-trivial Python program. Saving to a file, reading a configuration file, responding to an HTTP request, all involve object serialization and deserialization. 

Serialization and deserialization involve various schemes, formats and protocols to stream Python objects and to get them back later intact. Serialization schemes, formats or protocols you choose determine how fast your program runs and how secure it is.

Lets use a dictionary of python objects to serialize. Class is also a Python object. We use a Python module named pickle and its method pickle.dumps(object).

foo = dict(int_list=[3, 4, 5],  text='Hello World', number=9.99, boolean=False, none=None)
import cPickle as pickle

print pickle.dumps(foo)

print pickle.dumps(foo, protocol=pickle.HIGHEST_PROTOCOL)

Updated on: 16-Jun-2020

249 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements