The pickle module provides functionality for serializing and deserializing Python object hierarchies. Serialization converts Python objects into a byte stream that can be saved to disk, while deseiralization rceonstructs the original objects from stored data. This mechanism enables permanent storage of complex data structures across program executions.
Core API
pickle.dump(obj, file[, protocol])
Writes serialized object data to a file-like object. The protocol parameter controls the serialization format: protocol 0 produces ASCII-readable output, protocol 1 uses an older binary format, and protocol 2 offers improved efficiency. Setting protocol to -1 selects the highest available version. Default protocol is 0. When using protocol 1 or higher, the file must be opened in binary mode.
pickle.load(file)
Reads serialized data from a file-like object and reconstructs the original Python object. The file argument requires both read() and readline() methods.
Implementation Example
Storing objects to disk:
import pickle
# Prepare sample data structure
config_data = {
'host': 'localhost',
'ports': [8080, 8443],
'options': {'debug': True, 'timeout': 30}
}
# Create object with circular reference
nested_list = ['a', 'b', 'c']
nested_list.append(nested_list)
# Serialize to binary file
with open('cache.bin', 'wb') as output_file:
pickle.dump(config_data, output_file, protocol=0)
pickle.dump(nested_list, output_file, protocol=pickle.HIGHEST_PROTOCOL)
Retrieving stored objects:
import pickle
with open('cache.bin', 'rb') as input_file:
restored_config = pickle.load(input_file)
print(restored_config)
restored_nested = pickle.load(input_file)
print(restored_nested)
Security Notes
Only unpickle data from trusted sources. The pickle format can execute arbitrary code during deserialization, making it vulnerable to malicious input. For cross-language data exchange, consider JSON or MessagePack alternatives.