1
2
3
4
5
6
7
8 from __future__ import with_statement
9
10 from _weakref import ref
11
12 __all__ = ['WeakSet']
13
14 __version__ = '1.0.0'
15
16
18
19
20
21
22
24
25 self.weakcontainer = ref(weakcontainer)
26
28 w = self.weakcontainer()
29 if w is not None:
30 w._iterating.add(self)
31 return self
32
40
41
44 self.data = set()
45
46 def _remove(item, selfref=ref(self)):
47 self = selfref()
48 if self is not None:
49 if self._iterating:
50 self._pending_removals.append(item)
51 else:
52 self.data.discard(item)
53 self._remove = _remove
54
55 self._pending_removals = []
56 self._iterating = set()
57 if data is not None:
58 self.update(data)
59
65
67 with _IterationGuard(self):
68 for itemref in self.data:
69 item = itemref()
70 if item is not None:
71 yield item
72
74 return sum(x() is not None for x in self.data)
75
77 return ref(item) in self.data
78
80 return (self.__class__, (list(self),),
81 getattr(self, '__dict__', None))
82
83 __hash__ = None
84
85 - def add(self, item):
86 if self._pending_removals:
87 self._commit_removals()
88 self.data.add(ref(item, self._remove))
89
94
96 return self.__class__(self)
97
99 if self._pending_removals:
100 self._commit_removals()
101 while True:
102 try:
103 itemref = self.data.pop()
104 except KeyError:
105 raise KeyError('pop from empty WeakSet')
106 item = itemref()
107 if item is not None:
108 return item
109
114
119
121 if self._pending_removals:
122 self._commit_removals()
123 if isinstance(other, self.__class__):
124 self.data.update(other.data)
125 else:
126 for element in other:
127 self.add(element)
128
130 self.update(other)
131 return self
132
133
134 - def _apply(self, other, method):
135 if not isinstance(other, self.__class__):
136 other = self.__class__(other)
137 newdata = method(other.data)
138 newset = self.__class__()
139 newset.data = newdata
140 return newset
141
144 __sub__ = difference
145
153
162
165 __and__ = intersection
166
171
177
179 return self.data.issubset(ref(item) for item in other)
180 __lt__ = issubset
181
183 return self.data <= set(ref(item) for item in other)
184
186 return self.data.issuperset(ref(item) for item in other)
187 __gt__ = issuperset
188
190 return self.data >= set(ref(item) for item in other)
191
193 if not isinstance(other, self.__class__):
194 return NotImplemented
195 return self.data == set(ref(item) for item in other)
196
199 __xor__ = symmetric_difference
200
208
217
220 __or__ = union
221
224