[three]Bean

Context manager for python shelve module

Jun 06, 2011 | categories: python View Comments

Getting in the flow of using context managers is great.

# This feels really old.
f = open('foo.txt')
handle_file(f)
f.close()

# This feels really great.
with open('foo.txt') as f:
    handle_file(f)

Python's shelve module doesn't seem to be up to date; I get so frustrated whenever I try to use it inside with syntax and am refused.

I fixed the problem!

import shelve

class cmshelve(object):
    """ Context manager for shelve """

    def __init__(self, filename):
        self.filename = filename

    def __enter__(self):
        self.obj = shelve.open(self.filename)
        return self.obj

    def __exit__(self, exc_type, exc_value, traceback):
        self.obj.close()

You can use it a little something like this

>>> with cmshelve('foo.db') as d:
...     d['foo'] = "bar"
...     print d
{'foo': 'bar'}

>>> # This proves that the shelve was actually closed
>>> print d
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: invalid operation on closed shelf

>>> # And as you'd expect, you can go back and re-open it just fine
>>> with cmshelve('foo.db') as d:
...     print d
{'foo': 'bar'}
View Comments
blog comments powered by Disqus