×

Python Pickle

The pickle is a module that enables serialization and de-serialization of the structure of the object in python. Pickling is the process that uses the protocols to convert the Python object hierarchy into the byte stream. The process of converting byte stream into Python object hierarchy is termed unpickling. Pickling is also called serialization, while the inverse operation that is unpickling is called de-serialization.

Python Pickle Dump and Python Pickle Load

pickle.dump() and pickle.load() are two functions in the pickle module that are used to store and retrieve data using this module. In order to use both these functions, it is necessary to import the pickle module into your program.

Once you have imported the pickle module into your program, then the next step will be to add the object data to the file. To do so, you will have to use the pickle.dump() function. This function takes three arguments, where the first argument contains the object that is to be stored in the file, and the second argument gives the file object that is obtained when the desired file is opened in the write-binary mode. While the third argument determines the protocols, this argument is of key-value type.

The two protocols that are available to be used in the third argument are:

  • Pickle.HIGHEST_PROTOCOL
  • Pickle.DEFAULT_PROTOCOL

Now let’s implement the program to store the data in a file using pickle.

import pickle


# data items you want to enter in the file


total_data = int(input('Enter the number of dataitems: '))


dataitems = []


# Take the value of the data items from the user


for i in range(total_data):


    raw = input('Enter the data '+str(i)+' : ')


    dataitems.append(raw)


# enter the file you want to insert data in


# Open the file in write-binary mode


file = open('file_1', 'wb')


#  enter the data entered to that file


pickle.dump(dataitems, file)


# close the file after performing the operation


file.close()

You can enter the data values in the file using this program and once it is executed it will create a file and store those data values in the file.

Output:

Python Pickle

Python Pickle Load

Now, you have successfully entered the data, you should be able to retrieve that data too in order to use it. This function enables to retrieve of the data from the file. The data values can easily be retrieved when you open the file in read-binary mode using this function. The primary parameter passed to this function is the file object from which information is to be retrieved.

Now let’s write a code to retrieve the information that was stored in the above example by using pickle load.

import pickle


# Enter the file in which data was stored earlier


#Open the file in read binary mode


file = open('file_1', 'rb')


#Now load the information from the file using pickle.load() function


dataitems = pickle.load(file)


# close the file once the information is retrieved


file.close()


print('The data stored in the file is as follows:')


count = 0


for item in dataitems:


    print('The data stored ', count, ' is : ', item)


    count += 1

Output:

Python Pickle

Thus, by using the above two functions you have successfully stored and retrieved information from a file.

Note: The pickle module is not safe when dealing with untrusted data. So, use pickle only with the trusted data otherwise use more secured formats like JSON.

Data that can be Pickled

Not every type of data written in python can be pickled. However, Python-pickle enables to pickle only the given format of data:

  • None and True, False
  • All the types of numbers including floating, complex and integers
  • strings, bytes, byte arrays
  • tuples, lists, sets, and dictionaries but they must contain the objects that are prickleable by themselves
  • functions defined at the top level of a module but they should be defined by def and not lambda
  • built-in functions defined at the top level of a module
  • classes that are defined at the top level of a module
  • instances of such classes whose __dict__ or the result of calling __getstate__() is prickleable

When you try to pickle any object that cannot be pickled, it will throw a PicklingError exception; it may be possible that some of the bytes are written to the file before raising the exception. And when you attempt to pickle the recursive data structure, it may cause a RecursionError as there is a limit to the recursion depth that can be reached. You can keep a check on this limit with sys.setrecursionlimit().

Note: When you try to pickle any function both built-in or user-defined this only pickles the name of the function and the module name in which the mentioned function is present. It does not pickle the code inside the function nor the attributes of the function.

Additional Information

  • The use of prickle protocol is limited to python and is not necessary that it support other languages. Therefore, it is not possible to transfer and access the data in any other language.  This is a major restriction with pickle.
  • Python uses the latest version of the pickle available by default. It can be manually changed by the user.
  • Pickle may execute differently with different versions of Python itself.

Data stream format

We know that prickle protocols are only limited to the Python programming language. This act both as an advantage and a disadvantage. As an advantage, there is no restriction imposed by any other external protocols like in the case of JSON but at the same time, it is a disadvantage as we cannot use any other programming language when dealing with pickled data.

Pickletools is a module that has the tools, especially to study the data streams that are produced by the pickle module. This has the opcodes regarding the protocols of the pickle. Till now there have been six protocols that are used by the pickle module to implement pickling. The latest versions of the Python are compactible to the higher protocol.

  • Protocol version 0 is the earliest protocol that was available to pickle the data. It was a “human-readable” protocol that was compatible with the older version of Python.
  • Protocol version 1 was the binary format protocol that was also limited
  • Protocol version 2  provides much more efficient pickling of new-style classes.
  • Protocol version 3 was added in Python 3.0 was introduced as the external support for the byte objects that were not unpickled by Python 2x and was added as the default protocol.
  • Protocol version 4 was introduced in Python 3.4. It was an extension of the earlier protocols as it allowed the user to pickle or unpickle larger data and allow the user to convert more types of objects. It is the default protocol starting with Python 3.8.
  • Protocol version 5 is the latest protocol that was introduced with Python 3.8. It supports the out-of-band data and speed up the in-band data.

Note: Pickle only reads and writes the objects of the file, it does not resolve the problem with the concurrent access to its file objects and neither does it resolves the issue of naming such objects. This module is used to transform the objects into the byte stream. The structure of the byte stream is just the same as that of the complex object.  These byte codes can be written on a file or they can also be sent across the network or can be stored in databases by using the shelve module that provides an interface to the user to pickle and unprickle objects on DBM-style database files.


Related Topics

Sublime Python

SUBLIME: A compact, cross-platform code editor called Sublime Text 3 (ST3) is well-known for its quickness, usability, and robust community support. Although it's a fantastic editor out of the box, its...

6 minutes read.

How to set up a proxy using selenium in python

What is Proxy? A proxy acts as a middleman between user requests and server responses. The main purposes of proxies are to protect user privacy and encapsulate data between various interactive...

3 minutes read.

Create First GUI Application using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

6 minutes read.

Composition in Python

Composition in Python Composition is one of the important concepts of Object-oriented programming (OOPs). Composition basically enables us for creating complex types objects by combining other types of objects in the...

6 minutes read.

GET and POST requests using Python

‘GET’ and ‘POST’ are two request methods of Hypertext Transfer Protocol (HTTP). What is HTTP? HTTP stands for Hypertext Transfer Protocol. It is a collection of protocols which makes communication between client...

4 minutes read.

How to declare array in python

How to declare array in python? Arrays are a great way of storing our numeric values into a variable in continuous locations. For declaring an array in C language, we used...

4 minutes read.

Scrimba python

Scrimba allows you to study whenever and wherever the topics or concepts you want. It also replaces classroom instruction with interactive screencasts, live events, and student-to-student help. Scrimba is an interactive...

3 minutes read.

Python IDE names

Python is one of the most renowned programming languages. It has different execution conditions and a great many compilers to execute the python programs, e.g., PyCharm, PyDev, Jupyter Notebook, Visual...

6 minutes read.

Python pow() Function

Python pow() Function The pow() function in Python return the parameter ‘x’ to the power ‘y’ and if the parameter ‘z’ is present, it returns x to the power y, modulo z (computed more efficiently than pow(x, y) % z). Syntax pow(x, y[, z]) Parameter x: This parameter represents the base...

1 minute read.

Python Time Library

We will consider various functions given by the python module library with examples.This python time module helps to work on time in python to get the current time.Before going with...

4 minutes read.

Python List copy() method

Python List copy () method The list.copy () method returns a shallow copy of the list. Syntax list.copy() Parameter NA Return This function returns the copy for the given list. Example 1 # Python program explaining # the list.copy() method # passing the...

1 minute read.

Python String count() method

Python String count() method The string.count() method returns the number of times a specified value appears in the string. Syntax string.count(sub[, start[, end]]) Parameter sub: This parameter represents a substring to be searched. start: This parameter...

1 minute read.

Python PPTX

Python-pptx is a python library that enables the user to create and update PowerPoint (.pptx) presentations. It is used to create modified PowerPoint presentations from the db content that can...

10 minutes read.

JWT Decode Python

Python's PyJWT package makes it possible to encrypt and decrypt JSON Web Tokens (JWT). JWT is a public, recognized global benchmark for safely expressing demands between two parties (RFC 7519). JSON...

7 minutes read.

Python TypeError

What is TypeError in python? TypeError is one of the exceptions in the python programming language. This exception occurs when an operation is performed on an unsupported object type or can...

6 minutes read.

Python frozenset()

Python frozenset() class The frozenset() class in Python returns a new frozenset object, optionally with elements taken from iterable. Syntax class frozenset([iterable]) Parameter iterable: This parameter represents an iterable object, like list, set, tuple etc. Return This class returns an unchangeable...

1 minute read.

Tuple in Python

Tuples Tuples are the same as the list but as we know that lists are mutable means we can change the data from it. In the tuple we cannot change the...

6 minutes read.

Python Set update() method

Python Set update() method The set.update() method in Python updates the current set, by adding items from another set. If an element is common in both the sets, only one appearance of this item...

1 minute read.

Create Table Using PyQt5 in Python

PyQt5: PyQt5 is one of several solutions that Python offers for creating GUI applications. Cross-platform GUI toolkit PyQt5 is a collection of Python interfaces for Qt version 5. With this library's...

4 minutes read.

Subprocess Module in Python

What is a Process? Every program will have its respective system state, i.e., the state in which it is running. A program that is in a running state or in a...

7 minutes read.