1 try:
2 from collections import defaultdict
3 except ImportError:
4
6 - def __init__(self, default_factory=None, *args, **kwargs):
7 self._default_factory = default_factory
8 dict.__init__(self, *args, **kwargs)
10 if key not in self and self._default_factory:
11 self[key] = self._default_factory()
12 return dict.__getitem__(self, key)
13
15 """
16 This is a collection of named sets. In principal, it contains an empty set
17 for every name, and you can add things to sets, discard things from sets,
18 and so on.
19
20 >>> ks = KeyedSets()
21 >>> ks['tim'] # get a named set
22 set([])
23 >>> ks.add('tim', 'friendly') # add an element to a set
24 >>> ks.add('tim', 'dexterous')
25 >>> ks['tim']
26 set(['friendly', 'dexterous'])
27 >>> 'tim' in ks # membership testing
28 True
29 >>> 'ron' in ks
30 False
31 >>> ks.discard('tim', 'friendly')# discard set element
32 >>> ks.pop('tim') # return set and reset to empty
33 set(['dexterous'])
34 >>> ks['tim']
35 set([])
36
37 This class is careful to conserve memory space - empty sets do not occupy
38 any space.
39 """
42 - def add(self, key, value):
43 if key not in self.d:
44 self.d[key] = set()
45 self.d[key].add(value)
47 if key in self.d:
48 self.d[key].discard(value)
49 if not self.d[key]:
50 del self.d[key]
54 return self.d.get(key, set())
56 if key in self.d:
57 return self.d.pop(key)
58 return set()
59