PYTHON · PYTHON FOR EVERYONE · CHAPTER 17

Object serialization

Save your objects to disk or send them over the network, and pick the right format without opening the door to malicious code.

8 min readCourse: Python for EveryoneLevel: beginner

From point A to point B

Point A: your script builds a device inventory in memory, but when it ends, everything is lost. Next time, you have to query the network all over again. Point B: by the end of this chapter, you'll save Python objects to disk and load them back, and you'll choose between pickle, shelve and JSON. You'll also recognize when loading serialized data is a security risk.

What serialization is

The objects in your program live in memory and disappear when the program ends. Sometimes you need to save them to disk to use them later. Other times you want to send them over the network to another program, on another machine.

Serializing (also called marshalling) means turning an object's state into bytes or text. You can save that result, transmit it and rebuild the object later. The reverse process is called deserializing.

Python ships several modules for this in the standard library: marshal, pickle, shelve and json. Each one solves a different problem.

marshal: the module you shouldn't use for your data

marshal is the most basic one. Its real job is reading and writing Python bytecode, the .pyc files. It only handles simple built-in types.

>>> import marshal
>>> data = marshal.dumps({"r1": [10, 20]})
>>> marshal.loads(data)
{'r1': [10, 20]}

It works, but don't use it to store your data. It doesn't protect against corrupt or malicious data, and its format can change between Python versions. A file you save today might not load after an upgrade.

pickle: saving and loading almost any object

pickle serializes almost any object: numbers, strings, lists, nested dictionaries and instances of your own classes. The 2 basic functions are dump, which writes an object to a file, and load, which reads it.

pickle produces bytes, not text. That's why the file is opened in binary mode: "wb" to write and "rb" to read. The with block closes the file when it's done.

import pickle

vlans = {10: "users", 20: "voice", 99: "management"}

with open("vlans.pkl", "wb") as f:      # "wb": binary write
    pickle.dump(vlans, f)

with open("vlans.pkl", "rb") as f:      # "rb": binary read
    copy = pickle.load(f)

print(copy)
print(copy == vlans, copy is vlans)
$ python3 vlans.py
{10: 'users', 20: 'voice', 99: 'management'}
True False

The recovered object is equal to the original (== gives True), but it isn't the same object in memory (is gives False). It's a rebuilt copy.

You can save several objects to the same file by calling dump several times. To get them back, you call load the same number of times and in the same order.

import pickle

routers = ["r1", "r2", "r3"]
switches = ["sw1", "sw2"]

with open("devices.pkl", "wb") as f:
    pickle.dump(routers, f)
    pickle.dump(switches, f)

with open("devices.pkl", "rb") as f:
    print(pickle.load(f))               # they're read in the same order
    print(pickle.load(f))
$ python3 devices.py
['r1', 'r2', 'r3']
['sw1', 'sw2']

If you don't need a file, dumps and loads (with a trailing “s,” for string) work directly with a bytes object. That's what you'd use to send the object over a socket or store it in a cache. It also works with your own classes:

import pickle
from dataclasses import dataclass, field


@dataclass
class Interface:
    name: str
    ip: str
    vlans: list[int] = field(default_factory=list)
    active: bool = True


gi01 = Interface("Gi0/1", "192.168.10.1", [10, 20])
data = pickle.dumps(gi01)               # dumps: to bytes, no file
print(type(data), len(data), "bytes")
restored = pickle.loads(data)
print(restored)
$ python3 interface.py
<class 'bytes'> 106 bytes
Interface(name='Gi0/1', ip='192.168.10.1', vlans=[10, 20], active=True)
Python 3.14 update. The book recommended importing cPickle, the C version, and falling back to pickle only if that failed. In Python 3, cPickle no longer exists: pickle uses its C accelerator automatically under the hood, so import pickle is all you need. Also, file() is gone: you use open() in binary mode inside with. The book opened the file in "w" mode; in Python 3 that fails, because pickle writes bytes.
>>> import cPickle
Traceback (most recent call last):
  ...
ModuleNotFoundError: No module named 'cPickle'
>>> import pickle
>>> pickle.Pickler
<class '_pickle.Pickler'>

pickle protocols

pickle has several format versions, called protocols, numbered 0 to 5. Newer ones are more compact and faster, and they support more kinds of objects. The trade-off is that an older Python version can't read a protocol it doesn't know.

dump and dumps accept the protocol parameter. If you don't set it, pickle.DEFAULT_PROTOCOL is used. The constant pickle.HIGHEST_PROTOCOL tells you the highest one available.

>>> import pickle
>>> pickle.DEFAULT_PROTOCOL
5
>>> pickle.HIGHEST_PROTOCOL
5
>>> pickle.dumps(["r1", "r2"], protocol=0)
b'(lp0\nVr1\np1\naVr2\np2\na.'
>>> pickle.dumps(["r1", "r2"])
b'\x80\x05\x95\x0f\x00\x00\x00\x00\x00\x00\x00]\x94(\x8c\x02r1\x94\x8c\x02r2\x94e.'

Protocol 0 is the original one, partly “readable.” Protocol 5, added in Python 3.8, is the default since Python 3.14. In practice, keep the default unless you have to share files with older Python versions.

Python 3.14 update. In Python 2.5 the default protocol was 0, a text format, and the highest was 2. Python 3.0 moved the default to 3, Python 3.8 to 4 and Python 3.14 to 5. In Python 3 every protocol produces bytes.

The pickle security warning

This is the most important point in the chapter. The official documentation puts it bluntly: the pickle module is not secure. A tampered pickle can run arbitrary code the moment you load it.

The reason is that pickle doesn't store just data: it stores instructions for rebuilding objects, and those instructions can include function calls. This harmless example proves it with print. An attacker would use something much worse, like deleting files or opening a connection.

import pickle


class Trap:
    def __reduce__(self):
        # Tells pickle: "to rebuild me, call print with this argument"
        return (print, ("This code ran when the pickle was loaded!",))


payload = pickle.dumps(Trap())
pickle.loads(payload)                   # just loading it runs the call
$ python3 trap.py
This code ran when the pickle was loaded!

The rule is clear:

  • Only load with pickle data you generated yourself and that nobody could have altered.
  • Never load a pickle received from an API, a web form or an email.
  • If you need to check that a pickle hasn't been modified, the documentation suggests signing it with hmac.
  • For data that comes from outside, use a format that only holds data, like JSON.

shelve: a dictionary stored on disk

With dump and load you have to remember the order in which you saved each object. If you saved 30 and want the last one, you have to read the 29 before it. shelve solves that problem.

shelve.open(name) returns a Shelf object that behaves like a persistent dictionary. Each value is stored with pickle under a string key, and you get it back by its key. It also accepts the protocol parameter, which is passed on to pickle.

import shelve

with shelve.open("inventory") as db:    # creates the file if it doesn't exist
    db["r1"] = {"ip": "10.0.0.1", "model": "ISR4331", "vlans": [10, 20]}
    db["sw1"] = {"ip": "10.0.0.11", "model": "C9300", "vlans": [10, 20, 99]}

with shelve.open("inventory") as db:
    print(db["sw1"]["ip"])
    print("r1" in db, "fw1" in db)      # `in` instead of has_key()
    print(sorted(db.keys()))
    for host, data in sorted(db.items()):
        print(host, data["model"])
$ python3 inventory.py
10.0.0.11
True False
['r1', 'sw1']
r1 ISR4331
sw1 C9300

A Shelf has the methods of a dictionary: keys(), values(), items(), get() and the in operator. Keys must be strings. Depending on the available database backend, shelve may create one or more files with names derived from the one you give. In the test with Python 3.14, it created a single file, inventory.

There's a trap worth knowing about. When you read db["r1"] you get a copy; if you modify it in place, the change isn't saved. Read the value, modify it and assign it back:

import shelve

with shelve.open("inventory") as db:
    db["r1"] = {"ip": "10.0.0.1", "vlans": [10, 20]}

    db["r1"]["vlans"].append(30)        # modifies a temporary copy...
    print(db["r1"]["vlans"])            # ...which is lost: [10, 20]

    device = db["r1"]                   # the right way: read,
    device["vlans"].append(30)          # modify
    db["r1"] = device                   # and assign it back
    print(db["r1"]["vlans"])            # [10, 20, 30]
$ python3 writeback.py
[10, 20]
[10, 20, 30]

Another option is to open it with shelve.open("inventory", writeback=True). That way shelve keeps the objects you read in memory and writes them on close, at the cost of more memory. Since shelve uses pickle under the hood, the same warning applies: don't open a shelf from an unknown source.

Python 3.14 update. The book listed has_key among the Shelf methods. That method was removed from dictionaries in Python 3: use key in db. Since Python 3.4, Shelf also works as a context manager, so you can use with instead of calling close().

JSON: the standard format for APIs

The book didn't cover it, but today JSON is the most widely used exchange format. It's what the REST APIs of SDN controllers, cloud platforms and RESTCONF-enabled devices return. It's text, any language can read it, and it holds only data: loading it doesn't run code.

The json module uses the same names as pickle: dumps and loads for strings, dump and load for files. The difference is that it works with text, so the file is opened in text mode with encoding="utf-8".

import json

response = '''
{"hostname": "sw1", "uptime_s": 864000, "ospf": true,
 "interfaces": [{"name": "Gi1/0/1", "vlan": 10, "ip": null}]}
'''

data = json.loads(response)             # JSON text -> Python objects
print(type(data), data["interfaces"][0]["name"], data["ospf"], data["interfaces"][0]["ip"])

data["vlans"] = (10, 20)                # tuples become lists
text = json.dumps(data, indent=2, ensure_ascii=False)
print(text)

with open("sw1.json", "w", encoding="utf-8") as f:
    json.dump(data, f, indent=2)
with open("sw1.json", encoding="utf-8") as f:
    print(json.load(f)["vlans"])
$ python3 api_sw1.py
<class 'dict'> Gi1/0/1 True None
{
  "hostname": "sw1",
  "uptime_s": 864000,
  "ospf": true,
  "interfaces": [
    {
      "name": "Gi1/0/1",
      "vlan": 10,
      "ip": null
    }
  ],
  "vlans": [
    10,
    20
  ]
}
[10, 20]

Notice the conversions: true becomes True, null becomes None, and the tuple (10, 20) comes back as a list. indent=2 produces readable output, and ensure_ascii=False keeps accented and other non-ASCII characters without escaping them.

JSON only understands dictionaries, lists, strings, numbers, booleans and None. To save your own classes, convert them to one of those types first:

import json
from dataclasses import asdict, dataclass


@dataclass
class Interface:
    name: str
    ip: str


gi01 = Interface("Gi0/1", "192.168.10.1")
try:
    json.dumps(gi01)
except TypeError as e:
    print("TypeError:", e)
print(json.dumps(asdict(gi01)))         # convert to a dict first
$ python3 interface_json.py
TypeError: Object of type Interface is not JSON serializable
{"name": "Gi0/1", "ip": "192.168.10.1"}

Which one to choose

ModuleFormatWhat it storesUse it for
marshalBinaryBasic typesNothing of your own: it's for .pyc files
pickleBinaryAlmost any Python objectCaches and trusted internal data
shelveBinary (pickle + dbm)Objects accessible by keySmall trusted local stores
jsonTextDict, list, str, numbers, bool, NoneAPIs, configuration and exchange with other languages

When in doubt, start with JSON. Turn to pickle or shelve only when you need to store objects JSON doesn't support and you control where the data comes from.

Challenge

Answer before you open the solution.

1. Why does this code fail in Python 3: pickle.dump(data, open("x.pkl", "w"))?

Because pickle writes bytes and the file is in text mode. Open it with "wb", preferably inside a with block so it closes on its own.

2. A coworker emails you a backup.pkl file. Do you load it with pickle.load?

No, unless you fully trust where it came from. Loading a pickle can run arbitrary code. Ask for the data in JSON or verify its integrity, for example with an hmac signature.

3. Which protocol does pickle use by default in Python 3.14?

Protocol 5. You can confirm it with pickle.DEFAULT_PROTOCOL. Before 3.14 the default was 4.

4. You saved 30 objects with pickle.dump and need the last one. Which module would have saved you from reading the other 29?

shelve. It stores each object under a string key, and you get it back directly with db["key"].

5. You run json.loads(json.dumps({"vlans": (10, 20)})). What type is vlans in the result?

A list: [10, 20]. JSON doesn't distinguish tuples from lists, so the tuple comes back as a list.

Key takeaways

  • Serializing means turning objects into bytes or text to store or transmit them.
  • pickle.dump and pickle.load work with binary files ("wb", "rb"); dumps and loads, with bytes.
  • In Python 3.14 pickle's default protocol is 5, and you no longer need cPickle.
  • Never load data from an unknown source with pickle or shelve: it can run code.
  • shelve gives you a persistent dictionary with string keys.
  • JSON is the format for APIs and data exchange: data only, readable and safe to load.

In the next chapter, you'll make the jump to databases: you'll store your network inventory in SQLite and query it with SQL from Python.

Official resources

Source and credits. This course is based on the book Python para todos by Raúl González Duque, published under the Creative Commons Attribution 2.5 Spain license. The original book was written for Python 2.5. Jesús Espinoza, with AI assistance, brought it to Python 3.14: he rewrote every chapter in his own words, replaced the examples with networking cases, updated the syntax and the modules that no longer exist, fixed errors in the original and tested all the code with Python 3.14.6 against the official documentation.

Navigate