Serializing Python Objects with the pickle Module
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:
| 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 ...
Get Intuitive Python now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.