Introduction
Pickle is Python’s own format for saving
objects: almost any Python value, from a list of numbers to a trained model, can be
written to a file with the pickle module and read back later. Files are
usually named .pkl or .pickle. Many machine learning
libraries save models this way, and PyTorch checkpoints contain pickles.
A pickle is a small program for a stack machine that rebuilds the objects, and it can call any Python function while doing so. Loading a pickle from an untrusted source can therefore run any code on the computer. Only load pickles you trust.
Structure
A pickle is a sequence of one-byte opcodes, some followed by
arguments, that push values onto a stack, build lists, dictionaries and objects from
them, and store them in a memo so they can be shared. The last opcode is
STOP, the byte 2E (.).
There are six protocol versions, 0 to 5. Protocol 0 is printable text; the later ones
are binary. From protocol 2, the file starts with the PROTO opcode
80 followed by the protocol number, so most pickles begin
80 02 to 80 05. Protocol 4 and later group the opcodes into
frames, each started by the opcode 95 and an 8-byte length. The
opcodes page lists every opcode of
protocols 0 to 5 with its stack effect. The
protocols and stream rules page gives
the Python version of each protocol, frames, out-of-band buffers, persistent IDs, the
extension registry, the memo and __reduce__, and the
name mapping page the Python 2
compatibility tables.
In the explorer
The opcode page follows Python’s pickletools for protocols 0 to 5. The explorer reads a dropped
.pkl or .pickle file as a disassembler and stack simulator: every opcode, the rebuilt
objects, the memo, the imported names and every validity problem, and it never unpickles or runs anything.
A file with several pickles, written by repeated dump calls, is read pickle by pickle (each with
its own protocol, frames and an empty memo), shown as “Pickle 1”, “Pickle 2” and so on. A later piece counts as
a pickle when it starts with PROTO 2 to 5, even if damaged, or when it reads cleanly to its own
STOP; any other bytes after the last pickle stay trailing data with a problem, so a damaged
protocol 0 or 1 pickle that follows another is shown as trailing data. Byte strings (a NumPy array, an embedded
file) are shown as bytes, and the checks that depend on the loading program (whether a class defines
__setstate__, what a persistent ID or extension code means) are shown as notes and labels, not as
errors.
Links
Software
Developers
- pickle – Python’s built-in module (Python)
- pickletools – Python’s built-in disassembler for pickles (Python)