Difference Between Shelve vs Pickle

The pickle module is used to convert  Python objects into a byte stream. Python objects like lists, dictionaries, etc are supported by it. Whereas, The shelve module is built on top of the pickle module. It implements a serialization dictionary where keys are strings and values are pickled Python objects. Values can be only those objects that can be handled by the pickle module. The shelve module is used when we need to store data that is small in size and less complex. For large and complex data we use a database. It is insecure to load a shelf from an untrusted source because loading a shelf can execute arbitrary code.

Drawbacks of a pickle:

  • Pickle objects are limited only to Python and can only be loaded in Python.
  • The pickle file is unreadable.

Drawbacks of shelve:

  • It does not support concurrent writes.
  • It can not be used to store objects that can not be handled by pickle.


Python Shelve Module

In this article, we will learn to create a shelf file, store data in a shelf file, retrieve the data that is stored in the shelf file, update the data of a shelf file, get a list of shelf keys, Delete data stored in a shelf file and closing shelf file.

The Shelve module is used to store data when using a relational database is not recommended. A shelf object is a dictionary-like object, which is defined in this module. Keys in shelf objects are strings and values are Python objects, that can be handled by the Pickle module. The shelve module comes with Python’s standard utility module, so there is no need to install it externally.

Similar Reads

Classes in the Shelve Module

Class Shelf: It is a subclass of collections.abc.MutableMapping which stores pickled values in the dictionary object. Functions present in the Shelf class get, close, and sync. These functions are covered below. Class BsdDbShelf: A subclass of Shelf that exposes first(), next(), previous(), last(), and set_location() which are available in the third-party bsddb module from pybsddb but not in other database modules. The dictionary object passed to the constructor must support those methods. Functions present in BsdDbShelf class are set_location, next, previous, first, and last. Class DbfilenameShelf: A subclass of Shelf which accepts a filename instead of a dict-like object. The underlying file will be opened using dbm.open(). By default, the file will be created and opened for both reading and writing. This class only contains a constructor....

Difference Between Shelve vs Pickle

...

Contact Us