Are there any straightforward methods to preserve a Python function (or encode its code)?

Example #3 demonstrates a program that showcases the pickling of Python functions. The code provided illustrates this process, and the output is shown.
The explanation for the code is as follows:
First, the pickle module is imported. Then, the add() function is created as a Python object that will be stored in a file.
This is an introduction to Python Pickle, which offers modules for the serialization and deserialization of Python objects such as lists, dictionaries, tuples, and more.

Introduction to Python Pickle

Python offers
pickle modules
to serialize and deserialize
python objects
such as lists,
dictionaries, tuples
, etc. The process of pickling, also known as marshaling or flattening in other programming languages, is utilized to store
Python object

  • Serialization, also known as pickling, refers to the conversion of various data types (such as lists, dictionaries, and tuples) into a format that can be stored on disks or transmitted via a network.
  • The information stored in the file with the
    byte stream
    can be used to rebuild the original
    python object
    . This process of transforming
    converting byte streams
    back to
    Python objects
    is known as de-serialization.


The following outlines the process of pickling in python:

  1. Import
    pickle module
  2. To store an object in a file in byte format, you can utilize the pickle.dump(object, filename) function.
  3. To restore a Python object from a previously dumped file, utilize the pickle.load(filename) function.
Examples of Python Pickle

Below are provided examples of the following.

Example #1

“Rephrased MSDTHOT”:
“Python list pickling program demonstration”


# Program for pickling python lists
# importing module
import pickle
# number of input data to take
n = int(input("Enter the number of items"))
data = []  # input list
# adding items to the list
for d in range(n):
    item = input("Enter data :" + str(d+1)+': ')
# open a file where data need to be stored
file = open('list.pkl', 'wb')
# dump information to the file
pickle.dump(data, file)
# close the file
# open the file where data is dumped
fileo = open('list.pkl', 'rb')
# loading data
datao = pickle.load(fileo)
# close the file
# showing pickled data
print("showing data pickled")
for i in datao:


Python Pickle


The explanation for the above code:


  • The pickle module is imported.
  • The user is prompted to enter the number of items (n) that should be added to the empty list.
  • The list is populated with ‘n’ items using a for loop.
  • A file is opened in a new instance, using the “wb” mode for writing bytes.
  • The pickle.dump() method will be used to save the list to this file.
  • the file is closed.


  • The file containing the dumped list is opened using the “RB” mode for reading bytes.
  • The file is loaded with the use of pickle.load() to retrieve the data.
  • the file is closed.
  • The list is traversed to print the loaded data.
Example #2

This program demonstrates the process of pickling python dictionaries.


# Python program for serialization and de-serialization of dictionary
# importing module
import pickle
# creating python object --> dictionary
dictionary = {1: 'monday', 2: 'tuesday', 3: 'wednesday', 4: 'thursday', 5: 'friday', 6: 'saturday', 7: 'sunday'}
# open a file where to store dictionary
print("dictionary to be stored:")
file = open('dictionary.pkl', 'wb')
pickle.dump(dictionary, file) # storing dictionary into file
# closing file
fileo = open('dictionary.pkl', 'rb')
dicto = pickle.load(fileo)
print("displaying dictionary data")
for key, item in dicto.items():
    print(key, '-->', item)


 illustrate pickling of python


The explanation for the above code:

  • The pickle module is imported.
  • In this scenario,
    python object, dictionary
    is formed.
  • The dictionary file is opened in “wb” mode for writing bytes.
  • The dictionary is stored by utilizing the pickle.dump() function.
  • the file is closed.
  • The dictionary file is opened in read-bytes “RB” mode for retrieval.
  • the file is closed.
  • The items in the dictionary are subsequently displayed using a for loop.
Example #3

A program showcasing the pickling process of
python function


# Python program for serialization and de-serialization of function
# importing module
import pickle
# creating python object --> function()
# pickling
def add(a, b):
    return (a+b)
# opening file to store the add()
file = open('function.pkl', 'wb')
pickle.dump(add, file)
# closing file
# unpickling
fileo = open('function.pkl', 'rb')
addition = pickle.load(fileo)
# calling function
x = int(input("enter first number"))
y = int(input("enter second number"))
print("sum of numbers entered is :", addition(x, y))


sum of no entered


The explanation for the above code:

  • The pickle module is imported.
  • The add() function is a Python object that will be saved to a file.
  • The file is opened in the ‘wb’ mode for writing bytes.
  • By utilizing the pickle.dump() method, the add() function is stored or dumped into this file.
  • the file is closed.
  • The file is now opened in “RB” mode to retrieve the function file.
  • The load() function is used with pickle to load the add() function.
  • The user is prompted to enter two numbers, which are then passed to the add() function.
  • The addition of the two numbers is displayed.
Advantages and Disadvantages with usages of Pickling
  • The purpose of
    store python objects
    is to avoid repetitive object construction. Instead of creating the same object repeatedly, we can create it once and store it in a
    disk (pickling
    file. Later on, we can load this object from the disk (unpickling) without the need to recreate it.
  • In the field of Machine Learning, pickling is a valuable technique. When training a machine learning model on a large dataset, it requires a significant amount of time and effort. Instead of repeatedly training the same model, pickling can be employed to save time and effort. By training the model only once, it can be stored on a local disk. Later, when testing the model, it can simply be loaded from the disk without the need for further training.
  • Due to its exclusive focus on Python, it does not ensure compatibility across different programming languages.
  • Compatibility issues arise between different versions of Python, indicating that pickling performed in Python 2.x may not be functional in Python 3.x.
  • It is advisable to steer clear of obtaining content from unidentified sources, as it could potentially harbor harmful or malicious elements.

Python pickle
module provides a convenient method for
storing python objects
various data structures such as
tuple, dictionaries
, lists, and even python classes and functions. However, it does not offer cross-language compatibility or support for multiple python versions. It is also important to avoid unpickling data from unknown sources, as they may contain harmful or incorrect information.

Final thoughts

This guide provides an overview of
Python Pickle
, including an introduction to
python pickle
, along with examples and discussions on the advantages and disadvantages.

Frequently Asked Questions