]> scripts.mit.edu Git - wizard.git/blob - wizard/sset.py
Added documentation on sset.py
[wizard.git] / wizard / sset.py
1 import os.path
2
3 def make(seen_file):
4     """
5     Return a :class:`SerialisedSet` if given any non-empty string.
6     If given an empty string, return a :class:`DummySerialisedSet`.
7     """
8     if seen_file:
9         return SerializedSet(seen_file)
10     else:
11         return DummySerializedSet()
12
13 class ISerializedSet(object):
14     """A unique unordered collection of strings."""
15     def add(self, name):
16         """Adds a value into the set."""
17         raise NotImplementedError
18
19 class SerializedSet(ISerializedSet):
20     """
21     This set also records itself to a file, so that it
22     is persisted over multiple sessions.
23     """
24     def __init__(self, file):
25         self.set = set()
26         if os.path.isfile(file):
27             for line in open(file, "r"):
28                 self.set.add(line.rstrip())
29         self.file = open(file, "a")
30     def __contains__(self, name):
31         return name in self.set
32     def add(self, name):
33         self.set.add(name)
34         self.file.write(name + "\n")
35         self.file.flush()
36
37 class DummySerializedSet(ISerializedSet):
38     """
39     Dummy object that doesn't actually cache anything and
40     claims that everything needs to be done.
41     """
42     def __contains__(self, name):
43         return False
44     def add(self, name):
45         pass