On this page
  1. pickletools
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Auditing a Pickle Payload Without Executing It
  7. Gotchas & Boundaries
  8. Common Functions

pickletools

Prev: pickle | Up: stdlib_module | Next: pkgutil
Rel: sys, sysconfig, builtins, warnings, dataclasses
Ref: docs.python.org — pickletools
Tags: #public #python3 #stdlib


Import

import pickletools

Overview

Inspection, disassembly, and optimization toolkit for pickle byte streams (dis(), genops(), optimize()). Use pickletools to audit what a pickle payload will import/execute without unpickling it, debug serialization bloat, or strip unused MEMOIZE/PUT opcodes.

Quick Start

import pickle
import pickletools

blob = pickle.dumps({"a": [1, 2, 3]}, protocol=4)
ops = [(op.name, arg) for op, arg, _pos in pickletools.genops(blob)]
assert ops[0] == ("PROTO", 4) and ops[-1] == ("STOP", None)

shrunk = pickletools.optimize(blob)
assert len(shrunk) <= len(blob)

Implementation Walkthrough

1. Auditing a Pickle Payload Without Executing It

genops() parses opcodes passively so you can check for dangerous GLOBAL / STACK_GLOBAL / REDUCE instructions before ever touching pickle.loads():

import pickle
import pickletools

def list_pickle_globals(data: bytes) -> list[str]:
    found = []
    for op, arg, _pos in pickletools.genops(data):
        if op.name in ("GLOBAL", "INST"):
            found.append(str(arg))
    return found

assert list_pickle_globals(pickle.dumps({"k": 1})) == []

Gotchas & Boundaries

Common Functions

Linked from

Related notes