Python Pickle Module
In Python development, we often need to save runtime objects or restore previous states after a program restarts, for example:
- Caching calculation results to disk to avoid recomputation
- Saving user configurations and intermediate program states
- Passing complex objects between different Python processes
The pickle module is precisely the official built-in solution Python provides for these problems.
Python’s pickle module is a standard library module for serializing and deserializing Python objects.
Before using Pickle, you need to understand two core concepts:
- Serialization (Pickling): Converting a Python object into a byte sequence
- Deserialization (Unpickling): Converting a byte sequence back into a Python object
The pickle module can save almost any Python object (such as lists, dictionaries, class instances, etc.) to a file, or transmit it over a network, and then reload it when needed.
Why Use the Pickle Module?
Section titled “Why Use the Pickle Module?”- Data Persistence: Save Python objects to files so that the data remains accessible after the program closes.
- Data Transfer: Transmit Python objects over a network, such as passing data in distributed systems.
- Fast Storage and Loading: The
picklemodule can efficiently handle complex data structures, making it suitable for scenarios requiring fast storage and loading.
Typical Use Cases for Pickle
Section titled “Typical Use Cases for Pickle”pickle is well-suited for the following scenarios:
- Local data persistence
- Saving and restoring program runtime state
- Caching intermediate computation results
- Python inter-process communication (IPC)
- Saving machine learning models and feature data
Scenarios where it is not suitable:
- Cross-language data exchange
- Frontend-backend API data transmission
- Deserialization from untrusted data sources
What Objects Does Pickle Support?
Section titled “What Objects Does Pickle Support?”1. Supported Object Types
Section titled “1. Supported Object Types”| Type | Supported |
|---|---|
| int / float / bool / str | Yes |
| list / tuple / dict / set | Yes |
| None | Yes |
| Custom class instances | Yes |
| Nested structures | Yes |
Unsupported or Not Recommended Objects
Section titled “Unsupported or Not Recommended Objects”- Open file objects
- Sockets, database connections
- OS resources
- Objects dependent on runtime environment state
Importing the Module
Section titled “Importing the Module”Using the Pickle module is very simple, just import it:
Basic Usage of the Pickle Module
Section titled “Basic Usage of the Pickle Module”1. Serializing Objects
Section titled “1. Serializing Objects”Use the pickle.dump() method to serialize a Python object and save it to a file.
Example
Section titled “Example”'wb'means opening the file in binary write mode.pickle.dump()serializes thedataobject and writes it to the file.
2. Deserializing Objects
Section titled “2. Deserializing Objects”Use the pickle.load() method to load and deserialize a Python object from a file.
Example
Section titled “Example”'rb'means opening the file in binary read mode.pickle.load()reads the byte stream from the file and deserializes it into a Python object.
3. Serializing to a Byte String
Section titled “3. Serializing to a Byte String”If you don’t want to save to a file, you can use pickle.dumps() to serialize an object into a byte string:
Example
Section titled “Example”4. Deserializing from a Byte String
Section titled “4. Deserializing from a Byte String”Use pickle.loads() to deserialize an object from a byte string:
Example
Section titled “Example”5. Serializable Object Types
Section titled “5. Serializable Object Types”Pickle can serialize most Python objects, including:
- Basic data types: integers, floats, strings, booleans, None
- Collection types: lists, tuples, dictionaries, sets
- Custom class instances
- Functions and classes (with some limitations)
Example
Section titled “Example”6. Serializing Custom Classes
Section titled “6. Serializing Custom Classes”Pickle handles custom class instances very well:
Example
Section titled “Example”7. Serializing Multiple Objects
Section titled “7. Serializing Multiple Objects”You can call pickle.dump() multiple times to save multiple objects:
Example
Section titled “Example”8. Practical Application Examples
Section titled “8. Practical Application Examples”Example 1: Saving and loading machine learning model configuration
Example
Section titled “Example”Example 2: Caching computation results
Example
Section titled “Example”Important Notes on the Pickle Module
Section titled “Important Notes on the Pickle Module”- Security: The
picklemodule can execute arbitrary code during deserialization. Therefore, do not loadpickledata from untrusted sources to avoid malicious attacks. - Compatibility: The byte stream generated by
pickleis Python-specific, and there may be compatibility issues between different versions of Python. - Performance: For large datasets,
pickleserialization and deserialization can be relatively slow. Consider using more efficient serialization tools such asjsonormsgpack.
Advanced Usage: Custom Object Serialization
Section titled “Advanced Usage: Custom Object Serialization”The pickle module supports serialization of custom classes. By default, pickle saves the object’s attributes and class name. If you need more complex serialization logic, you can implement the __getstate__() and __setstate__() methods in your class.
Example
Section titled “Example”Common Methods of the pickle Module
Section titled “Common Methods of the pickle Module”| Method | Description | Example |
|---|---|---|
pickle.dump(obj, file) |
Serialize object and write to file | pickle.dump(data, open('data.pkl', 'wb')) |
pickle.load(file) |
Read and deserialize object from file | data = pickle.load(open('data.pkl', 'rb')) |
pickle.dumps(obj) |
Serialize object to byte string | bytes_data = pickle.dumps([1, 2, 3]) |
pickle.loads(bytes) |
Deserialize object from byte string | lst = pickle.loads(bytes_data) |
pickle.HIGHEST_PROTOCOL |
Highest available protocol version (attribute) | pickle.dump(..., protocol=pickle.HIGHEST_PROTOCOL) |
pickle.DEFAULT_PROTOCOL |
Default protocol version (attribute, usually 4) | pickle.dumps(obj, protocol=pickle.DEFAULT_PROTOCOL) |
1. Serialize object to file
Example
Section titled “Example”2. Deserialize from file
Example
Section titled “Example”3. Serialize to byte string (network transfer/caching)
Example
Section titled “Example”pickle Module Protocol Versions
Section titled “pickle Module Protocol Versions”| Protocol Version | Description |
|---|---|
| 0 | Human-readable ASCII format (compatible with older versions) |
| 1 | Binary format (compatible with older versions) |
| 2 | Python 2.3+ optimized support for class objects |
| 3 | Python 3.0+ default protocol (does not support Python 2) |
| 4 | Python 3.4+ supports larger objects and more data types |
| 5 | Python 3.8+ supports memory optimization and data sharing |