2 min read

Python Shelve Module

The shelve module implements a persistent, dictionary-like object. It is backed by a database file (using dbm), allowing you to store Python objects that can be pickled.

Importing the Module

import shelve

Opening a Shelf

To open a shelf, use shelve.open(). It takes a filename as an argument.

import shelve

# Open a shelf file
with shelve.open('mydata') as shelf:
    # ... use the shelf ...
    pass

Writing Data

You can treat the shelf object like a dictionary. Keys must be strings, but values can be any picklable Python object.

import shelve

with shelve.open('mydata') as shelf:
    shelf['key1'] = {1, 2, 3}
    shelf['key2'] = 'some string'
    shelf['key3'] = [10, 20, 30]

Reading Data

Reading is also like accessing a dictionary.

import shelve

with shelve.open('mydata') as shelf:
    print(shelf['key1'])
    # Output: {1, 2, 3}

    if 'key2' in shelf:
        print(shelf['key2'])

Updating Data

By default, shelve does not track modifications to mutable objects stored in the shelf. To ensure changes are saved, you can either re-assign the object or set writeback=True.

Without writeback=True

with shelve.open('mydata') as shelf:
    data = shelf['key3']
    data.append(40)
    shelf['key3'] = data # Explicitly write back

With writeback=True

with shelve.open('mydata', writeback=True) as shelf:
    shelf['key3'].append(50) # Automatically saved

Note: writeback=True can be slower and consume more memory because it caches all accessed entries.

programming/python/python