On this page
  1. pickle
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Caching Trusted Local Artifacts with Protocol Version Pinning
  7. Gotchas & Boundaries
  8. Common Functions
  9. Classes & Objects
  10. Constants & Attributes

pickle

Prev: pdb | Up: stdlib_module | Next: pickletools
Rel: copyreg, shelve, marshal, dbm, sqlite3
Ref: docs.python.org — pickle
Tags: #public #python3 #stdlib


Import

import pickle

Overview

Python-specific binary object serializer (dumps, loads, dump, load) capable of persisting arbitrary Python object graphs (including custom classes and cyclic references). CRITICAL SECURITY RULE: pickle.loads() executes arbitrary code during deserialization—use it only for trusted, same-process/same-machine caches, and use json, sqlite3, or struct for any external or untrusted data.

Quick Start

import pickle

payload = {"users": ["Ada", "Grace"], "scores": (10, 20)}
blob = pickle.dumps(payload, protocol=pickle.HIGHEST_PROTOCOL)
restored = pickle.loads(blob)
assert restored == payload

Implementation Walkthrough

1. Caching Trusted Local Artifacts with Protocol Version Pinning

import pickle
from pathlib import Path

def save_cache(path: Path, obj: object) -> None:
    with path.open("wb") as fh:
        pickle.dump(obj, fh, protocol=pickle.HIGHEST_PROTOCOL)

def load_cache(path: Path) -> object:
    with path.open("rb") as fh:
        return pickle.load(fh)

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes