97

I am learning about object serialization for the first time. I tried reading and 'googling' for differences in the modules pickle and shelve but I am not sure I understand it. When to use which one? Pickle can turn every python object into stream of bytes which can be persisted into a file. Then why do we need the module shelve? Isn't pickle faster?

zubinmehta
  • 4,368
  • 7
  • 33
  • 51
  • Is it like the case that pickle is like a very low-level stuff and shelve gives us more ways to store complex objects? – zubinmehta Nov 05 '10 at 03:46
  • 1
    `shelve` provides a dictionary-style interface to pickling. A dictionary interface to pickling is convenient for implementing things like caching of results (so you don't ever recalculate) -- the keys being `*args,**kwds` and the value being the calculated results. – Mike McKerns Feb 11 '14 at 06:30
  • 1
    Note that `shelve` *DOES NOT* enable one to store objects that `pickle` cannot pickle. If you are looking for a better version of `shelve` that can both store the majority of python objects as well as provides a more flexible dictionary interface to disk or database… then you might want to look at `klepto`. See: http://stackoverflow.com/a/32586980/2379433 – Mike McKerns Sep 16 '15 at 16:38

3 Answers3

123

pickle is for serializing some object (or objects) as a single bytestream in a file.

shelve builds on top of pickle and implements a serialization dictionary where objects are pickled, but associated with a key (some string), so you can load your shelved data file and access your pickled objects via keys. This could be more convenient were you to be serializing many objects.

Here is an example of usage between the two. (should work in latest versions of Python 2.7 and Python 3.x).

pickle Example

import pickle

integers = [1, 2, 3, 4, 5]

with open('pickle-example.p', 'wb') as pfile:
    pickle.dump(integers, pfile)

This will dump the integers list to a binary file called pickle-example.p.

Now try reading the pickled file back.

import pickle

with open('pickle-example.p', 'rb') as pfile:
    integers = pickle.load(pfile)
    print integers

The above should output [1, 2, 3, 4, 5].

shelve Example

import shelve

integers = [1, 2, 3, 4, 5]

# If you're using Python 2.7, import contextlib and use
# the line:
# with contextlib.closing(shelve.open('shelf-example', 'c')) as shelf:
with shelve.open('shelf-example', 'c') as shelf:
    shelf['ints'] = integers

Notice how you add objects to the shelf via dictionary-like access.

Read the object back in with code like the following:

import shelve

# If you're using Python 2.7, import contextlib and use
# the line:
# with contextlib.closing(shelve.open('shelf-example', 'r')) as shelf:
with shelve.open('shelf-example', 'r') as shelf:
    for key in shelf.keys():
        print(repr(key), repr(shelf[key]))

The output will be 'ints', [1, 2, 3, 4, 5].

Mojtaba Kamyabi
  • 3,440
  • 3
  • 29
  • 50
wkl
  • 77,184
  • 16
  • 165
  • 176
  • 1
    Can you shed some light on what the 'c' flag is for in the call to `shelve.open`? I googled but could not find an answer. Thanks in advance. – aniketd Sep 24 '15 at 20:01
  • 8
    @aniketd the `'c'` flag tells `shelve` to open the file for reading and writing, or to create the file if needed. It's also described in [`shelve.open`'s documentation](https://docs.python.org/2/library/shelve.html), which shares the same flags as [`anydbm.open`](https://docs.python.org/2/library/anydbm.html#anydbm.open). – wkl Sep 24 '15 at 20:38
  • @birryree What version of Python does your example work with? On 2.7.10, it's indicating that there is no Context Manager implemented for shelve: `----> 5 with shelve.open('shelf-example-file.txt', 'c') as shelf: 6 for k, v in my_dict: 7 shelf[k] = v AttributeError: DbfilenameShelf instance has no attribute '__exit__'` – Pyderman Jan 25 '16 at 22:24
  • @Pyderman I must have verified my code in 3.x but not 2.7.x, probably assuming context manager usage wouldn't be different between them. I updated my examples to say that if you're using Python 2.7, you should `import contextlib` in your code and then wrap your `shelve.open` with `contextlib.closing()`. – wkl Jan 25 '16 at 23:15
  • 4
    This answer would benefit from a paragraph about when to prefer which, and whether pickle is actually significantly faster – lucidbrot Jul 30 '19 at 07:19
8

According to pickle documentation:

Serialization is a more primitive notion than persistence; although pickle reads and writes file objects, it does not handle the issue of naming persistent objects, nor the (even more complicated) issue of concurrent access to persistent objects. 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 shelve module provides a simple interface to pickle and unpickle objects on DBM-style database files.

as - if
  • 2,729
  • 1
  • 20
  • 26
-1

PROs & CONs

Since nobody really mentioned any


DBM:

  • PROs:
  1. Simple to use: DBM is a basic key-value store and requires minimal setup. Fast: DBM provides fast access to data, especially when compared to other disk-based storage options.
  2. Can handle large amounts of data: DBM is able to handle very large datasets, provided you have enough disk space.
  • CONs:
  1. Limited functionality: DBM is a simple key-value store and does not provide advanced functionality such as transactions or multi-process concurrency.
  2. Not well suited for complex data structures: DBM is best suited for storing simple key-value pairs, and may not be the best choice for complex data structures that require multiple values per key or more advanced querying capabilities.

Shelve:

  • PROs:
  1. Rich functionality: Shelve provides a richer API for data access, including the ability to store multiple values per key, support for transactions, and more advanced querying capabilities.
  2. Easy to use: Shelve is a more user-friendly API than DBM, as it provides a dictionary-like interface for data storage and retrieval.
  • CON:

Slower than DBM:

  1. Shelve has a higher overhead compared to DBM and may not be suitable for large datasets or applications with high performance requirements.

  2. May not scale well: Shelve may not be able to handle very large datasets or high concurrency levels, as it can be more prone to locking and other performance issues.

ciurlaro
  • 742
  • 10
  • 22