czayas
czayas

Reputation: 515

Using __repr__ with shelve module in Python

I'm writing a wrapper class for the shelve module, and I'm intend to use it like a dictionary. Here's the code:

import shelve

class MyShelve:

    def __init__(self, filename='myshelve.db'):
        self.s = shelve.open(filename)

    def __del__(self):
        self.s.close()

    def __repr__(self):
        return repr(self.s)

    def __getitem__(self, k):
        return self.s.get(k, None)

    def __setitem__(self, k, v):
        self.s[k] = v

Everything seemed to work fine until I used the expression "key in dict". This is an example session:

>>> d = {'1': 'One', '2': 'Two'}
>>> d
{'1': 'One', '2': 'Two'}
>>> '1' in d
True
>>> from myshelve import MyShelve
>>> s = MyShelve()
>>> s['1'] = 'One'
>>> s['2'] = 'Two'
>>> s
{'1': 'One', '2': 'Two'}
>>> '1' in s.s
True
>>> '1' in s
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "myshelve.py", line 15, in __getitem__
    return self.s.get(k, None)
  File "/usr/lib64/python2.7/shelve.py", line 113, in get
    if key in self.dict:
  File "/usr/lib64/python2.7/_abcoll.py", line 369, in __contains__
    self[key]
  File "/usr/lib64/python2.7/bsddb/__init__.py", line 270, in __getitem__
    return _DeadlockWrap(lambda: self.db[key])  # self.db[key]
  File "/usr/lib64/python2.7/bsddb/dbutils.py", line 68, in DeadlockWrap
    return function(*_args, **_kwargs)
  File "/usr/lib64/python2.7/bsddb/__init__.py", line 270, in <lambda>
    return _DeadlockWrap(lambda: self.db[key])  # self.db[key]
TypeError: Integer keys only allowed for Recno and Queue DB's

What am I doing wrong?

Upvotes: 0

Views: 204

Answers (2)

Nafiul Islam
Nafiul Islam

Reputation: 82470

First and foremost, always inherit from object. It will save you from a lot of trouble later on. Secondly, you need to use __contains__. Thirdly, when using __contains__ or __getitem__ or any dunder method for that matter, make sure to use exceptions, meaning try-except blocks. Here is a sample of what you're looking for:

class MyShelve(object):

    def __init__(self, filename='myshelve.db'):
        self.s = shelve.open(filename)

    def __del__(self):
        self.s.close()

    def __repr__(self):
        return repr(self.s)

    def __getitem__(self, item):
        return self.s.get(item, False)

    def __contains__(self, item):
        try:
            return item in self.s
        except TypeError:
            return False

    def __setitem__(self, k, v):
        self.s[k] = v

Demo:

In[3]: from shelving import MyShelve
In[4]: s = MyShelve()
In[5]: s['1'] = 'One'
In[6]: s['2'] = 'Two'
In[7]: '1' in s
Out[7]: True

Note that without the exception block the expression 3 in s would evaluate to this:

Traceback (most recent call last):
(...)
TypeError: gdbm key must be string, not int

In hindsight, it is better to use a function with preconfigured values than to use a class in this case, because you will be overwriting a lot of things, and that will waste your time. Furthermore, its easier to use a context manager that with a function that returns a file object rather than having a class that encapsulates your file object (because when you open up a shelve, you actually create a file).

Upvotes: 1

user4179775
user4179775

Reputation:

Try to use __contain__ method, and customize the cases. it is what the "in" operator calls.

class MyShelve:

    def __init__(self,filename='myshelve.db'):
        self.s = shelve.open(filename)

    def __del__(self):
        self.s.close()

    def __repr__(self):
        return repr(self.s)

    def __getitem__(self, k):
        return self.s.get(k, None)

    def __setitem__(self, k, v):
        self.s[k] = v
    def __contains__(self, m):
            return True if (m in self.s.values() or self.s.keys)  else False

    def close(self):
        self.s.close()

    def clear(self):
        self.s.clear()

    def items(self):
         return self._shelve.iteritems()

s= MyShelve()

s['1'] = 'One'
s['2'] = 'two'
print '1' in s #Output: True

Upvotes: 1

Related Questions