liveBook · Manning

Unpickling

As explained in Python How-To

Unpickling is the process of deserializing a pickle representation to recreate the Python object it contains.

Unpickling restores a Python object from a pickle representation. Open the binary file in read mode, call pickle.load, and assign its return value to a variable. Comparing the restored value with the original verifies that the data was preserved. section 11.3.2

with open("task_tuple_saved.pickle", "rb") as file:
   task_tuple_loaded = pickle.load(file)

with open("task_dict_saved.pickle", "rb") as file:
   task_dict_loaded = pickle.load(file)

Load tuple and dictionary data from pickle files using the required rb mode. section 11.3.2

Restoring a custom object

Unpickling can recreate an instance of a custom class. The restored Task has the same attributes as the original, but it is a different object, so equality of __dict__ does not imply identity. section 11.3.2

Keep these practical limitations in mind:

  • Keep the custom class definition available when unpickling its instances; otherwise Python may raise an AttributeError. section 11.3.2
  • Use pickle when preserving many Python objects, including functions and custom classes, but not modules, file objects, or database connections. section 11.3.3
  • Treat pickle data cautiously because loading specially constructed data can provide an opportunity to embed malicious code. section 11.3.3

How Python How-To covers it

How deep it goes
Explains load usage, binary modes, fidelity checks, custom classes, compatibility limits, and security concerns.
Examples
Uses tuple and dictionary files, a Task instance, a serialized function, and a malicious custom object.
What it assumes
Requires a pickle representation and, for custom instances, the corresponding class definition in the namespace.
What you can do after
Apply unpickling through pickle.load or pickle.loads and verify restored values against their originals.
How it connects
Connects unpickling with pickling, JSON serialization, binary files, bytes objects, functions, and custom classes.

Also explained in

Compare how 2 books explain unpickling →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.