In Python 3, you will fetch an error when importing the cPickle module. This brief post will show you a simple method of resolving such as error.
The pickle
module implements binary protocols for serializing and de-serializing a Python object structure. “Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream (from a binary file or bytes-like object is converted back into an object hierarchy.
The pickle
module implements an algorithm for turning an arbitrary Python object into a series of bytes.
The cPickle
module implements the same algorithm, in C instead of Python. It is many times faster than the Python implementation, but does not allow the user to subclass from Pickle.
Importing cPickle Module in Python 3
The cPickle
module is included in the Standard Library of Python version 2. Hence, if you are in Python 3, you need to import the cPickle
module as:
>>> import _pickle as cPickle
It is recommended to just use the pickle
module that comes in the Standard Library of both Python 2 and Python 3.
You can also add error handling if you wish to support both Python versions as:
try:
import cPickle as pickle
except:
import pickle