pickle | Python Standard Library – Real Python

The Python pickle module provides tools to serialize and deserialize Python objects, allowing you to save complex data types to a file and restore them later. This is useful for persisting data or sending Python objects over a network.

Here’s a quick example:

Key Features

  • Serializes Python objects to a byte stream
  • Deserializes byte streams back to Python objects
  • Supports a wide variety of Python data types, including custom classes
  • Provides different protocols for backward compatibility and efficiency

Frequently Used Classes and Functions

Object Type Description
pickle.dump() Function Serializes an object and writes it to a file
pickle.load() Function Deserializes an object from a file
pickle.dumps() Function Serializes an object to a byte string
pickle.loads() Function Deserializes an object from a byte string
pickle.Pickler Class Provides an interface for serializing Python objects
pickle.Unpickler Class Provides an interface for deserializing Python objects

Examples

Serialize and deserialize a Python object to and from a byte string:

Common Use Cases

  • Saving and loading application state
  • Caching computations
  • Transmitting Python objects over a network
  • Persisting machine learning models

Real-World Example

Here’s how you can use pickle to save and load user settings:

In this example, you use the pickle module to serialize and deserialize the user settings for an app.

The Python pickle Module: How to Persist Objects in Python

For additional information on related topics, take a look at the following resources: