1 # Access WeakSet through the weakref module.
2 # This code is separated-out because it is needed
3 # by abc.py to load everything else at startup.
5 from _weakref
import ref
10 def __init__(self
, data
=None):
12 def _remove(item
, selfref
=ref(self
)):
15 self
.data
.discard(item
)
16 self
._remove
= _remove
21 for itemref
in self
.data
:
27 return sum(x() is not None for x
in self
.data
)
29 def __contains__(self
, item
):
30 return ref(item
) in self
.data
33 return (self
.__class
__, (list(self
),),
34 getattr(self
, '__dict__', None))
37 self
.data
.add(ref(item
, self
._remove
))
43 return self
.__class
__(self
)
48 itemref
= self
.data
.pop()
50 raise KeyError('pop from empty WeakSet')
55 def remove(self
, item
):
56 self
.data
.remove(ref(item
))
58 def discard(self
, item
):
59 self
.data
.discard(ref(item
))
61 def update(self
, other
):
62 if isinstance(other
, self
.__class
__):
63 self
.data
.update(other
.data
)
67 def __ior__(self
, other
):
71 # Helper functions for simple delegating methods.
72 def _apply(self
, other
, method
):
73 if not isinstance(other
, self
.__class
__):
74 other
= self
.__class
__(other
)
75 newdata
= method(other
.data
)
76 newset
= self
.__class
__()
80 def difference(self
, other
):
81 return self
._apply
(other
, self
.data
.difference
)
84 def difference_update(self
, other
):
88 self
.data
.difference_update(ref(item
) for item
in other
)
89 def __isub__(self
, other
):
93 self
.data
.difference_update(ref(item
) for item
in other
)
96 def intersection(self
, other
):
97 return self
._apply
(other
, self
.data
.intersection
)
98 __and__
= intersection
100 def intersection_update(self
, other
):
101 self
.data
.intersection_update(ref(item
) for item
in other
)
102 def __iand__(self
, other
):
103 self
.data
.intersection_update(ref(item
) for item
in other
)
106 def issubset(self
, other
):
107 return self
.data
.issubset(ref(item
) for item
in other
)
110 def __le__(self
, other
):
111 return self
.data
<= set(ref(item
) for item
in other
)
113 def issuperset(self
, other
):
114 return self
.data
.issuperset(ref(item
) for item
in other
)
117 def __ge__(self
, other
):
118 return self
.data
>= set(ref(item
) for item
in other
)
120 def __eq__(self
, other
):
121 if not isinstance(other
, self
.__class
__):
122 return NotImplemented
123 return self
.data
== set(ref(item
) for item
in other
)
125 def symmetric_difference(self
, other
):
126 return self
._apply
(other
, self
.data
.symmetric_difference
)
127 __xor__
= symmetric_difference
129 def symmetric_difference_update(self
, other
):
133 self
.data
.symmetric_difference_update(ref(item
) for item
in other
)
134 def __ixor__(self
, other
):
138 self
.data
.symmetric_difference_update(ref(item
) for item
in other
)
141 def union(self
, other
):
142 return self
._apply
(other
, self
.data
.union
)
145 def isdisjoint(self
, other
):
146 return len(self
.intersection(other
)) == 0