Python Design Patterns - Strings & Serialization



String serialization is the process of writing a state of object into a byte stream. In python, the pickle library is used for enabling serialization. This module includes a powerful algorithm for serializing and de-serializing a Python object structure. Pickling is the process of converting Python object hierarchy into byte stream and unpickling is the reverse procedure.

Example - Serialization

The demonstration of the pickle module is as follows −

main.py

import pickle

#Here's an example dict
grades = { 'Alice': 89, 'Bob': 72, 'Charles': 87 }

#Use dumps to convert the object to a serialized string
serial_grades = pickle.dumps( grades )
print(serial_grades)

#Use loads to de-serialize an object
received_grades = pickle.loads( serial_grades )
print(received_grades)

Output

The above program generates the following output −

b'\x80\x05\x95#\x00\x00\x00\x00\x00\x00\x00}\x94(\x8c\x05Alice\x94KY\x8c\x03Bob\x94KH\x8c\x07Charles\x94KWu.'
{'Alice': 89, 'Bob': 72, 'Charles': 87}
Advertisements