Serializing Python Objects with the pickle Module

Intuitive Python — by David Muller (31 / 41)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Chapter 4 Avoiding Traps | TOC | Handling Datetimes with Timezones 👉

Python only includes one standard library module named after a food, and that module is named pickle. The pickle module allows arbitrary Python objects to be serialized into a stream of bytes. This stream of bytes can then be unpickled by another Python program to restore the object that was originally pickled. Let’s explore this in a little more detail.

In the following example pickle is used to serialize and de-serialize a list containing strings and None:

pickle_example.py

​ ​import​ ​pickle​

​ l = [​"a"​, ​"b"​, None, ​"c"​]

​ dumped_l = pickle.dumps(l)
​ ​print​(dumped_l)

​ loaded_l = pickle.loads(dumped_l)
​ ​print​(loaded_l)

If you run python3 pickle_example.py, you should see output like the following:

​<= b'\x80\x03]q\x00(X\x01\x00\x00\x00aq\x01X\x01\x00\x00\x00bq\x02NX\x01\x00
​ \x00\x00cq\x03e.'
​ ['a', 'b', None, 'c']

import pickle makes the pickle module available to our program. A list with strings and None is assigned to the variable l. pickle.dumps(l) returns bytes which are assigned to the dumped_l variable and printed out: this is the pickled representation of the l list. Calling pickle.loads(dumped_l) unpickles the bytes back into a Python object — in this case, a list…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.