On this page
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
- Passive inspection still does not make untrusted pickles safe to load: Checking opcodes is great for diagnostics and forensics, but for untrusted data, replace pickle with json or a schema-validated format.
optimize()returns new bytes: It removes redundant memo opcodes, producing smaller payloads that unpickle identically.
Common Functions
- pickletools.dis() —
dis(pickle, out=None, memo=None, indentlevel=4, annotate=0)— Produce a symbolic disassembly of a pickle. - pickletools.genops() —
genops(pickle)— Generate all the opcodes in a pickle. - pickletools.optimize() —
optimize(p)— Optimize a pickle string by removing unused PUT opcodes
Linked from
Related notes
- tuts/python3/stdlib_module/pickle Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/pickletools/dis Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/pickletools/genops Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/pickletools/optimize Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/pkgutil Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/builtins Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/dataclasses Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/json Linked here; shared tags: #stdlib