Good Place. Good Things. Good Time.

Python object serialization

Python object serialization

Introduction to Python Object Serialization

Python object serialization, when we define in the context of data storing and unpacking, is considered as a method. In which we can convert/translate a python data object into a byte format. This byte format is storable (either as a file or in a buffer memory). On top of that, you will be able to transmit, reformat, or restore it later as well via sockets. In serialization, a module named pickle from python allows you to serialize the python object, which can also be stored as a file to any location or inside the buffer memory for a temporary period.

Pickle to Serialize a python object

Pickle is a module developed under python which can convert a python object into a byte system string (which usually cannot be read by the user) which can later be saved as a file or into a buffer memory. Finally, it can also unpack the byte strings into the original python objects. There are two different methods for serialization and deserialization under the pickle module, as mentioned below:

  • dumps() – This function allows you to serialize a python object into a byte stream.
  • dump() – This function allows you to serialize and store a python object into a file.
  • loads() – This function allows you to de-serialize a byte stream into a python object.
  • load() – This function allows you to de-serialize a python object to its original form through a byte streamed file stored at a path.

There are two versions of protocols while working on pickling. One is HIGHEST_PROTOCOL, and another one is DEFAULT_PROTOCOL. A standard value for the HIGHEST_PROTOCOL is 5, and that for DEFAULT_PROTOCOL is 4.

You can check this by running the following piece of code in python:

import pickle
print("The highest protocol value is:", pickle.HIGHEST_PROTOCOL)
print("The Default protocol value is:", pickle.DEFAULT_PROTOCOL)

The output for this code is as shown below, which gives you the protocol values for HIGHEST and DEFAULT protocol, respectively.

The HIGHEST and DEFAULT Protocol Values

Python object serialization output 1

Let us see some examples associated with object serialization, de-serialization in Python programming:

1. The pickle.dump() Method to Serialize a Python Object

The pickle.dump() method will take a python object as an argument and then store it as a text file with the object serialized into bytes. Remember that this conversion will not show you the original python object but a text byte which has that object serialized in. See the code below:

import pickle
file =  open('serialized.txt', 'wb')
dic1 = {
"name" : "Lalit",
"age" : 28,
"active" : True,
"married" : False,
"pets" : None,
"amount": 450.98,
}
pickle.dump(dic1, file)
file.close()

Here, we have created a dictionary named “dic1”, which contains the information about the user accessing the web portal and the amount of purchase he has made.

We have defined a “file” object as well. This object will allow us to store the serialized bytes into a text file at a working directory with the name “serialized”.See the output below:

Python object serialization output 2

Here, no output is visible as the file is created and stored in the working directory. We Can see it as shown below:

Python object serialization output 3

We can open this file in any text editor to see the output.

output 4

2. The pickle.load() Method to De-serialize the bytes into Python Object

The pickle.load() function will take a file that has serialized the python object into bytes and then convert it into the original python object. See the code below for a better realization.

import pickle
#Accessing the text file with serialization into bytes
file = open("serialized.txt", "rb")
#Using load() function to convert the file into a python object (dictionary)
dic = pickle.load(file)
print(dic)
file.close()

Here, we have used the same file object we have created a serialization in the previous example. Then we have used the pickle.load() to read that file and convert it into the original python object that is a dictionary. See the output as shown below:

output 5

You can see the original dictionary that you get as an output in the console, as shown above, with the user information.

3. The pickle.dumps() Method to Serialize the Python Object

Now, we will use the pickle.dumps() method. Which allows us to serialize a python object into a byte-sized text object. However, the difference here is, this method doesn’t allow us to store the result into a file; rather, it allows the result to print out directly in the console. See an example below:

import pickle
my_dict = {
"name" : "Shawn",
"Age" : 28,
"Gender" : "Male",
"Cars" : None,
"Single" : True,
"Languages" : ["English", "German", "Spanish"]
}
#Using pickle.dumps() to serialize the object
print(pickle.dumps(my_dict, protocol = pickle.DEFAULT_PROTOCOL))

Here, we have used pickle.dumps() method with DEFAULT_PROTOCOL value to convert the object into bytes. See the output as shown below:

output 6

4. The pickle.loads() Method to convert open bytes into python objects

Let us do a reverse; we will use the byte code above to get the original dictionary under python using pickle.loads() method.

import pickle
btstring = b'x80x04x95kx00x00x00x00x00x00x00}x94(x8cx04namex94x8cx05Shawnx94x8cx03Agex94Kx1cx8cx06Genderx94x8cx04Malex94x8cx04Carsx94Nx8cx06Singlex94x88x8ctLanguagesx94]x94(x8cx07Englishx94x8cx06Germanx94x8cx07Spanishx94eu.'
#Using pickle.loads() to convert the byte string into a dictionary
my_dict = pickle.loads(btstring)
print(my_dict)

This code will generate the original dictionary with its components. See the output screenshot as shown below:

output 7

We will wrap this article here, but not before some conclusion points.

Conclusion

  1. Serialization is a process of converting a python object into bytes that can be stored as a file or in buffer memory and can be de-serialized as well.
  2. The pickle module is used to serialize and de-serialize the python object.
  3. Pickle has two types of protocols based on which the serialization and deserialization happens. They are namely, DEFAULT_PROTOCOL, and HIGHEST_PROTOCOL respectively.
  4. Pickle can only save the object attributes and could not store the object code.

Recommended Articles

This is a guide to Python object serialization. Here we discuss the two different methods for serialization and deserialization under the pickle module. You may also look at the following articles to learn more –

  1. Python Stream
  2. Python Dump
  3. Python NameError
  4. Python json.dumps

The post Python object serialization appeared first on EDUCBA.

Read original article here: Python object serialization

Read original article here: Python object serialization



Disclaimers and Denial of responsibility..!

Denial of responsibility! TheTopMag.com is an automatic aggregator of all media around the world. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – jamesonline999@gmail.com . The content will be deleted within 72 hours.
You might also like
Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.