liveBook · Manning

Pickle

As explained in The Quick Python Book, Fourth Edition

pickle is a Python standard-library serialization facility for converting Python objects to and from a byte stream.

pickle converts Python object hierarchies into byte streams and reconstructs them later. It provides compact persistence for program state without manually writing code for each value. section 13.8

Use the module through paired dump/load operations:

  • Open a binary file with 'wb' and call pickle.dump for each object to save. section 13.8
  • Reopen the file with 'rb' and call pickle.load in the same order to restore the objects. section 13.8
  • Pickle handles numbers, strings, lists, tuples, dictionaries, class instances, shared objects, and cyclic references. section 13.8
  • Pickle cannot serialize code objects or system resources such as files and sockets. section 13.8

Save and restore related values

Store a dictionary such as {'a': 42, 'b': 3.14, 'c': 'test'} with pickle.dump inside a 'with' block, then return pickle.load from a similarly opened binary file. The restored dictionary retains its values and structure. section 13.8

import pickle
a = 42
b = 3.14
c = "test"
file = open("state", 'wb')
pickle.dump(a, file)
pickle.dump(b, file)
pickle.dump(c, file)
file.close()

Inspect the direct sequence for writing several values: import pickle, open a binary file, dump a, b, and c, then close the file. section 13.8

import pickle
file = open("state", 'rb')
a = pickle.load(file)
b = pickle.load(file)
c = pickle.load(file)
file.close()
print(f"{a=} {b=} {c=}")
 
a=42 b=3.14 c='test'

Inspect the matching read sequence, where pickle.load restores each value in its original order and prints 42, 3.14, and 'test'. section 13.8

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains byte-stream conversion, ordered dump/load calls, supported structures, and serialization limits without implementation internals.
Examples
Demonstrates serializing separate scalar values, restoring them, saving a dictionary, and maintaining a disk-backed calculation cache.
What it assumes
Assumes familiarity with Python variables, dictionaries, functions, and opening files in binary modes.
What you can do after
Apply pickle.dump and pickle.load to save and restore Python values through binary files.
How it connects
Connects serialization with file objects, binary files, program state, and shelving.

Also explained in

Compare how 3 books explain pickle →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.