1 # −*− coding: UTF−8 −*−
6 A class providing dictionary access to a folder.
7 cribbed from http://bitbucket.org/howthebodyworks/fsdict
12 return tempfile.mkdtemp()
16 provide dictionary access to a temp dir. I don't know why i didn't just use
17 shelve. I think I forgot it existed.
19 N.B. the keys ordering here is FS-dependent and thus unlike to be the same as
20 with a real dict. beware.
25 def __init__(self, initval=[], work_dir=None, *args, **kwargs):
27 work_dir = get_tmp_dir()
28 self.work_dir = path(work_dir)
29 if not self.work_dir.exists():
31 for key, val in getattr(initval, 'iteritems', initval.__iter__)():
33 self.unclean_dirs.append(self.work_dir)
34 super(FSDict, self).__init__(*args, **kwargs)
36 def __setitem__(self, key, val, *args, **kwargs):
37 pickle.dump(val, open(self.work_dir/key, 'w'))
39 def __getitem__(self, key, *args, **kwargs):
40 return pickle.load(open(self.work_dir/key, 'r'))
44 a hardline list of everything in the dict. may be long.
46 return repr(dict([(k, v) for k, v in self.iteritems()]))
50 str is truncated somewhat.
53 return '{' + repr(self.keys()[0]) + ':' + repr(self[self.keys()[0]]) + ', ...'
55 return super(FSDict, self).__str__()
57 def keys(self, *args, **kwargs):
58 return [key for key in self.iterkeys()]
60 def iterkeys(self, *args, **kwargs):
61 for f in self.work_dir.files():
62 yield str(self.work_dir.relpathto(f))
65 for key in self.iterkeys():
69 for key in self.iterkeys():
72 def __delitem__(self, key, *args, **kwargs):
73 (self.work_dir/key).unlink()
75 def values(self, *args, **kwargs):
76 return [self[key] for key in self.keys()]
79 self.work_dir.rmtree()
83 for fsd in cls.unclean_dirs:
89 def move(self, new_dir):
92 self.work_dir.move(new_dir)
96 self.work_dir = new_dir
98 def __eq__(self, other):
100 when compared to a dict, equate equal if all keys and vals are equal
101 note, this is potentially expensive.
103 #duck type our way to sanity:
104 if not hasattr(other, 'keys'): return False
105 #OK, it's a dict-ish thing
107 return all([self[key]==other[key] for key in other]) and \
108 len(self.keys())==len(other.keys())