What Python pickle saves and what it looks up
A Python program can build a dictionary in memory and save it for another run. The standard library module pickle turns the dictionary into bytes, a form that can be written to a file. Turning an object into bytes for storage is called serialization, or pickling when using this module. Loading those bytes to rebuild the object is called unpickling. Python’s pickle documentation
A pickle can tell Python to run code as part of loading. Load only pickle data you trust, such as the bytes you create in these examples. Python’s guidance on trusted pickle data
Turn a dictionary into bytes
In an empty directory, save this as round_trip.py and run python3 round_trip.py. It changes the dictionary after turning it into bytes so the two values are easy to tell apart.
import pickle
profile = {"name": "Ada"}
data = pickle.dumps(profile)
profile["name"] = "Grace"
print(type(data).__name__)
print(pickle.loads(data))
dumps() returns bytes, and loads() takes bytes. The rebuilt dictionary has the value recorded when dumps() ran.
bytes
{'name': 'Ada'}
For a file opened in binary mode ("wb" for writing or "rb" for reading), pickle.dump(value, file) writes directly to the file and pickle.load(file) reads directly from it. Python’s pickle functions
Save an instance and load it in a new run
A class adds a second ingredient. An instance has data such as name, and its class defines methods such as label(). For an ordinary instance like this one, pickle saves its attributes and records where to find its class. Put the class in profile_model.py. Python can import this file as the module profile_model. What Python can pickle
class Profile:
def __init__(self, name):
self.name = name
def label(self):
return f"Profile: {self.name}"
In the same directory, put the writer in save_profile.py. Path.write_bytes() writes the serialized instance to profile.pkl.
import pickle
from pathlib import Path
from profile_model import Profile
profile = Profile("Ada")
Path("profile.pkl").write_bytes(pickle.dumps(profile))
Put the reader in load_profile.py. Path.read_bytes() gets the saved bytes, and pickle.loads() imports profile_model as needed to look up Profile and rebuild the instance.
import pickle
from pathlib import Path
data = Path("profile.pkl").read_bytes()
profile = pickle.loads(data)
print(profile.label())
Run the writer and reader as separate commands. The reader prints Profile: Ada using the name from the file and the method from the class.
python3 save_profile.py
python3 load_profile.py
In profile_model.py, change label() to return f"Member: {self.name}". Run only python3 load_profile.py again. The same file now produces Member: Ada. The changed label comes from the class available when the file is loaded. Ada still comes from the saved instance data. The examples were tested on CPython 3.12.3 and 3.15.2.
See the name stored in the file
pickletools is a standard library tool that prints the instructions in a pickle without rebuilding the object. The -m flag tells Python to run it as a command. Pass it profile.pkl to see the class lookup recorded by the writer. Python’s pickletools documentation
python3 -m pickletools profile.pkl
In the output, the strings 'profile_model' and 'Profile' appear before STACK_GLOBAL, the instruction that uses those two names to find the class. Later lines contain 'name' and 'Ada', the saved attribute and its value.
Use pickle for a trusted local cache that can be rebuilt if its Python classes change. For records that need to survive a refactor or be read by another language, store explicit fields such as name in JSON, a text format for exchanging structured data. Python’s comparison with JSON
Python 3.15’s sentinel() uses the same kind of name lookup to recover the placeholder object itself. A rename shows what happens when the saved name is gone. Why renaming a Python sentinel breaks old pickles