Skip to content
Related Articles

Related Articles

Subclass and methods of Shelve class in Python
  • Last Updated : 26 Aug, 2020

Shelve is a module in Python’s standard library which can be used as a non-relational database. The key difference between a dbm and shelve is that shelve can serve its values as any arbitrary object which can be handled by pickle module while in dbm database we can only have standard datatypes of Python as it’s database values. The key in shelve is always a string object while values can be any arbitrary pickle object. 

In this article we will have a look at subclasses of shelve and inbuilt methods can be used to handle the “Shelf” object. Please go through this article to understand the basic retrieving of data (insert, update, and retrieve) from shelf objects.

These are the following three subclasses of shelve :

Class Name Description
 Shelf This is the base class of shelve which stores pickled object values in dict objects and string objects as key.
BsdDbShelf

The pickle object passed to dict object of this sub class must support these functions : next(), previous()

first(), last() and set_location(key), these are available in pybsddb (a third party module) but not in 

other database modules.



DbfilenameShelf

This is also a base class of shelve and it accepts the filename as it’s parameter not a dict object like others. 

It opens  a file using dbm.open(), by default for both read and write.

Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

# In this example we will see
# the different types of objects
# of sub class of shelve class
import shelve
  
# importing bsddb module to create
# a bsddb object which can support
# metioned next(), first() methods..
import bsddb
  
# Shelve Class :
d = {1 : 'geeks', 2 : 'GfG'}
  
# Dictionary object as parameter
Shelf_obj = shelve.Shelf(d)
  
print(type(Shelf_obj))
  
# BsdDbShelf Class :
bsddb_file = bsddb.btopen('spam.db', 'c')
  
# bsddb object as parameter
bsddb_obj = shelve.BsdDbShelf(bsddb_file)
  
print(type(bsddb_obj))
  
# DbfilenameShelf Class :
# File name as parameter
Dbfile_obj = shelve.open('file_name', writeback = True)
  
print(type(Dbfile_obj))

chevron_right


Output :

<class 'shelve.Shelf'>
<class 'shelve.BsdDbShelf'>
<class 'shelve.DbfilenameShelf'>

Class shelve.Shelf(dict, protocol=None, writeback=False, keyencoding=’utf-8′) :

A subclass of collections.abc.MutableMapping, stores pickle values as dictionary objects.

  • By default, pickle version 3 protocol is used, if any other protocol used then specify in protocol parameter in constructor.
  • If writeback parameter is set at True, the Shelf will hold all the entries as cache and release them back to dictionary at the time of sync or close. But it will use more memory and hence sync and close may take longer time.
  • keyencoding parameter the type of encoding used to encode the keys before they are given to dictionary objects.

Following are the methods defined for this class :

Method Description
Shelf.__contains__(key)

Returns a bool class object, True if key given in parameter is present in collable dict 

object otherwise returns False.

Shelf.__del__() Deletes the Shelf dictionary object from the disk.
Shelf.__getitem__(key)

Returns the corresponding value in the dict object corresponding to the key given 



as parameter.

Shelf.__len__() Returns the total number of items present in dictionary.
Shelf.__delitem__(key) Deletes the particular item from the dict corresponding to the key given as parameter.
Shelf.__setitem__(key, value)

This method is used to update the existing item in dictionary to a new value  

corresponding to key given as parameter to a new value also given as second argument.

Shelf.get(key, default=None)

This method will return the value corresponds to key given as parameter if present

 else return the value given as second parameter which was set to None as default.

Shelf.__iter__() Returns a iterator for the dictionary object.
Shelf.close() Closes the current opened Shelf object file.
Shelf.clear()

Does not deletes the dictionary object rather removes all the items present 

in it and makes it empty.

Shelf.pop(key, default = ‘KeyError’)

Removes the item corresponds to given key parameter and returns the key value ,

if present else if key not found then returns the second parameter given if given else 

raise the key error.

Shelf.popitem()

Remove and return some (key, value) pair as tuple from dict otherwise raise a KeyError 

if dict object is empty.

Shelf.setdefault(key,default = None)

Sets second parameter as value to key in first parameter, also sets D[key] = d if key is 

not present in D, or default as None.

Shelf.items() Returns list of 2-tuples of key, value pair for all the items in dictionary object.
Shelf.keys() An iterator containing keys of object.
Shelf.values() An iterator containing value in the object.

The above methods can easily be implemented as we perform manipulations on a simple dictionary objects.

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :