How to Serialize a Custom Object in Python: A Beginner’s Guide



So, you’ve created a custom object in Python, and now you want to save it for later use or share it with others. You’ve come to the right place! In this guide, we’ll walk you through the process of serializing a custom object in Python, step by step.

What is Serialization?

Before we dive into the details, let’s quickly understand what serialization is. Serialization is the process of converting an object into a format that can be stored or transmitted, and then later deserialized, or converted back into an object.

Serialization is useful when you want to save an object’s state, send it over a network, or store it in a database. By serializing an object, you can easily recreate it later, without losing any of its data or functionality.

Step 1: Importing the Required Modules

The first step is to import the necessary modules. In Python, we can use the pickle module for object serialization. Let’s import it:

import pickle

Step 2: Creating the Custom Object

Next, let’s create a custom object that we want to serialize. For the sake of this example, let’s say we have a class called Person with attributes like name, age, and occupation:

class Person:
    def __init__(self, name, age, occupation):
        self.name = name
        self.age = age
        self.occupation = occupation

person = Person("John Doe", 30, "Developer")

Step 3: Serializing the Object

Now that we have our custom object, let’s serialize it using the pickle.dump() function:

with open("person.pickle", "wb") as file:
    pickle.dump(person, file)

Here, we open a file called “person.pickle” in write binary mode (“wb”) and use the pickle.dump() function to serialize the person object into the file.

Step 4: Deserializing the Object

Once our object is serialized, we can easily deserialize it and recreate the object later. Let’s see how:

with open("person.pickle", "rb") as file:
    deserialized_person = pickle.load(file)

print(deserialized_person.name)  # Output: John Doe
print(deserialized_person.age)  # Output: 30
print(deserialized_person.occupation)  # Output: Developer

Here, we open the “person.pickle” file in read binary mode (“rb”) and use the pickle.load() function to deserialize the object back into the deserialized_person variable. We can then access the attributes of the object as usual.

Step 5: Handling Exceptions

It’s important to handle exceptions when working with serialization. For example, if the file doesn’t exist or if there’s an error during serialization or deserialization, an exception will be raised. Let’s handle these exceptions gracefully:

try:
    with open("person.pickle", "rb") as file:
        deserialized_person = pickle.load(file)
        print(deserialized_person.name)
except FileNotFoundError:
    print("File not found!")
except pickle.PickleError:
    print("Error occurred during serialization or deserialization!")

By using a try-except block, we can catch specific exceptions and handle them accordingly. In this example, we catch the FileNotFoundError and pickle.PickleError exceptions and display appropriate error messages.

Conclusion

And there you have it! You now know how to serialize a custom object in Python using the pickle module. Serialization allows you to save and share objects easily, without losing any of their data or functionality.

Remember to import the pickle module, create your custom object, serialize it using pickle.dump(), and deserialize it using pickle.load(). Don’t forget to handle exceptions to ensure smooth execution of your code.

Happy coding and serializing!