Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 1 | """Classes to represent arbitrary sets (including sets of sets). |
| 2 | |
| 3 | This module implements sets using dictionaries whose values are |
| 4 | ignored. The usual operations (union, intersection, deletion, etc.) |
| 5 | are provided as both methods and operators. |
| 6 | |
Guido van Rossum | 290f187 | 2002-08-20 20:05:23 +0000 | [diff] [blame] | 7 | Important: sets are not sequences! While they support 'x in s', |
| 8 | 'len(s)', and 'for x in s', none of those operations are unique for |
| 9 | sequences; for example, mappings support all three as well. The |
| 10 | characteristic operation for sequences is subscripting with small |
| 11 | integers: s[i], for i in range(len(s)). Sets don't support |
| 12 | subscripting at all. Also, sequences allow multiple occurrences and |
| 13 | their elements have a definite order; sets on the other hand don't |
| 14 | record multiple occurrences and don't remember the order of element |
| 15 | insertion (which is why they don't support s[i]). |
| 16 | |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 17 | The following classes are provided: |
| 18 | |
| 19 | BaseSet -- All the operations common to both mutable and immutable |
| 20 | sets. This is an abstract class, not meant to be directly |
| 21 | instantiated. |
| 22 | |
| 23 | Set -- Mutable sets, subclass of BaseSet; not hashable. |
| 24 | |
| 25 | ImmutableSet -- Immutable sets, subclass of BaseSet; hashable. |
| 26 | An iterable argument is mandatory to create an ImmutableSet. |
| 27 | |
| 28 | _TemporarilyImmutableSet -- Not a subclass of BaseSet: just a wrapper |
| 29 | around a Set, hashable, giving the same hash value as the |
| 30 | immutable set equivalent would have. Do not use this class |
| 31 | directly. |
| 32 | |
| 33 | Only hashable objects can be added to a Set. In particular, you cannot |
| 34 | really add a Set as an element to another Set; if you try, what is |
Raymond Hettinger | ede3a0d | 2002-08-20 23:34:01 +0000 | [diff] [blame] | 35 | actually added is an ImmutableSet built from it (it compares equal to |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 36 | the one you tried adding). |
| 37 | |
| 38 | When you ask if `x in y' where x is a Set and y is a Set or |
| 39 | ImmutableSet, x is wrapped into a _TemporarilyImmutableSet z, and |
| 40 | what's tested is actually `z in y'. |
| 41 | |
| 42 | """ |
| 43 | |
| 44 | # Code history: |
| 45 | # |
| 46 | # - Greg V. Wilson wrote the first version, using a different approach |
| 47 | # to the mutable/immutable problem, and inheriting from dict. |
| 48 | # |
| 49 | # - Alex Martelli modified Greg's version to implement the current |
| 50 | # Set/ImmutableSet approach, and make the data an attribute. |
| 51 | # |
| 52 | # - Guido van Rossum rewrote much of the code, made some API changes, |
| 53 | # and cleaned up the docstrings. |
Guido van Rossum | 2658822 | 2002-08-21 02:44:04 +0000 | [diff] [blame] | 54 | # |
Guido van Rossum | 9f87293 | 2002-08-21 03:20:44 +0000 | [diff] [blame] | 55 | # - Raymond Hettinger added a number of speedups and other |
Guido van Rossum | dc61cdf | 2002-08-22 17:23:33 +0000 | [diff] [blame] | 56 | # improvements. |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 57 | |
| 58 | |
| 59 | __all__ = ['BaseSet', 'Set', 'ImmutableSet'] |
| 60 | |
| 61 | |
| 62 | class BaseSet(object): |
| 63 | """Common base class for mutable and immutable sets.""" |
| 64 | |
| 65 | __slots__ = ['_data'] |
| 66 | |
| 67 | # Constructor |
| 68 | |
Guido van Rossum | 5033b36 | 2002-08-20 21:38:37 +0000 | [diff] [blame] | 69 | def __init__(self): |
| 70 | """This is an abstract class.""" |
| 71 | # Don't call this from a concrete subclass! |
| 72 | if self.__class__ is BaseSet: |
Guido van Rossum | 9f87293 | 2002-08-21 03:20:44 +0000 | [diff] [blame] | 73 | raise TypeError, ("BaseSet is an abstract class. " |
| 74 | "Use Set or ImmutableSet.") |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 75 | |
| 76 | # Standard protocols: __len__, __repr__, __str__, __iter__ |
| 77 | |
| 78 | def __len__(self): |
| 79 | """Return the number of elements of a set.""" |
| 80 | return len(self._data) |
| 81 | |
| 82 | def __repr__(self): |
| 83 | """Return string representation of a set. |
| 84 | |
| 85 | This looks like 'Set([<list of elements>])'. |
| 86 | """ |
| 87 | return self._repr() |
| 88 | |
| 89 | # __str__ is the same as __repr__ |
| 90 | __str__ = __repr__ |
| 91 | |
| 92 | def _repr(self, sorted=False): |
| 93 | elements = self._data.keys() |
| 94 | if sorted: |
| 95 | elements.sort() |
| 96 | return '%s(%r)' % (self.__class__.__name__, elements) |
| 97 | |
| 98 | def __iter__(self): |
| 99 | """Return an iterator over the elements or a set. |
| 100 | |
| 101 | This is the keys iterator for the underlying dict. |
| 102 | """ |
| 103 | return self._data.iterkeys() |
| 104 | |
Raymond Hettinger | e87ab3f | 2002-08-24 07:33:06 +0000 | [diff] [blame] | 105 | # Equality comparisons using the underlying dicts |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 106 | |
| 107 | def __eq__(self, other): |
| 108 | self._binary_sanity_check(other) |
| 109 | return self._data == other._data |
| 110 | |
| 111 | def __ne__(self, other): |
| 112 | self._binary_sanity_check(other) |
| 113 | return self._data != other._data |
| 114 | |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 115 | # Copying operations |
| 116 | |
| 117 | def copy(self): |
| 118 | """Return a shallow copy of a set.""" |
Raymond Hettinger | fa1480f | 2002-08-24 02:35:48 +0000 | [diff] [blame] | 119 | result = self.__class__() |
Raymond Hettinger | d9c9151 | 2002-08-21 13:20:51 +0000 | [diff] [blame] | 120 | result._data.update(self._data) |
| 121 | return result |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 122 | |
| 123 | __copy__ = copy # For the copy module |
| 124 | |
| 125 | def __deepcopy__(self, memo): |
| 126 | """Return a deep copy of a set; used by copy module.""" |
| 127 | # This pre-creates the result and inserts it in the memo |
| 128 | # early, in case the deep copy recurses into another reference |
| 129 | # to this same set. A set can't be an element of itself, but |
| 130 | # it can certainly contain an object that has a reference to |
| 131 | # itself. |
| 132 | from copy import deepcopy |
Raymond Hettinger | fa1480f | 2002-08-24 02:35:48 +0000 | [diff] [blame] | 133 | result = self.__class__() |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 134 | memo[id(self)] = result |
| 135 | data = result._data |
| 136 | value = True |
| 137 | for elt in self: |
| 138 | data[deepcopy(elt, memo)] = value |
| 139 | return result |
| 140 | |
Guido van Rossum | dc61cdf | 2002-08-22 17:23:33 +0000 | [diff] [blame] | 141 | # Standard set operations: union, intersection, both differences. |
| 142 | # Each has an operator version (e.g. __or__, invoked with |) and a |
| 143 | # method version (e.g. union). |
Tim Peters | 4924db1 | 2002-08-25 17:10:17 +0000 | [diff] [blame] | 144 | # Subtle: Each pair requires distinct code so that the outcome is |
| 145 | # correct when the type of other isn't suitable. For example, if |
| 146 | # we did "union = __or__" instead, then Set().union(3) would return |
| 147 | # NotImplemented instead of raising TypeError (albeit that *why* it |
| 148 | # raises TypeError as-is is also a bit subtle). |
Guido van Rossum | dc61cdf | 2002-08-22 17:23:33 +0000 | [diff] [blame] | 149 | |
| 150 | def __or__(self, other): |
| 151 | """Return the union of two sets as a new set. |
| 152 | |
| 153 | (I.e. all elements that are in either set.) |
| 154 | """ |
| 155 | if not isinstance(other, BaseSet): |
| 156 | return NotImplemented |
| 157 | result = self.__class__(self._data) |
| 158 | result._data.update(other._data) |
| 159 | return result |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 160 | |
| 161 | def union(self, other): |
| 162 | """Return the union of two sets as a new set. |
| 163 | |
| 164 | (I.e. all elements that are in either set.) |
| 165 | """ |
Guido van Rossum | dc61cdf | 2002-08-22 17:23:33 +0000 | [diff] [blame] | 166 | return self | other |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 167 | |
Guido van Rossum | dc61cdf | 2002-08-22 17:23:33 +0000 | [diff] [blame] | 168 | def __and__(self, other): |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 169 | """Return the intersection of two sets as a new set. |
| 170 | |
| 171 | (I.e. all elements that are in both sets.) |
| 172 | """ |
Guido van Rossum | dc61cdf | 2002-08-22 17:23:33 +0000 | [diff] [blame] | 173 | if not isinstance(other, BaseSet): |
| 174 | return NotImplemented |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 175 | if len(self) <= len(other): |
| 176 | little, big = self, other |
| 177 | else: |
| 178 | little, big = other, self |
Raymond Hettinger | fa1480f | 2002-08-24 02:35:48 +0000 | [diff] [blame] | 179 | result = self.__class__() |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 180 | data = result._data |
| 181 | value = True |
| 182 | for elt in little: |
| 183 | if elt in big: |
| 184 | data[elt] = value |
| 185 | return result |
| 186 | |
Guido van Rossum | dc61cdf | 2002-08-22 17:23:33 +0000 | [diff] [blame] | 187 | def intersection(self, other): |
| 188 | """Return the intersection of two sets as a new set. |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 189 | |
Guido van Rossum | dc61cdf | 2002-08-22 17:23:33 +0000 | [diff] [blame] | 190 | (I.e. all elements that are in both sets.) |
| 191 | """ |
| 192 | return self & other |
| 193 | |
| 194 | def __xor__(self, other): |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 195 | """Return the symmetric difference of two sets as a new set. |
| 196 | |
| 197 | (I.e. all elements that are in exactly one of the sets.) |
| 198 | """ |
Guido van Rossum | dc61cdf | 2002-08-22 17:23:33 +0000 | [diff] [blame] | 199 | if not isinstance(other, BaseSet): |
| 200 | return NotImplemented |
Raymond Hettinger | fa1480f | 2002-08-24 02:35:48 +0000 | [diff] [blame] | 201 | result = self.__class__() |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 202 | data = result._data |
| 203 | value = True |
| 204 | for elt in self: |
| 205 | if elt not in other: |
| 206 | data[elt] = value |
| 207 | for elt in other: |
| 208 | if elt not in self: |
| 209 | data[elt] = value |
| 210 | return result |
| 211 | |
Guido van Rossum | dc61cdf | 2002-08-22 17:23:33 +0000 | [diff] [blame] | 212 | def symmetric_difference(self, other): |
| 213 | """Return the symmetric difference of two sets as a new set. |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 214 | |
Guido van Rossum | dc61cdf | 2002-08-22 17:23:33 +0000 | [diff] [blame] | 215 | (I.e. all elements that are in exactly one of the sets.) |
| 216 | """ |
| 217 | return self ^ other |
| 218 | |
| 219 | def __sub__(self, other): |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 220 | """Return the difference of two sets as a new Set. |
| 221 | |
| 222 | (I.e. all elements that are in this set and not in the other.) |
| 223 | """ |
Guido van Rossum | dc61cdf | 2002-08-22 17:23:33 +0000 | [diff] [blame] | 224 | if not isinstance(other, BaseSet): |
| 225 | return NotImplemented |
Raymond Hettinger | fa1480f | 2002-08-24 02:35:48 +0000 | [diff] [blame] | 226 | result = self.__class__() |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 227 | data = result._data |
| 228 | value = True |
| 229 | for elt in self: |
| 230 | if elt not in other: |
| 231 | data[elt] = value |
| 232 | return result |
| 233 | |
Guido van Rossum | dc61cdf | 2002-08-22 17:23:33 +0000 | [diff] [blame] | 234 | def difference(self, other): |
| 235 | """Return the difference of two sets as a new Set. |
| 236 | |
| 237 | (I.e. all elements that are in this set and not in the other.) |
| 238 | """ |
| 239 | return self - other |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 240 | |
| 241 | # Membership test |
| 242 | |
| 243 | def __contains__(self, element): |
| 244 | """Report whether an element is a member of a set. |
| 245 | |
| 246 | (Called in response to the expression `element in self'.) |
| 247 | """ |
| 248 | try: |
Raymond Hettinger | de6d697 | 2002-08-21 01:35:29 +0000 | [diff] [blame] | 249 | return element in self._data |
| 250 | except TypeError: |
Guido van Rossum | 9f87293 | 2002-08-21 03:20:44 +0000 | [diff] [blame] | 251 | transform = getattr(element, "_as_temporarily_immutable", None) |
Raymond Hettinger | de6d697 | 2002-08-21 01:35:29 +0000 | [diff] [blame] | 252 | if transform is None: |
| 253 | raise # re-raise the TypeError exception we caught |
| 254 | return transform() in self._data |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 255 | |
| 256 | # Subset and superset test |
| 257 | |
| 258 | def issubset(self, other): |
| 259 | """Report whether another set contains this set.""" |
| 260 | self._binary_sanity_check(other) |
Raymond Hettinger | 43db0d6 | 2002-08-21 02:22:08 +0000 | [diff] [blame] | 261 | if len(self) > len(other): # Fast check for obvious cases |
| 262 | return False |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 263 | for elt in self: |
| 264 | if elt not in other: |
| 265 | return False |
| 266 | return True |
| 267 | |
| 268 | def issuperset(self, other): |
| 269 | """Report whether this set contains another set.""" |
| 270 | self._binary_sanity_check(other) |
Raymond Hettinger | 43db0d6 | 2002-08-21 02:22:08 +0000 | [diff] [blame] | 271 | if len(self) < len(other): # Fast check for obvious cases |
| 272 | return False |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 273 | for elt in other: |
| 274 | if elt not in self: |
| 275 | return False |
| 276 | return True |
| 277 | |
| 278 | # Assorted helpers |
| 279 | |
| 280 | def _binary_sanity_check(self, other): |
| 281 | # Check that the other argument to a binary operation is also |
| 282 | # a set, raising a TypeError otherwise. |
| 283 | if not isinstance(other, BaseSet): |
| 284 | raise TypeError, "Binary operation only permitted between sets" |
| 285 | |
| 286 | def _compute_hash(self): |
| 287 | # Calculate hash code for a set by xor'ing the hash codes of |
Tim Peters | d06d030 | 2002-08-23 20:06:42 +0000 | [diff] [blame] | 288 | # the elements. This ensures that the hash code does not depend |
| 289 | # on the order in which elements are added to the set. This is |
| 290 | # not called __hash__ because a BaseSet should not be hashable; |
| 291 | # only an ImmutableSet is hashable. |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 292 | result = 0 |
| 293 | for elt in self: |
| 294 | result ^= hash(elt) |
| 295 | return result |
| 296 | |
Guido van Rossum | 9f87293 | 2002-08-21 03:20:44 +0000 | [diff] [blame] | 297 | def _update(self, iterable): |
| 298 | # The main loop for update() and the subclass __init__() methods. |
Guido van Rossum | 9f87293 | 2002-08-21 03:20:44 +0000 | [diff] [blame] | 299 | data = self._data |
| 300 | value = True |
Raymond Hettinger | 80d21af | 2002-08-21 04:12:03 +0000 | [diff] [blame] | 301 | it = iter(iterable) |
| 302 | while True: |
Guido van Rossum | 9f87293 | 2002-08-21 03:20:44 +0000 | [diff] [blame] | 303 | try: |
Raymond Hettinger | 80d21af | 2002-08-21 04:12:03 +0000 | [diff] [blame] | 304 | for element in it: |
| 305 | data[element] = value |
| 306 | return |
Guido van Rossum | 9f87293 | 2002-08-21 03:20:44 +0000 | [diff] [blame] | 307 | except TypeError: |
| 308 | transform = getattr(element, "_as_immutable", None) |
| 309 | if transform is None: |
| 310 | raise # re-raise the TypeError exception we caught |
| 311 | data[transform()] = value |
| 312 | |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 313 | |
| 314 | class ImmutableSet(BaseSet): |
| 315 | """Immutable set class.""" |
| 316 | |
Guido van Rossum | 0b650d7 | 2002-08-19 16:29:58 +0000 | [diff] [blame] | 317 | __slots__ = ['_hashcode'] |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 318 | |
| 319 | # BaseSet + hashing |
| 320 | |
Guido van Rossum | 9f87293 | 2002-08-21 03:20:44 +0000 | [diff] [blame] | 321 | def __init__(self, iterable=None): |
| 322 | """Construct an immutable set from an optional iterable.""" |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 323 | self._hashcode = None |
Guido van Rossum | 9f87293 | 2002-08-21 03:20:44 +0000 | [diff] [blame] | 324 | self._data = {} |
| 325 | if iterable is not None: |
| 326 | self._update(iterable) |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 327 | |
| 328 | def __hash__(self): |
| 329 | if self._hashcode is None: |
| 330 | self._hashcode = self._compute_hash() |
| 331 | return self._hashcode |
| 332 | |
| 333 | |
| 334 | class Set(BaseSet): |
| 335 | """ Mutable set class.""" |
| 336 | |
| 337 | __slots__ = [] |
| 338 | |
| 339 | # BaseSet + operations requiring mutability; no hashing |
| 340 | |
Guido van Rossum | 9f87293 | 2002-08-21 03:20:44 +0000 | [diff] [blame] | 341 | def __init__(self, iterable=None): |
| 342 | """Construct a set from an optional iterable.""" |
| 343 | self._data = {} |
| 344 | if iterable is not None: |
| 345 | self._update(iterable) |
| 346 | |
| 347 | def __hash__(self): |
| 348 | """A Set cannot be hashed.""" |
| 349 | # We inherit object.__hash__, so we must deny this explicitly |
| 350 | raise TypeError, "Can't hash a Set, only an ImmutableSet." |
Guido van Rossum | 5033b36 | 2002-08-20 21:38:37 +0000 | [diff] [blame] | 351 | |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 352 | # In-place union, intersection, differences |
| 353 | |
Raymond Hettinger | 1b9f5d4 | 2002-08-24 06:19:02 +0000 | [diff] [blame] | 354 | def __ior__(self, other): |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 355 | """Update a set with the union of itself and another.""" |
| 356 | self._binary_sanity_check(other) |
| 357 | self._data.update(other._data) |
| 358 | return self |
| 359 | |
Raymond Hettinger | 1b9f5d4 | 2002-08-24 06:19:02 +0000 | [diff] [blame] | 360 | def union_update(self, other): |
| 361 | """Update a set with the union of itself and another.""" |
| 362 | self |= other |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 363 | |
Raymond Hettinger | 1b9f5d4 | 2002-08-24 06:19:02 +0000 | [diff] [blame] | 364 | def __iand__(self, other): |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 365 | """Update a set with the intersection of itself and another.""" |
| 366 | self._binary_sanity_check(other) |
| 367 | for elt in self._data.keys(): |
| 368 | if elt not in other: |
| 369 | del self._data[elt] |
| 370 | return self |
| 371 | |
Raymond Hettinger | 1b9f5d4 | 2002-08-24 06:19:02 +0000 | [diff] [blame] | 372 | def intersection_update(self, other): |
| 373 | """Update a set with the intersection of itself and another.""" |
| 374 | self &= other |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 375 | |
Raymond Hettinger | 1b9f5d4 | 2002-08-24 06:19:02 +0000 | [diff] [blame] | 376 | def __ixor__(self, other): |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 377 | """Update a set with the symmetric difference of itself and another.""" |
| 378 | self._binary_sanity_check(other) |
| 379 | data = self._data |
| 380 | value = True |
| 381 | for elt in other: |
| 382 | if elt in data: |
| 383 | del data[elt] |
| 384 | else: |
| 385 | data[elt] = value |
| 386 | return self |
| 387 | |
Raymond Hettinger | 1b9f5d4 | 2002-08-24 06:19:02 +0000 | [diff] [blame] | 388 | def symmetric_difference_update(self, other): |
| 389 | """Update a set with the symmetric difference of itself and another.""" |
| 390 | self ^= other |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 391 | |
Raymond Hettinger | 1b9f5d4 | 2002-08-24 06:19:02 +0000 | [diff] [blame] | 392 | def __isub__(self, other): |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 393 | """Remove all elements of another set from this set.""" |
| 394 | self._binary_sanity_check(other) |
| 395 | data = self._data |
| 396 | for elt in other: |
| 397 | if elt in data: |
| 398 | del data[elt] |
| 399 | return self |
| 400 | |
Raymond Hettinger | 1b9f5d4 | 2002-08-24 06:19:02 +0000 | [diff] [blame] | 401 | def difference_update(self, other): |
| 402 | """Remove all elements of another set from this set.""" |
| 403 | self -= other |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 404 | |
| 405 | # Python dict-like mass mutations: update, clear |
| 406 | |
| 407 | def update(self, iterable): |
| 408 | """Add all values from an iterable (such as a list or file).""" |
Guido van Rossum | 9f87293 | 2002-08-21 03:20:44 +0000 | [diff] [blame] | 409 | self._update(iterable) |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 410 | |
| 411 | def clear(self): |
| 412 | """Remove all elements from this set.""" |
| 413 | self._data.clear() |
| 414 | |
| 415 | # Single-element mutations: add, remove, discard |
| 416 | |
| 417 | def add(self, element): |
| 418 | """Add an element to a set. |
| 419 | |
| 420 | This has no effect if the element is already present. |
| 421 | """ |
| 422 | try: |
Raymond Hettinger | de6d697 | 2002-08-21 01:35:29 +0000 | [diff] [blame] | 423 | self._data[element] = True |
| 424 | except TypeError: |
Guido van Rossum | 9f87293 | 2002-08-21 03:20:44 +0000 | [diff] [blame] | 425 | transform = getattr(element, "_as_immutable", None) |
Raymond Hettinger | de6d697 | 2002-08-21 01:35:29 +0000 | [diff] [blame] | 426 | if transform is None: |
| 427 | raise # re-raise the TypeError exception we caught |
| 428 | self._data[transform()] = True |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 429 | |
| 430 | def remove(self, element): |
| 431 | """Remove an element from a set; it must be a member. |
| 432 | |
| 433 | If the element is not a member, raise a KeyError. |
| 434 | """ |
| 435 | try: |
Raymond Hettinger | de6d697 | 2002-08-21 01:35:29 +0000 | [diff] [blame] | 436 | del self._data[element] |
| 437 | except TypeError: |
Guido van Rossum | 9f87293 | 2002-08-21 03:20:44 +0000 | [diff] [blame] | 438 | transform = getattr(element, "_as_temporarily_immutable", None) |
Raymond Hettinger | de6d697 | 2002-08-21 01:35:29 +0000 | [diff] [blame] | 439 | if transform is None: |
| 440 | raise # re-raise the TypeError exception we caught |
| 441 | del self._data[transform()] |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 442 | |
| 443 | def discard(self, element): |
| 444 | """Remove an element from a set if it is a member. |
| 445 | |
| 446 | If the element is not a member, do nothing. |
| 447 | """ |
| 448 | try: |
Guido van Rossum | e399d08 | 2002-08-23 14:45:02 +0000 | [diff] [blame] | 449 | self.remove(element) |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 450 | except KeyError: |
| 451 | pass |
| 452 | |
Guido van Rossum | c9196bc | 2002-08-20 21:51:59 +0000 | [diff] [blame] | 453 | def pop(self): |
Tim Peters | 53506be | 2002-08-23 20:36:58 +0000 | [diff] [blame] | 454 | """Remove and return an arbitrary set element.""" |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 455 | return self._data.popitem()[0] |
| 456 | |
| 457 | def _as_immutable(self): |
| 458 | # Return a copy of self as an immutable set |
| 459 | return ImmutableSet(self) |
| 460 | |
| 461 | def _as_temporarily_immutable(self): |
| 462 | # Return self wrapped in a temporarily immutable set |
| 463 | return _TemporarilyImmutableSet(self) |
| 464 | |
| 465 | |
Raymond Hettinger | fa1480f | 2002-08-24 02:35:48 +0000 | [diff] [blame] | 466 | class _TemporarilyImmutableSet(BaseSet): |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 467 | # Wrap a mutable set as if it was temporarily immutable. |
| 468 | # This only supplies hashing and equality comparisons. |
| 469 | |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 470 | def __init__(self, set): |
| 471 | self._set = set |
Raymond Hettinger | fa1480f | 2002-08-24 02:35:48 +0000 | [diff] [blame] | 472 | self._data = set._data # Needed by ImmutableSet.__eq__() |
Guido van Rossum | d6cf3af | 2002-08-19 16:19:15 +0000 | [diff] [blame] | 473 | |
| 474 | def __hash__(self): |
Raymond Hettinger | d501851 | 2002-08-24 04:47:42 +0000 | [diff] [blame] | 475 | return self._set._compute_hash() |