Dumping and loading with pickle

The pickle module is Python's native format to make objects persistent. The Python Standard Library (https://docs.python.org/3/library/pickle.html) says this about pickle:

The pickle module can transform a complex object into a byte stream and it can transform the byte stream into an object with the same internal structure. Perhaps the most obvious thing to do with these byte streams is to write them onto a file, but it is also conceivable to send them across a network or store them in a database.

The focus of pickle is Python, and only Python. This is not a data-interchange format, such as JSON, YAML, CSV, or XML, that can be used with applications written in other languages.

The pickle module is tightly integrated with Python in a variety of ways. For example, the __reduce__() and __reduce_ex__() methods of a class exist to support the pickle processing.

We can easily pickle our microblog in the following manner:

import pickle
from pathlib import Path with Path("travel_blog.p").open("wb") as target: pickle.dump(travel, target)

This exports the entire travel object to the given file. The file is written as raw bytes, so the open() function uses the "wb" mode.

We can easily recover a picked object in the following manner:

import pickle
from pathlib import Path
with Path("travel_blog.p").open("rb") as source: copy = pickle.load(source)

As pickled data is written as bytes, the file must be opened in the "rb" mode. The pickled objects will be correctly bound to the proper class definitions. The underlying stream of bytes is not intended for human consumption. It is readable after a fashion, but it is not designed for readability as YAML is.

We'll design a class for reliable pickle processing in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset