130. Serialization with pickle

The pickle module in Python is used to serialize (convert a Python object into a byte stream) and deserialize (reconstruct the Python object from the byte stream) Python objects. It is useful for saving objects to files or sending them over a network. Below are examples that demonstrate how to use pickle for serializing and deserializing Python objects.

1. Basic Serialization (Pickling)

This example shows how to serialize a Python object into a byte stream and store it in a file.

import pickle

# Sample Python object (dictionary)
data = {'name': 'John', 'age': 30, 'city': 'New York'}

# Serialize the object and save it to a file
with open('data.pickle', 'wb') as file:
    pickle.dump(data, file)

print("Object serialized and saved to data.pickle")

2. Basic Deserialization (Unpickling)

This example shows how to read a serialized object from a file and deserialize it back into a Python object.

import pickle

# Read the serialized object from the file
with open('data.pickle', 'rb') as file:
    loaded_data = pickle.load(file)

print("Object deserialized from data.pickle:")
print(loaded_data)

3. Serializing a Custom Class Object

This example demonstrates how to pickle and unpickle an object of a custom class.


4. Serializing Multiple Objects

You can serialize multiple objects in a single file.


5. Pickle with File Handling

You can directly use pickle to handle large files or data.


6. Pickle with String (Memory Buffer)

Using pickle to serialize objects into a memory buffer instead of writing to a file.


7. Pickle Protocol

The pickle module supports different serialization protocols. The default is protocol 3, but you can use different protocols for compatibility or efficiency.


8. Pickle with Try-Except for Error Handling

Error handling when loading a pickled file.


9. Avoiding Pickle Insecurity

Since pickle can execute arbitrary code during deserialization, it’s unsafe to unpickle data from untrusted sources. Always validate the data source.


10. Using pickle with Python's with Statement

Ensure that files are properly closed after pickling by using with statements.


Key Points:

  • Pickle allows serialization of complex Python objects to a byte stream, which can then be saved or transmitted.

  • pickle.dump() serializes and saves an object to a file.

  • pickle.load() deserializes and loads an object from a file.

  • Pickling custom objects: Custom classes can also be serialized and deserialized.

  • Protocols: Pickle supports different serialization protocols for backward compatibility.

  • Security: Avoid unpickling data from untrusted sources due to potential code execution risks.

Last updated