PICKLE MODULE
• The pickle module is used for implementing binary protocols 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.
The process to converts any kind of python objects (list, dict, etc.) into byte streams (0s
and 1s) is called pickling or serialization or flattening or marshalling..
• Unpickling: It is the inverse of Pickling process where a byte stream is converted into an
object hierarchy. We can converts the byte stream (generated through pickling) back into
python objects by a process called as unpickling
• Module Interface :
dumps() – This function is called to serialize an object hierarchy.
loads() – This function is called to de-serialize a data stream.
• The pickle module is the main mechanism Python provides for
serializing Python objects.
• Basically, pickle turns a Python structure into a byte-stream
representation which is easily sent or stored. Then, a pickle can be
used to reconstruct the original object.
• All of Python’s native datatypes: floating point numbers,
Booleans, integers, etc.
• Lists, tuples, dictionaries, and sets containing picklable objects.
• Advantages:
• Customizable.
• Can serialize pretty much any Python object.
• Space efficient
• Easy for small uses.
Disadvantages:
• Slower than most other methods.
• Not secure: no protection against malicious data.
• Python specific. Can’t communicate with non-Python code.
Example 1
• Below is a simple program on how to pickle a list:
• Pickle a simple list: Pickle_list1.py
import pickle
mylist = ['a', 'b', 'c', 'd’]
with open('[Link]', 'wb’) as fh:
[Link](mylist, fh)
• In the above code, list – “mylist” contains four elements (‘a’, ‘b’, ‘c’, ‘d’).
• We open the file in “wb” mode instead of “w” as all the operations are done using bytes in the
current working directory.
• A new file named “[Link]” is created, which converts the mylist data in the byte stream.
import pickle
pickle_off = open ("[Link]", "rb")
test = [Link](pickle_off) print(test)
• Output: On running above scripts, you can see your mylist data
again as output. ['a', 'b', 'c', 'd']