Python – Pickling – Serialization

Previous
Next

Serialization and De-Serialization:

  • In Object oriented applications, we store information in the form of Objects.
  • We use files to store information in textual format.
  • Object contains the information – using dynamic variables – also called state of object.
  • If we want to store Object state(information) into File is called Serialization.
  • Converting “Object State” into “Persistent State” is called Serialization.

Java: Serialization & De-Serialization

.Net: Marshalling & Deflating

Python: Pickling & UN pickling

Pickle:

  • “pickle” is the pre-define module providing functionality to perform Serialization and De-serialization
  • “dump()” method is used to write the object information into file.
  • “load()” method is used to read the object from the file

Notes:

  • Serialized data will be in binary format.
  • We need to open file in (write binary) mode to write the object data.
  • We cannot open binary file directly(nothing can see). Data will in symbolic format.

Why object data in binary form?

  • Static variables are used to store common information of all objects which is free access to everyone.
  • Dynamic variables (stored in object) always store specific information of Object.
  • Object data is secured; hence we need to protect the data while converting into file. Hence they provided binary file format.

Code: We use 3 files to implement

  1. Emp.py file to specify Employee object
  2. Serialize.py file
  3. Deserialize.py file

emp.py:

class Employee :
    def __init__(self, num, name, salary):
        self.num = num
        self.name = name
        self.salary = salary
        return

serialize.py:

import pickle
from emp import Employee
class Serialization:
    file = None
    def main():
        try :
            Serialization.file = open("./data.bin", mode="wb")
            print("File is ready")

            obj = Employee(101, "Amar", 45000)
            pickle.dump(obj, Serialization.file)
            print("Object is serialized successfully")

        except Exception as e:
            print("Exception :", e)

        finally:
            if Serialization.file != None:
                Serialization.file.close()
                print("File closed")
        return

Serialization.main()

Run serialize file:

Previous
Next

Add Comment

Courses Enquiry Form