Sub topic 3
How pickle works: a small virtual machine
This chapter assumes you know basic Python, including classes and special methods, and that you know a model's weights have to be saved to disk and loaded later. You don't need to know the pickle format yet.
The model: a program, not a data layout
Most file formats describe data. A CSV file is rows and columns. A JSON file is a tree of values. A pickle file is different. It is a short program for a small virtual machine, and pickle.loads is the interpreter that runs it. The program's job is to rebuild a Python object.
The machine has three parts:
- A byte stream of instructions. Each instruction starts with a one-byte opcode, optionally followed by arguments.
- A stack. Most opcodes push a value onto it or pop values off it to build something bigger.
- A memo. This is a numbered table of objects that have already been built, so they can be referred to again.
Loading runs the opcodes in order until it reaches the STOP opcode. The value on top of the stack at that moment is the result.
A first pickle, written by hand
Protocol 0 is the oldest version of the format. It is plain text, so you can write a pickle by hand:
import pickle
data = b"(I1\nVa\nl."
print(pickle.loads(data)) # [1, 'a']Here is what each instruction does:
(isMARK. It records the current stack height, so a later opcode knows where a group of items starts.I1\nisINT. It pushes the integer 1.Va\nisUNICODE. It pushes the string'a'.lisLIST. It pops everything above the last mark and pushes a list built from those items..isSTOP. It ends the program and returns the top of the stack.
Nothing in the file says "this is a list of an int and a string". The list exists only because the opcodes build it.
A mini unpickler
The loop is small enough to write yourself. This version handles only the five opcodes above:
def mini_unpickle(data: bytes):
stack = []
marks = []
i = 0
while True:
op = data[i:i + 1]
i += 1
if op == b"(": # MARK
marks.append(len(stack))
elif op in (b"I", b"V"): # INT, UNICODE: one argument line
end = data.index(b"\n", i)
arg = data[i:end]
stack.append(int(arg) if op == b"I" else arg.decode("ascii"))
i = end + 1
elif op == b"l": # LIST: collect items above the mark
start = marks.pop()
items = stack[start:]
del stack[start:]
stack.append(items)
elif op == b".": # STOP
return stack.pop()
else:
raise ValueError(f"unsupported opcode {op!r}")
assert mini_unpickle(b"(I1\nVa\nl.") == [1, "a"]The real unpickler in CPython is the same loop with about 70 opcodes. It has no schema and no validation pass. It does not check that the program is safe or sensible before it starts. Each instruction takes effect as soon as it is read.
Opcodes you will meet
Later protocols add compact binary forms of the same ideas. The table lists the opcodes you will see most often when you inspect real pickles.
| Opcode | What it does |
|---|---|
| `PROTO`, `FRAME` | Declare the protocol version and the length of a frame (protocol 4 and later). |
| `MARK` | Remember the current stack position. |
| `BININT1`, `BININT`, `LONG1` | Push an integer of increasing size. |
| `SHORT_BINUNICODE`, `BINUNICODE` | Push a UTF-8 string. |
| `EMPTY_LIST`, `EMPTY_DICT`, `APPENDS`, `SETITEMS` | Create an empty container, then fill it with items above the mark. |
| `TUPLE`, `TUPLE1`, `TUPLE2`, `TUPLE3` | Build a tuple from stack items. |
| `MEMOIZE`, `BINPUT`, `BINGET` | Store the top of the stack in the memo, or push a stored object back. |
| `GLOBAL`, `STACK_GLOBAL` | Import a module attribute by name and push it. |
| `REDUCE` | Pop a callable and an argument tuple, call it, and push the result. |
| `NEWOBJ` | Create an instance of a class without calling its `__init__`. |
| `BUILD` | Pop a state value and use it to restore an object's attributes. |
| `STOP` | End the program. |
The last four rows matter most for security. Pickle does not store a class definition. It stores the class's module and name through GLOBAL, and it rebuilds instances with NEWOBJ, REDUCE and BUILD. The class has to be importable when you load the file. The next chapters show why this is dangerous.
The memo: shared references and cycles
If pickle only wrote values, an object referenced twice would be written twice, and a self-referencing list would never finish. The memo solves both problems. When the pickler writes an object, it records a memo index. When it meets that object again, it emits a BINGET with the index instead of writing the object a second time.
import pickle
shared = [1, 2]
pair = [shared, shared]
restored = pickle.loads(pickle.dumps(pair))
print(restored[0] is restored[1]) # True: one object, referenced twice
loop = []
loop.append(loop)
copy = pickle.loads(pickle.dumps(loop))
print(copy[0] is copy) # True: the cycle is preservedA json round trip would turn pair into two separate lists and would fail on loop. The memo is the reason pickle can restore the real structure of a Python object graph.
Protocol versions
The protocol number sets which opcodes the pickler may emit.
| Protocol | Introduced | Notes |
|---|---|---|
| 0 | Early Python | Text-based and human readable. |
| 1 | Early Python | Old binary format. |
| 2 | Python 2.3 | Efficient pickling of new-style classes. |
| 3 | Python 3.0 | Adds `bytes` objects. Python 2 cannot read it. |
| 4 | Python 3.4 | Large objects, framing, `STACK_GLOBAL`. |
| 5 | Python 3.8 | Out-of-band buffers for large data such as arrays. |
pickle.DEFAULT_PROTOCOL shows what your interpreter writes by default. The unpickler is backward compatible, so a new Python reads old pickles. The reverse fails. A protocol 5 file raises an error on an interpreter that only knows protocol 4.
Edge cases and gotchas
- Trailing bytes are ignored.
pickle.loadsstops at the firstSTOPand discards anything after it. A file can contain a harmless-looking pickle followed by other data, and a tool that only checks the first part may miss the rest. To read several pickles from one stream, callUnpickler.load()repeatedly. - Pickle is Python-specific. Other languages have no standard reader. Even in Python, a pickle depends on the exact module paths of the classes inside it. If a library moves a class to another module, old files stop loading.
- Errors appear late. The unpickler discovers a missing class or a truncated file only when it reaches that opcode. By then, earlier opcodes have already run.
- Instances skip
__init__.NEWOBJallocates the object, andBUILDthen fills in its attributes directly. Any validation in your constructor is bypassed on load.
Exercises
Exercise
What are the three parts of the pickle virtual machine, and what does the STOP opcode return?
Show answer
The parts are the opcode stream, the stack, and the memo. STOP ends the program and returns the object on top of the stack.
Exercise
Extend mini_unpickle to support b"N" (NONE, pushes None) and b"t" (TUPLE, like LIST but builds a tuple). Then check that mini_unpickle(b"(I1\nNt.") returns (1, None).
Show answer
Add two branches to the loop. elif op == b"N": stack.append(None) handles NONE. For TUPLE, copy the LIST branch and push tuple(items) instead of items. The input then gives (1, None).
Exercise
Why can pickle restore loop = []; loop.append(loop) when JSON cannot encode it?
Show answer
The memo gives each built object an index. When the pickler meets the list again inside itself, it writes a memo reference (BINGET) instead of writing the list again. The unpickler pushes the already-built list, which recreates the cycle.