summaryrefslogtreecommitdiffstats
path: root/Lib/shelve.py
blob: b90e6412ecac6ea69f30d3ba4d24933faf8abb6f (plain)
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
"""Manage shelves of pickled objects."""

import pickle
import StringIO

class Shelf:

	def __init__(self, dict):
		self.dict = dict
	
	def keys(self):
		return self.dict.keys()
	
	def __len__(self):
		return self.dict.len()
	
	def has_key(self, key):
		return self.dict.has_key(key)
	
	def __getitem__(self, key):
		return pickle.Unpickler(StringIO.StringIO(self.dict[key])).load()
	
	def __setitem__(self, key, value):
		f = StringIO.StringIO()
		p = pickle.Pickler(f)
		p.dump(value)
		self.dict[key] = f.getvalue()
	
	def __delitem__(self, key):
		del self.dict[key]
	
	def close(self):
		self.db.close()
		self.db = None

class DbShelf(Shelf):
	
	def __init__(self, file):
		import anydbm
		Shelf.__init__(self, anydbm.open(file))

def open(file):
	return DbShelf(file)