Ad Code

✨🎆 Codex 1.0 PLACEMENT READY PROGRAM! 🎆✨

Get 75% Discount Early bird offer CLICK to JOIN CodeX 1.0 click

Pickling and Unpickling tutorials in Python?

Pickling in Python – Complete Explanation with Examples

Pickling is the process of converting a Python object into a byte stream so that it can be stored in a file or transferred over a network. This process is also known as object serialization.

The reverse operation of converting byte stream back into a Python object is called Unpickling or object deserialization.

Why Do We Use Pickling?

  • To save Python objects permanently in a file.
  • To transfer objects between two systems (client & server).
  • To store machine learning models.
  • To reduce computation by saving processed data objects.

Pickle Module in Python

Python provides the pickle module for serialization.

Main Methods:

  • dump() → Writes object to a file in byte format.
  • dumps() → Converts object to byte stream (not saved in file).
  • load() → Reads byte stream from a file and converts to object.
  • loads() → Converts byte stream back to object.

Example 1: Pickling a List Using dump()

import pickle

lst = ["C","C++","Java",".NET","PHP"]

f = open("d://coursedetails.txt", "wb")
pickle.dump(lst, f)
f.close()

Explanation: The list is converted into bytes and stored in coursedetails.txt.


Example 2: Unpickling a List Using load()

import pickle

f = open("d://coursedetails.txt","rb")
s = pickle.load(f)
print(s)
f.close()

Output: ["C", "C++", "Java", ".NET", "PHP"]


Example 3: Using dumps() and loads() for Real-Time Objects

Note: Use dumps() when you want to convert an object directly into a byte stream without writing into a file. Use loads() when converting a byte stream back into the original object.

import pickle

class Student:
    rno = 1001
    sname = "xyz"
    x = ["c","CPP","JAVA"]

stu = Student()

st = pickle.dumps(stu)   # Object to byte stream
print("Pickled Object is ", st)

s = pickle.loads(st)     # Byte stream to object
print(s.x)
print(s.rno)
print(s.sname)

Advantages of Pickling

  • Very easy method to save Python objects.
  • Useful for machine learning model storage.
  • Supports complex objects (classes, functions, lists, dictionaries, etc.).
  • Faster than writing custom serialization.

Disadvantages of Pickling

  • Pickled data is not human readable.
  • Not compatible across different Python versions.
  • Should not unpickle data from untrusted sources (security risk).

Real-Life Use Cases of Pickling

  • Saving trained machine learning models (scikit-learn, NLP models).
  • Sharing data between server and client in network programs.
  • Storing session data in applications.
  • Caching large objects (dataset preprocessing).

Pickling vs JSON Serialization

Pickling JSON
Stores Python-specific objects (classes, functions, etc.) Stores only basic data types
Not human readable Human readable
Fast and compact Slower compared to pickle
Python-only format Language independent

Interview Questions on Pickling

  1. What is pickling and unpickling in Python?
  2. What is the difference between dump() and dumps()?
  3. Is pickled data readable?
  4. Can we pickle user-defined classes?
  5. Why is unpickling unsafe from untrusted sources?
  6. Compare Pickling vs JSON.
  7. Where is pickling used in machine learning?

Conclusion

Pickling is one of the most powerful features of Python that helps store and transfer complex data objects easily. It is widely used in real-time applications like AI/ML models, caching, distributed systems, and client-server programs.

Post a Comment

2 Comments

  1. # Wap to find area of circle , triangle, ractangle using pickling & unpickling

    import pickle
    class Circle:
    def accept(self,a):
    self.a=a
    def dis(self):
    print("Area Of Circle : %d"%(3.14*self.a*self.a))
    class Triangle(Circle):
    def accept1(self,b):
    self.b=b
    def dis1(self):
    print("Area Of Triangle : ",((self.a*self.b)/2))
    class Ract(Triangle):
    def accept2(self):
    self.area=self.a*self.b
    def dis2(self):
    print("Area Of Ractangle : ",self.area)
    f=open ('demo2.txt','wb')

    a1=Circle()
    a1.accept(a=5)
    a1=Triangle()
    a1.accept(a=5)
    a1.accept1(b=10)
    a1=Ract()
    a1.accept(a=12)
    a1.accept1(b=8)
    a1.accept2()
    pickle.dump(a1,f)
    print("Pickling Done!!")
    #pickshow = pickle.loads(pickCircle)
    f=open ('demo2.txt','rb')

    obj=pickle.load(f)
    print("Unpickling Done!!")
    obj.dis()
    obj.dis1()
    obj.dis2()


    ReplyDelete
  2. import pickle
    class Student:
    rno=1001
    subject=['phy','chem','maths','english','hindi']

    obj = Student()
    data=pickle.dumps(obj)
    f = open("picklemultiple.txt","wb")
    f.write(data)
    f.close()

    f = open("picklemultiple.txt","rb")

    s = pickle.load(f)

    print(s.rno)
    print(s.subject)

    ReplyDelete

POST Answer of Questions and ASK to Doubt