Pickle Module : Pickling(Serializing) And Unpickling(De-serializing) Of Python Objects

Overview:

  • Python objects can be serialized into binary form and deserialized back to Python objects using the methods and classes available from the Python module pickle.
  • The process of converting a Python object into binary form is called Pickling.
  • The process of converting the binary stream back to a Python object is called Unpickling.
  • Pickled objects can be stored in a disk file and unpickled back as objects.
  • The Python module pickle provides the methods, classes, constants and exceptions to be used during the pickling process.
  • While the dump() variants pickle the Python object hierarchies the load() variants unpickle the bytes back into Python object hierarchies.

Pickling and unpickling in Python

Example:

In the Python example code below, the method pickle.dump() is used to convert a Python object type Part into a byte stream. The pickle.load() is used to convert the byte stream back to a Python object.

import pickle

 

# Class definition of a part

class Part:

    number = 0

    name   = ""

 

    def __init__(self, number, name):

        self.number  = number

        self.name    = name

       

    def identify(self):

        print("Part Number: %d"%(self.number))

        print("Part Name: %s"%(self.name))

 

# Instantiate a part

part1=Part(111, "Spindle");

 

# Create a file to store the pickled object

objectRepository = open("ObjectFile.picl", "wb");

 

# Pickle/serialize the python object and store the bytes into a binary file 

pickle.dump(part1, objectRepository, protocol=pickle.HIGHEST_PROTOCOL)

objectRepository.close()

 

# Unpickle/de-serialize the python object and print the attributes of the object

objectRepository    = open("ObjectFile.picl", "rb",);

reconstructedObject = pickle.load(objectRepository)

 

# Print object attributes

reconstructedObject.identify()

 

Output:

Part Number: 111

Part Name: Spindle

 

 


Copyright 2023 © pythontic.com