Reading history

Python pickle and shelve: Saving Python Objects

6 min read 1 views

Save and load Python objects with pickle and shelve, control what is saved, and learn why you must never unpickle untrusted data.

JSON is great for simple data, but it cannot save a date, a set or an object of your own class. Python’s pickle module can save almost any Python object to bytes or a file and load it back exactly as it was. That power comes with a serious danger, though, which every Python programmer must know about. This lesson covers pickle, its safe use, and shelve, a dictionary that lives on disk.

In this lesson you will learn

  • What serialization means
  • pickle.dumps, loads, dump and load
  • Why you must never unpickle data from others
  • Choosing what to save with __getstate__ and __setstate__
  • Storing data by key with shelve

You should know JSON, file handling and classes.

Saving Objects With pickle

Serialization means turning an object into bytes or text so it can be saved or sent somewhere, and later turned back into the same object.

import pickle, json, os, tempfile
from datetime import date

# pickle can save almost any Python object, not just JSON-friendly ones
data = {
    "name": "Nusrat",
    "joined": date(2025, 1, 15),            # JSON cannot store a date
    "courses": {"Python", "SQL"},          # ...or a set
    "marks": (88, 92, 79),                 # ...or keep a tuple a tuple
}

blob = pickle.dumps(data)                  # object -> bytes
print("pickled into", type(blob).__name__)
back = pickle.loads(blob)                  # bytes -> object
print(back == data, type(back["joined"]).__name__, type(back["marks"]).__name__)

try:
    json.dumps(data)
except TypeError as e:
    print("json fails:", e)

# Saving to and loading from a file (binary mode!)
path = os.path.join(tempfile.mkdtemp(), "student.pkl")
with open(path, "wb") as f:
    pickle.dump(data, f)
with open(path, "rb") as f:
    loaded = pickle.load(f)
print("loaded from file:", loaded["name"], sorted(loaded["courses"]))

# Your own classes work too, as long as the class can be imported when loading
class Cart:
    def __init__(self):
        self.items = []
    def add(self, item, price):
        self.items.append((item, price))
    def total(self):
        return sum(p for _, p in self.items)

cart = Cart()
cart.add("Pen", 15)
cart.add("Notebook", 120)
copy = pickle.loads(pickle.dumps(cart))
print("cart total after round trip:", copy.total())

Output

pickled into bytes
True date tuple
json fails: Object of type date is not JSON serializable
loaded from file: Nusrat ['Python', 'SQL']
cart total after round trip: 135
  • pickle.dumps(obj) turns an object into bytes; pickle.loads(data) turns the bytes back into an object.
  • The loaded copy is equal to the original, and types are kept: the date is still a date, the set a set and the tuple a tuple. JSON fails on the date.
  • pickle.dump(obj, file) and pickle.load(file) do the same with files. Open them in binary mode, "wb" and "rb".
  • Objects of your own classes work too. Pickle saves the object’s data and the class name, not the class code. The class must be importable with the same name when you load it.

The Danger, and Safer Tools

import pickle, json, shelve, os, tempfile

# DANGER: unpickling runs code chosen by whoever made the data.
class Sneaky:
    def __reduce__(self):
        # When loaded, pickle will call print(...) -- it could be anything
        return (print, ("!!! this ran while loading the pickle !!!",))

evil_bytes = pickle.dumps(Sneaky())
pickle.loads(evil_bytes)        # never do this with data from someone else
print("Rule: only unpickle data you created yourself.")

# For data you exchange with others, use JSON: it only holds plain data
safe = json.loads('{"name": "Arif", "marks": [72, 81]}')
print("json gives plain data:", safe)

# Controlling what gets pickled with __getstate__ / __setstate__
class Connection:
    def __init__(self, host):
        self.host = host
        self.socket = object()          # pretend this cannot be saved
    def __getstate__(self):
        state = self.__dict__.copy()
        del state["socket"]             # do not save the live connection
        return state
    def __setstate__(self, state):
        self.__dict__.update(state)
        self.socket = None              # reconnect later

c = pickle.loads(pickle.dumps(Connection("db.local")))
print("host:", c.host, "socket:", c.socket)

# shelve: a dictionary that is stored on disk, using pickle inside
path = os.path.join(tempfile.mkdtemp(), "store")
with shelve.open(path) as db:
    db["u1"] = {"name": "Tania", "cgpa": 3.95}
    db["u2"] = {"name": "Mitu", "cgpa": 3.67}
with shelve.open(path) as db:
    for key in sorted(db):
        print(key, db[key]["name"], db[key]["cgpa"])

Output

!!! this ran while loading the pickle !!!
Rule: only unpickle data you created yourself.
json gives plain data: {'name': 'Arif', 'marks': [72, 81]}
host: db.local socket: None
u1 Tania 3.95
u2 Mitu 3.67
  • A pickle can tell Python to call any function while loading, using __reduce__. Here it only calls print, but an attacker could delete files or steal data instead. Loading a pickle can run any code.
  • So: only unpickle data that you created and kept safe. Never unpickle a file someone sent you, an upload, or data from the internet.
  • For data shared with other people or programs, use JSON. It only holds plain data, so loading it cannot run code.
  • __getstate__ chooses what gets saved, and __setstate__ rebuilds the object when loading. Here the live “socket” is left out and set to None.
  • shelve gives you a dictionary stored in a file. Keys are strings, and values can be any picklable object. Data written in one with block is there when you open it again.

Which Format?

FormatStoresSafe to load from others?Readable by other languages?
JSONDicts, lists, strings, numbers, true/false, nullYesYes
CSVTables of textYesYes
pickleAlmost any Python objectNoNo
SQLiteTables with queriesYesYes

Pickle is a good fit for short-term saves inside your own program: caching a slow result, saving a trained machine-learning model you built yourself, or passing data between your own processes (which is what multiprocessing does).

Common Mistakes

  1. Unpickling untrusted data. This is the big one. It is a known way to break into systems.
  2. Opening the file in text mode ("w" or "r"). Pickle needs "wb" and "rb".
  3. Renaming or moving a class after saving objects of it. Old pickles then fail to load.
  4. Using pickle for long-term storage or data shared with other programs. Prefer JSON, CSV or a database.

Practice Exercises

Exercise 1. Pickle the set {3, 1, 2} to bytes, load it back, and check that the result is still a set.

Show answer
import pickle
back = pickle.loads(pickle.dumps({3, 1, 2}))
print(back, type(back).__name__)   # {1, 2, 3} set

Exercise 2. A website lets users upload a “saved game” file, which it loads with pickle.load. What is the risk, and what should it use instead?

Show answer

A user could upload a crafted pickle that runs their own code on the server. The site should store saved games as JSON (or in a database) and check the values after loading.

Frequently Asked Questions

Can a pickle made with one Python version be loaded by another?

Usually yes. Newer Pythons can load pickles from older ones. An older Python may not read the newest protocol, but you can choose an older one with the protocol argument.

What cannot be pickled?

Things tied to the running program: open files, network connections, threads and locks. Lambdas and functions defined inside other functions cannot be pickled either, because they have no importable name.

Summary

  • pickle saves and loads almost any Python object, keeping its exact types.
  • Use binary files: "wb" and "rb".
  • Never unpickle data you did not create yourself; use JSON for shared data.
  • shelve stores pickled values by key in a file, like a dictionary.

Next: Python timeit and cProfile.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *