Lesson · Standard Data Formats
Pickle
55 min readPickle
Pickle can serialize many Python object graphs, but it is Python-specific and unsafe for untrusted data. Its convenience never removes the need for a trust boundary.
Learning goals
- Serialize Python objects with
pickle.dumpsandpickle.dump, and reconstruct them withpickle.loadsandpickle.load. - Explain which object graphs pickle preserves (types, nested structure, shared references) and why that goes beyond JSON.
- State the security rule: deserialization can execute code, so only trusted bytes may be loaded.
- Predict when reconstruction fails (
UnpicklingError,AttributeError,ModuleNotFoundError) after code or class changes. - Choose a protocol deliberately and say what a protocol number implies for compatibility.
Mental model
Pickle records an object graph, not just data: shared references stay shared, class identity is stored by module and name, and reconstruction replays that structure. That power is why pickle bytes are opaque to other languages, and compatibility follows from the same design: the stored class must still exist when the bytes are loaded.
Mental model
read it top to bottom
Python object graph → pickle.dumps → bytes (opaque, versioned) ↓ storage or transport (trusted channel only) pickle.loads → equivalent object graph
Core idea
Pickle is the one standard serializer in this module that promises to rebuild live Python objects, including their classes and reference structure, which makes it convenient for caches and state files and makes it the wrong choice at every trust boundary. The two decisions that matter are trust (load only bytes you produced or fully control) and lifecycle (the classes and module paths must still exist when the data is read back).
Python object serialization
Python object serialization converts in-memory values into a representation that can cross a file, network, or process boundary. Consider compatibility, size, trust, and how much type information the format preserves.
pickle.dump
pickle.dump(obj, file) serializes obj into a binary file object and returns None; pickle.dumps(obj) performs the same conversion and returns bytes. The protocol argument selects the format version, with HIGHEST_PROTOCOL giving the newest and most compact one and older protocols the only ones readable by older interpreters.
pickle.load
pickle.load(file) reads a serialized object from a binary file object and rebuilds it, returning the object; pickle.loads(data) does the same for bytes. Reconstruction resolves stored class references by importing modules and calling reconstruction hooks, which is why the function is unsafe for untrusted input and why it raises AttributeError or ModuleNotFoundError when a class moved.
Compatibility concerns
Serialized data can outlive the code that created it. Version changes, class moves, dependency changes, and platform differences all affect compatibility decisions.
Security risks
Pickle deserialization is a code execution mechanism, not a plain data parser: the stream can direct the interpreter to import modules and call objects while building the result. A malicious stream therefore runs with the privileges of the loading process, and no post-load validation can undo damage caused during load.
Never load untrusted pickle data
Pickle can invoke object reconstruction machinery and is not safe for untrusted input. Treat a pickle stream as executable content from a trust perspective.
Walkthrough
pickle.dumps(trusted_value)turns the dict into abytesobject; unlike JSON output, this is a binary format that only pickle reads, and it records both the list and the dict structure.pickle.loads(blob)rebuilds an equal dict from those bytes; equality holds for the built-in types here, and a value that appeared twice in the original would be shared in the restored object too.- The comment marks the trust decision:
blobwas produced in this same process moments earlier, so loading it is safe; the trailing comment restates the rule for bytes arriving from anywhere else. - Predict before running: the printed dict, then why the
repr()of the pickle bytes is not readable text.
Experiments to try
- Dump the same dict to a file with
pickle.dumpin binary mode, load it back withpickle.load, and assert equality. - Put the same list under two keys, dump and load, and check
restored["a"] is restored["b"]; a shared reference survives the round trip, unlike a JSON round trip. - Dump an instance of a class defined at module level, then rename the class in the source and try to load the bytes; record the exact exception.
- Print
len(blob)underprotocol=0andprotocol=pickle.HIGHEST_PROTOCOLand compare.
Common mistakes
- Loading a pickle from a queue, cache, or upload because it came from inside the system: any writer with access to that channel can craft bytes that execute on load, so trust must be provable, not assumed.
- Using pickle as a stable storage format: class renames or module moves break loading with
AttributeErrororModuleNotFoundErroreven though the bytes are intact. - Producing bytes with one protocol and shipping them to an interpreter that cannot read that version: protocol numbers set a minimum reader, so record which one you produced.
- Opening the file in text mode: pickle writes bytes, so
open(path, "w")raisesTypeErroron the first dump; use"wb"and"rb".
Practice: Easy
- Round-trip
{"numbers": [1, 2, 3]}throughdumpsandloadsand compare withjson.dumpsoutput for the same data; state which of the two you can read as text. - Dump the dict with
protocol=0and printrepr(blob); find the readable fragments and the opcode-like names they contain. - Build a list of strings, dump and load it, and assert equality and type with
isinstance.
Practice: Medium
- Save three objects (a dict, a list, a tuple) to one file as separate
pickle.dumpcalls and read them back with threepickle.loadcalls; explain how the reader knows where each object ends. - Define a class at module level, dump an instance, load it back, and check
isinstance; then try dumping an instance of a class defined inside a function and record the pickling error. - Compare pickle and JSON for the same dict: sizes, readability, and what happens to a tuple and a
datetimein each.
Practice: Hard
- Design a trust policy for a cache directory: files written by the app itself, permissions, and a load path that refuses anything else; describe an attacker model for each check.
- Build a versioning scheme for pickled records: wrap each dump with a version number (a separate file or an envelope) and write the load path that rejects unknown versions with a clear error.
- Study compatibility: dump a namedtuple and an instance with
__slots__, then change the class definition (add a field, remove a method) and record which changes break reconstruction and how the error names itself.
Lesson checklist
- I can round-trip an object with
dump/loadand withdumps/loadsand pick the right pair. - I can explain what pickle preserves that JSON cannot, such as classes and shared references.
- I can state the trust rule and the reason behind it in one sentence.
- I can name the failures that class or module changes cause when old bytes are loaded.
Remember
Pickle serializes live Python objects, including their classes and shared references, and reconstructs them by executing the stream's rebuild instructions, which is both its advantage over JSON and the reason it belongs only behind a trust boundary. Treat stored pickles as long-lived artifacts: pin the protocol, keep class paths stable, and open files in binary mode.
Interview angles
What is the main purpose of **Python object serialization**?+
Python object serialization converts in-memory values into a representation that can cross a file, network, or process boundary. Consider compatibility, size, trust, and how much type information the format preserves.
What should you pay attention to when using **pickle.dump**?+
pickle.dump writes an object's serialized form to a binary file and returns None; dumps returns the bytes instead. The protocol argument fixes the format version, so producer and reader must agree on what the reader can understand.
How does **pickle.load** fit into this lesson?+
pickle.load rebuilds an object from bytes by importing the stored classes and invoking their reconstruction hooks, which is exactly why it must only run on trusted data. Class or module changes between dump and load surface here as AttributeError or ModuleNotFoundError.
Why is `pickle.loads` acceptable for a value you just serialized in the same process but not for bytes arriving over a network?+
Loading executes the stream's instructions for reconstructing objects, so a crafted stream can import modules and call code; the same process that just produced the bytes never had that opportunity, while a network sender does.