Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Pickle Module

Python Pickle Module

In Python development we often need to save runtime objects, or restore a previous state after the program restarts, for example:

pickle The module is exactly theofficial built-in solution。

Python's pickle The module is a standard library module for serializing and deserializing Python objects.

Before starting to use Pickle, you need to understand two core concepts:

pickle The 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?

  1. Data persistence: Save Python objects to a file so that the data is still accessible after the program closes.
  2. Data transfer: Transmit Python objects over a network, for example passing data in a distributed system.
  3. Fast storage and loading:pickle The module can handle complex data structures efficiently, making it suitable for scenarios that require fast storage and loading.

Typical use cases for Pickle

pickle is well suited to the following scenarios:

  1. Local data persistence
  2. Saving and restoring program runtime state
  3. Caching intermediate computation results
  4. Inter-process communication (IPC) between Python processes
  5. Saving machine learning models and feature data

Unsuitable scenarios:

What objects does Pickle support?

1. Supported object types

Type Supported
int / float / bool / str Supported
list / tuple / dict / set Supported
None Supported
Instances of custom classes Supported
Nested structures Supported

Unsupported or not recommended objects

Import the module

Using the Pickle module is very simple; just import it:

import pickle

Basic usage of the Pickle module

1. Serialize an object

Use pickle.dump() The method serializes a Python object and saves it to a file.

Example

import

pickle

Create a Python object

data

=

{

   

'name'

:

'Alice'

,

   

'age'

:

25

,

   

'hobbies'

:

[

'reading'

,

'traveling'

]

}

Serialize the object and save it to a file

with

open

(

'data.pkl'

,

'wb'

)

as

file

:

   

pickle

.

dump

(

data

,

file

)

2. Deserialize an object

Use pickle.load() The method loads and deserializes a Python object from a file.

Example

import

pickle

Load and deserialize the object from the file

with

open

(

'data.pkl'

,

'rb'

)

as

file

:

    loaded_data

=

pickle

.

load

(

file

)

print

(

loaded_data

)

3. Serialize to a byte string

If you do not want to save to a file, you can use pickle.dumps() to serialize an object into a byte string:

Example

import

pickle

data

=

[

1

,

2

,

3

,

4

,

5

]

Serialize to a byte string

byte_data

=

pickle

.

dumps

(

data

)

print

(

byte_data

)

Output similar to: b'\x80\x04\x95\x0f\x00\x00\x00...'

4. Deserialize from a byte string

Use pickle.loads() to deserialize an object from a byte string:

Example

import

pickle

byte_data

=

b

'\x80\x04\x95\x0f\x00\x00\x00\x00\x00\x00\x00]\x94(K\x01K\x02K\x03K\x04K\x05e.'

Deserialize from a byte string

original_data

=

pickle

.

loads

(

byte_data

)

print

(

original_data

)

Output: [1, 2, 3, 4, 5]

5. Object types that can be serialized

Pickle can serialize most Python objects, including:

Example

import

pickle

Serialize different types of data

numbers

=

[

1

,

2

,

3

]

text

=

"Hello, Pickle"

dictionary

=

{

'key'

:

'value'

}

tuple_data

=

(

1

,

2

,

3

)

set_data

=

{

1

,

2

,

3

}

Put all the data into a list

all_data

=

[

numbers

,

text

,

dictionary

,

tuple_data

,

set_data

]

Serialization

with

open

(

'mixed_data.pkl'

,

'wb'

)

as

f:

   

pickle

.

dump

(

all_data

,

f

)

Deserialize

with

open

(

'mixed_data.pkl'

,

'rb'

)

as

f:

    loaded_data

=

pickle

.

load

(

f

)

   

print

(

loaded_data

)

6. Serialize a custom class

Pickle handles instances of custom classes well:

Example

import

pickle

class

Student:

   

def

init

(

self

,

name

,

age

,

grade

)

:

       

self

.

name

=

name

       

self

.

age

=

age

       

self

.

grade

=

grade

   

   

def

repr

(

self

)

:

       

return

f

"Student(name={self.name}, age={self.age}, grade={self.grade})"

Create an Instance

student

=

Student

(

"Li Si"

,

20

,

"Junior year"

)

Serialization

with

open

(

'student.pkl'

,

'wb'

)

as

f:

   

pickle

.

dump

(

student

,

f

)

Deserialize

with

open

(

'student.pkl'

,

'rb'

)

as

f:

    loaded_student

=

pickle

.

load

(

f

)

   

print

(

loaded_student

)

   

Output: Student(name=Li Si, age=20, grade=Junior year)

7. Serialize multiple objects

You can call pickle.dump() multiple times to save multiple objects:

Example

import

pickle

data1

=

{

'item'

:

'apple'

,

'count'

:

5

}

data2

=

[

'banana'

,

'orange'

,

'grape'

]

data3

=

42

Save multiple objects

with

open

(

'multiple.pkl'

,

'wb'

)

as

f:

   

pickle

.

dump

(

data1

,

f

)

   

pickle

.

dump

(

data2

,

f

)

   

pickle

.

dump

(

data3

,

f

)

Read multiple objects (the order must be the same)

with

open

(

'multiple.pkl'

,

'rb'

)

as

f:

    loaded_data1

=

pickle

.

load

(

f

)

    loaded_data2

=

pickle

.

load

(

f

)

    loaded_data3

=

pickle

.

load

(

f

)

   

print

(

loaded_data1

)

print

(

loaded_data2

)

print

(

loaded_data3

)

8. Practical examples

Example 1: Save and load a machine learning model configuration

Example

import

pickle

Simulate a machine learning model configuration

model_config

=

{

   

'model_type'

:

'RandomForest'

,

   

'n_estimators'

:

100

,

   

'max_depth'

:

10

,

   

'trained_date'

:

'2024-01-13'

,

   

'accuracy'

:

0.95

}

Save the configuration

with

open

(

'model_config.pkl'

,

'wb'

)

as

f:

   

pickle

.

dump

(

model_config

,

f

)

Load the configuration

with

open

(

'model_config.pkl'

,

'rb'

)

as

f:

    config

=

pickle

.

load

(

f

)

   

print

(

f

"Model type: {config['model_type']}"

)

   

print

(

f

"Accuracy: {config['accuracy']}"

)

Example 2: Cache computation results

Example

import

pickle

import

os

def

expensive_computation

(

n

)

:

   

"""Simulate a time-consuming computation"""

    result

=

sum

(

i **

2

for

i

in

range

(

n

)

)

   

return

result

def

compute_with_cache

(

n

,

cache_file

=

'cache.pkl'

)

:

   

Check whether the cache exists

   

if

os

.

path

.

exists

(

cache_file

)

:

       

with

open

(

cache_file

,

'rb'

)

as

f:

            cache

=

pickle

.

load

(

f

)

           

if

n

in

cache:

               

print

(

"Read the result from the cache"

)

               

return

cache

[

n

]

   

else

:

        cache

=

{

}

   

   

Perform the computation

   

print

(

"Performing computation..."

)

    result

=

expensive_computation

(

n

)

   

   

Save to the cache

    cache

[

n

]

=

result

   

with

open

(

cache_file

,

'wb'

)

as

f:

       

pickle

.

dump

(

cache

,

f

)

   

   

return

result

Usage examples

print

(

compute_with_cache

(

1000000

)

)

 

The first call computes

print

(

compute_with_cache

(

1000000

)

)

 

The second call reads from the cache


Notes on the Pickle module

  1. Safety:pickle The module executes arbitrary code during deserialization, so never load pickle data from untrusted sources, to avoid malicious attacks.
  2. Compatibility:pickle The byte stream produced is Python-specific and may have compatibility issues between different Python versions.
  3. Performance: For large datasets,pickle serialization and deserialization can be slow; consider more efficient serialization tools such as json or msgpack。

Advanced usage: serialization of custom objects

pickle The 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 __getstate__() and __setstate__() method.

Example

import

pickle

class

Person:

   

def

init

(

self

,

name

,

age

)

:

       

self

.

name

=

name

       

self

.

age

=

age

   

def

getstate

(

self

)

:

       

Custom serialization logic

       

return

{

'name'

:

self

.

name

,

'age'

:

self

.

age

}

   

def

setstate

(

self

,

state

)

:

       

Custom deserialization logic

       

self

.

name

=

state

[

'name'

]

       

self

.

age

=

state

[

'age'

]

Create an object and serialize it

person

=

Person

(

'Bob'

,

30

)

with

open

(

'person.pkl'

,

'wb'

)

as

file

:

   

pickle

.

dump

(

person

,

file

)

Deserializing an Object

with

open

(

'person.pkl'

,

'rb'

)

as

file

:

    loaded_person

=

pickle

.

load

(

file

)

print

(

loaded_person.

name

,

loaded_person.

age

)


Common methods of the pickle module

Method Description Example
pickle.dump(obj, file) Serialize an object and write it to a file pickle.dump(data, open('data.pkl', 'wb'))
pickle.load(file) Read from a file and deserialize the object data = pickle.load(open('data.pkl', 'rb'))
pickle.dumps(obj) Serialize an object into a byte string bytes_data = pickle.dumps([1, 2, 3])
pickle.loads(bytes) Deserialize an object from a byte string lst = pickle.loads(bytes_data)
pickle.HIGHEST_PROTOCOL The highest available protocol version (attribute) pickle.dump(..., protocol=pickle.HIGHEST_PROTOCOL)
pickle.DEFAULT_PROTOCOL The default protocol version (attribute, usually 4) pickle.dumps(obj, protocol=pickle.DEFAULT_PROTOCOL)

1. Serialize an object to a file

Example

import

pickle

data

=

{

'name'

:

'Alice'

,

'age'

:

25

}

with

open

(

'data.pkl'

,

'wb'

)

as

f:

   

pickle

.

dump

(

data

,

f

,

protocol

=

pickle

.

HIGHEST_PROTOCOL

)

2. Deserialize from a file

Example

with

open

(

'data.pkl'

,

'rb'

)

as

f:

    loaded_data

=

pickle

.

load

(

f

)

print

(

loaded_data

)

 

Output: {'name': 'Alice', 'age': 25}

3. Serialize to a byte string (network transfer / caching)

Example

bytes_data

=

pickle

.

dumps

(

[

1

,

2

,

3

]

,

protocol

=

4

)

restored_list

=

pickle

.

loads

(

bytes_data

)


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