Pickle In Python

Introduction

The Pickle Module of Python is used for serializing and deserializing Python Object structures. Through Pickle functions the Python Object Hierarchy can be serialized (pickling) into a byte stream and through deserialization (unpickling) the byte-stream is converted back into Python Objects. Before diving into the details of Pickle, let’s briefly understand what Serialization and Deserialization are. Serialization is the process of saving a state of an object by converting an object into a stream of bytes to store the object into memory or file system.

Deserialization is reverse, it’s the process of converting a stream of bytes to object

Pickle

Pickle has two most important methods for Serializing and Deserializing they are ‘dump’ and ‘load’. Through ‘dump’ method Is used for Serializing and the ‘load’ method should be used for Deserializing. The example in the article will save the state of an object in a file.

dump

Let’s understand the dump through the simple Python program.

import pickle 

def serialize():
    data = {"name": "Mark", "age": 30, "dept": "IT"}
    file = open("employee.txt", "wb")
    pickle.dump(data, file)
    file.close()

serialize()

The code above has one method ‘serialize’ which saves the byte stream to a file. The ‘dump’ method takes two parameters, the first parameter is the data, and the second parameter is a file that should be in write-binary (wb) mode, where we are storing the bytes. The content of the file is in bytes,

load

Through load, function is the deserialization process

import pickle

def deserialize():
    file = open("employee.txt", "rb")
    data = pickle.load(file)
    print(data)
    file.close()

deserialize()

The load function takes a file object which will be in read-binary (rb) mode.

Pickling and Unpickling Custom Object

Create a custom employee object

class Employee():
    def __init__(self, name, age, dept):
        self.name = name
        self.age = age
        self.dept = dept
    
emp = Employee('Mark', 30, "IT")

Pickle Employee Object

import pickle

def serializeEmployee():
    file = open("employee.txt", "wb")
    pickle.dump(emp, file)
    file.close()

serializeEmployee()

Unpickle Employee Object

import pickle 

def deserialize():
    file = open("employee.txt", "rb")
    emp = pickle.load(file)
    print(emp.name, "-", emp.age, "-" , emp.dept)
    file.close()

deserialize()

Summary

The article explained the Serialization and Deserialization process of Python Object structures using the Pickle module, article also explained the Pickling and Unpickling of Python custom objects. Pickle only works with Python object structures it doesn’t support cross-language solution.