How to Pickle a Class in Python

In the realm of Python programming, pickling a class refers to the process of serializing and deserializing objects, which allows for the conversion of class objects to a format that lets us store or transmit and reconstruct later.

It is helpful in scenarios where we need to save the state of our program and restart from there later. In this tutorial, we will provide step-by-step instructions on how to pickle a class in Python.

Step 1: Creation of a Class to be Pickled

Firstly, we need to create a simple Python class. Let’s consider the following class ‘Employee’ with attributes like ‘name’ and ‘age’:
Note: Any Python object can be pickled, thus, you can choose any class you prefer.

Step 2: Pickling the Class

To pickle a class in Python, we use the ‘pickle’ module. The ‘pickle’ module implements binary protocols for serializing and de-serializing a Python object structure. Import the ‘pickle’ module and use the ‘dump’ function:

In the script above, ‘wb’ stands for Write Binary. The ‘pickle.dump()’ function takes two parameters, the class object you want to pickle (john) and the file the pickled object is to be stored (file). We used ‘with’ with ‘open()’, which ensures that the file is properly closed after it is no longer needed.

Step 3: Unpickling the Class

After we pickle the class, we can unpickle it using the ‘load()’ function from the ‘pickle’ module:

In the script above, ‘rb’ stands for read binary. We use ‘pickle.load()’ to load the pickled class into the john_loaded object. Then print the ‘name’ and ‘age’ attributes of the unpickled object.

The Complete Code

Let’s have a look at the complete code:

Output

Name: John Doe, Age: 30

Conclusion

That’s all there is to pickling classes in Python! It’s a simple way to serialize and deserialize your Python class objects. However, it’s essential to mention that pickled data can be malicious.

Never unpickle data that comes from an untrusted source, as this can result in arbitrary code execution. To learn more about pickling and potential hazards, visit the official Python docs.