-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathmyshelf.py
More file actions
46 lines (34 loc) · 1.27 KB
/
myshelf.py
File metadata and controls
46 lines (34 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created on 12/16/13 at 11:26 AM
# myshelf.py
"""myshelf.py contains a minimally-useful version of shelve based on semidbm instead of anydbm,
to support the MedRec package."""
__author__ = 'Jorge R. Herskovic <[email protected]>'
import semidbm
import cPickle as pickle
class shelve(object):
def __init__(self, filename, flag='c', protocol=pickle.HIGHEST_PROTOCOL):
self._my_file = semidbm.open(filename, flag=flag)
self._protocol = protocol
def __iter__(self):
for key in self._my_file:
yield key
def __getitem__(self, item):
return pickle.loads(self._my_file[item])
def __setitem__(self, key, value):
self._my_file[key] = pickle.dumps(value, self._protocol)
def close(self):
self._my_file.close()
self._my_file = None
def __del__(self):
if self._my_file is not None:
self._my_file.close()
def keys(self):
return self._my_file.keys()
def __len__(self):
return len(self.keys())
@classmethod
def open(cls, filename, flag='c', protocol=pickle.HIGHEST_PROTOCOL):
"""Alternate constructor to mimic the semantics of the python shelve module."""
return cls(filename, flag, protocol)