DEV Community

loading...

What is Pickle in python ?

grayhat profile image Mwenda Harun Mbaabu ・2 min read

It is used for serializing and de-serializing a Python object structure.

Pickling: It is a process where a Python object hierarchy is converted into a byte stream and dumps it into a file by using dump function.This character stream contains all the information necessary to reconstruct the object in another python script.

Unpickling: It is the inverse of Pickling process where a byte stream is converted into an object hierarchy.While the process of retrieving original Python objects from the stored string representation is called unpickling.we use load function to do this.

First of all you have to import pickle module through this command:

import pickle
Enter fullscreen mode Exit fullscreen mode

Pickle has two main methods. The first one is dump, which dumps an object to a file object and the second one is load, which loads an object from a file object.

Examples

1). Pickling.

import pickle

a=[1, 2, 3, 4, 5, 6, 7]

# open the file for writing
pic_out=open("mypicklefile","wb")

#write object to file mypicklefile
pickle.dump(a,pic_out)

pic_out.close()
Enter fullscreen mode Exit fullscreen mode

2). Unpickling.

import pickle
# open the file for reading
pic_in = open("mypicklefile", "rb")
# load the object from the file into var a
a = pickle.load(pic_in)

print(a)
Output:[1, 2, 3, 4, 5, 6, 7]
Enter fullscreen mode Exit fullscreen mode

Use cases of Pickling:

  • saving a program’s state data to disk so that it can carry on where it left off when restarted (persistence)
  • sending python data over a TCP connection in a multi-core or distributed system (marshalling)
  • storing python objects in a database
  • converting an arbitrary python object to a string so that it can be used as a dictionary key (e.g. for caching & memoization).

Official Docs

Discussion (0)

pic
Editor guide