blob: e88e845c1fd35f443896a246597628841dd57cd5 [file] [log] [blame]
Guido van Rossumd6cf3af2002-08-19 16:19:15 +00001"""Classes to represent arbitrary sets (including sets of sets).
2
3This module implements sets using dictionaries whose values are
4ignored. The usual operations (union, intersection, deletion, etc.)
5are provided as both methods and operators.
6
Guido van Rossum290f1872002-08-20 20:05:23 +00007Important: 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
9sequences; for example, mappings support all three as well. The
10characteristic operation for sequences is subscripting with small
11integers: s[i], for i in range(len(s)). Sets don't support
12subscripting at all. Also, sequences allow multiple occurrences and
13their elements have a definite order; sets on the other hand don't
14record multiple occurrences and don't remember the order of element
15insertion (which is why they don't support s[i]).
16
Guido van Rossumd6cf3af2002-08-19 16:19:15 +000017The following classes are provided:
18
19BaseSet -- All the operations common to both mutable and immutable
20 sets. This is an abstract class, not meant to be directly
21 instantiated.
22
23Set -- Mutable sets, subclass of BaseSet; not hashable.
24
25ImmutableSet -- 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
33Only hashable objects can be added to a Set. In particular, you cannot
34really add a Set as an element to another Set; if you try, what is
Raymond Hettingerede3a0d2002-08-20 23:34:01 +000035actually added is an ImmutableSet built from it (it compares equal to
Guido van Rossumd6cf3af2002-08-19 16:19:15 +000036the one you tried adding).
37
38When you ask if `x in y' where x is a Set and y is a Set or
39ImmutableSet, x is wrapped into a _TemporarilyImmutableSet z, and
40what'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 Rossum26588222002-08-21 02:44:04 +000054#
Guido van Rossum9f872932002-08-21 03:20:44 +000055# - Raymond Hettinger added a number of speedups and other
Guido van Rossumdc61cdf2002-08-22 17:23:33 +000056# improvements.
Guido van Rossumd6cf3af2002-08-19 16:19:15 +000057
58
59__all__ = ['BaseSet', 'Set', 'ImmutableSet']
60
61
62class BaseSet(object):
63 """Common base class for mutable and immutable sets."""
64
65 __slots__ = ['_data']
66
67 # Constructor
68
Guido van Rossum5033b362002-08-20 21:38:37 +000069 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 Rossum9f872932002-08-21 03:20:44 +000073 raise TypeError, ("BaseSet is an abstract class. "
74 "Use Set or ImmutableSet.")
Guido van Rossumd6cf3af2002-08-19 16:19:15 +000075
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 Hettingere87ab3f2002-08-24 07:33:06 +0000105 # Equality comparisons using the underlying dicts
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000106
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 Rossumd6cf3af2002-08-19 16:19:15 +0000115 # Copying operations
116
117 def copy(self):
118 """Return a shallow copy of a set."""
Raymond Hettingerfa1480f2002-08-24 02:35:48 +0000119 result = self.__class__()
Raymond Hettingerd9c91512002-08-21 13:20:51 +0000120 result._data.update(self._data)
121 return result
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000122
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 Hettingerfa1480f2002-08-24 02:35:48 +0000133 result = self.__class__()
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000134 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 Rossumdc61cdf2002-08-22 17:23:33 +0000141 # 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 Peters4924db12002-08-25 17:10:17 +0000144 # 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 Rossumdc61cdf2002-08-22 17:23:33 +0000149
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 Rossumd6cf3af2002-08-19 16:19:15 +0000160
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 Rossumdc61cdf2002-08-22 17:23:33 +0000166 return self | other
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000167
Guido van Rossumdc61cdf2002-08-22 17:23:33 +0000168 def __and__(self, other):
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000169 """Return the intersection of two sets as a new set.
170
171 (I.e. all elements that are in both sets.)
172 """
Guido van Rossumdc61cdf2002-08-22 17:23:33 +0000173 if not isinstance(other, BaseSet):
174 return NotImplemented
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000175 if len(self) <= len(other):
176 little, big = self, other
177 else:
178 little, big = other, self
Tim Petersd33e6be2002-08-25 19:12:45 +0000179 common = filter(big._data.has_key, little._data.iterkeys())
180 return self.__class__(common)
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000181
Guido van Rossumdc61cdf2002-08-22 17:23:33 +0000182 def intersection(self, other):
183 """Return the intersection of two sets as a new set.
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000184
Guido van Rossumdc61cdf2002-08-22 17:23:33 +0000185 (I.e. all elements that are in both sets.)
186 """
187 return self & other
188
189 def __xor__(self, other):
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000190 """Return the symmetric difference of two sets as a new set.
191
192 (I.e. all elements that are in exactly one of the sets.)
193 """
Guido van Rossumdc61cdf2002-08-22 17:23:33 +0000194 if not isinstance(other, BaseSet):
195 return NotImplemented
Raymond Hettingerfa1480f2002-08-24 02:35:48 +0000196 result = self.__class__()
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000197 data = result._data
198 value = True
199 for elt in self:
200 if elt not in other:
201 data[elt] = value
202 for elt in other:
203 if elt not in self:
204 data[elt] = value
205 return result
206
Guido van Rossumdc61cdf2002-08-22 17:23:33 +0000207 def symmetric_difference(self, other):
208 """Return the symmetric difference of two sets as a new set.
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000209
Guido van Rossumdc61cdf2002-08-22 17:23:33 +0000210 (I.e. all elements that are in exactly one of the sets.)
211 """
212 return self ^ other
213
214 def __sub__(self, other):
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000215 """Return the difference of two sets as a new Set.
216
217 (I.e. all elements that are in this set and not in the other.)
218 """
Guido van Rossumdc61cdf2002-08-22 17:23:33 +0000219 if not isinstance(other, BaseSet):
220 return NotImplemented
Raymond Hettingerfa1480f2002-08-24 02:35:48 +0000221 result = self.__class__()
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000222 data = result._data
223 value = True
224 for elt in self:
225 if elt not in other:
226 data[elt] = value
227 return result
228
Guido van Rossumdc61cdf2002-08-22 17:23:33 +0000229 def difference(self, other):
230 """Return the difference of two sets as a new Set.
231
232 (I.e. all elements that are in this set and not in the other.)
233 """
234 return self - other
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000235
236 # Membership test
237
238 def __contains__(self, element):
239 """Report whether an element is a member of a set.
240
241 (Called in response to the expression `element in self'.)
242 """
243 try:
Raymond Hettingerde6d6972002-08-21 01:35:29 +0000244 return element in self._data
245 except TypeError:
Guido van Rossum9f872932002-08-21 03:20:44 +0000246 transform = getattr(element, "_as_temporarily_immutable", None)
Raymond Hettingerde6d6972002-08-21 01:35:29 +0000247 if transform is None:
248 raise # re-raise the TypeError exception we caught
249 return transform() in self._data
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000250
251 # Subset and superset test
252
253 def issubset(self, other):
254 """Report whether another set contains this set."""
255 self._binary_sanity_check(other)
Raymond Hettinger43db0d62002-08-21 02:22:08 +0000256 if len(self) > len(other): # Fast check for obvious cases
257 return False
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000258 for elt in self:
259 if elt not in other:
260 return False
261 return True
262
263 def issuperset(self, other):
264 """Report whether this set contains another set."""
265 self._binary_sanity_check(other)
Raymond Hettinger43db0d62002-08-21 02:22:08 +0000266 if len(self) < len(other): # Fast check for obvious cases
267 return False
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000268 for elt in other:
269 if elt not in self:
270 return False
271 return True
272
Tim Petersea76c982002-08-25 18:43:10 +0000273 # Inequality comparisons using the is-subset relation.
274 __le__ = issubset
275 __ge__ = issuperset
276
277 def __lt__(self, other):
278 self._binary_sanity_check(other)
279 return len(self) < len(other) and self.issubset(other)
280
281 def __gt__(self, other):
282 self._binary_sanity_check(other)
283 return len(self) > len(other) and self.issuperset(other)
284
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000285 # Assorted helpers
286
287 def _binary_sanity_check(self, other):
288 # Check that the other argument to a binary operation is also
289 # a set, raising a TypeError otherwise.
290 if not isinstance(other, BaseSet):
291 raise TypeError, "Binary operation only permitted between sets"
292
293 def _compute_hash(self):
294 # Calculate hash code for a set by xor'ing the hash codes of
Tim Petersd06d0302002-08-23 20:06:42 +0000295 # the elements. This ensures that the hash code does not depend
296 # on the order in which elements are added to the set. This is
297 # not called __hash__ because a BaseSet should not be hashable;
298 # only an ImmutableSet is hashable.
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000299 result = 0
300 for elt in self:
301 result ^= hash(elt)
302 return result
303
Guido van Rossum9f872932002-08-21 03:20:44 +0000304 def _update(self, iterable):
305 # The main loop for update() and the subclass __init__() methods.
Guido van Rossum9f872932002-08-21 03:20:44 +0000306 data = self._data
307 value = True
Raymond Hettinger80d21af2002-08-21 04:12:03 +0000308 it = iter(iterable)
309 while True:
Guido van Rossum9f872932002-08-21 03:20:44 +0000310 try:
Raymond Hettinger80d21af2002-08-21 04:12:03 +0000311 for element in it:
312 data[element] = value
313 return
Guido van Rossum9f872932002-08-21 03:20:44 +0000314 except TypeError:
315 transform = getattr(element, "_as_immutable", None)
316 if transform is None:
317 raise # re-raise the TypeError exception we caught
318 data[transform()] = value
319
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000320
321class ImmutableSet(BaseSet):
322 """Immutable set class."""
323
Guido van Rossum0b650d72002-08-19 16:29:58 +0000324 __slots__ = ['_hashcode']
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000325
326 # BaseSet + hashing
327
Guido van Rossum9f872932002-08-21 03:20:44 +0000328 def __init__(self, iterable=None):
329 """Construct an immutable set from an optional iterable."""
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000330 self._hashcode = None
Guido van Rossum9f872932002-08-21 03:20:44 +0000331 self._data = {}
332 if iterable is not None:
333 self._update(iterable)
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000334
335 def __hash__(self):
336 if self._hashcode is None:
337 self._hashcode = self._compute_hash()
338 return self._hashcode
339
340
341class Set(BaseSet):
342 """ Mutable set class."""
343
344 __slots__ = []
345
346 # BaseSet + operations requiring mutability; no hashing
347
Guido van Rossum9f872932002-08-21 03:20:44 +0000348 def __init__(self, iterable=None):
349 """Construct a set from an optional iterable."""
350 self._data = {}
351 if iterable is not None:
352 self._update(iterable)
353
354 def __hash__(self):
355 """A Set cannot be hashed."""
356 # We inherit object.__hash__, so we must deny this explicitly
357 raise TypeError, "Can't hash a Set, only an ImmutableSet."
Guido van Rossum5033b362002-08-20 21:38:37 +0000358
Tim Peters4a2f91e2002-08-25 18:59:04 +0000359 # In-place union, intersection, differences.
360 # Subtle: The xyz_update() functions deliberately return None,
361 # as do all mutating operations on built-in container types.
362 # The __xyz__ spellings have to return self, though.
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000363
Raymond Hettinger1b9f5d42002-08-24 06:19:02 +0000364 def __ior__(self, other):
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000365 """Update a set with the union of itself and another."""
366 self._binary_sanity_check(other)
367 self._data.update(other._data)
368 return self
369
Raymond Hettinger1b9f5d42002-08-24 06:19:02 +0000370 def union_update(self, other):
371 """Update a set with the union of itself and another."""
372 self |= other
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000373
Raymond Hettinger1b9f5d42002-08-24 06:19:02 +0000374 def __iand__(self, other):
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000375 """Update a set with the intersection of itself and another."""
376 self._binary_sanity_check(other)
377 for elt in self._data.keys():
378 if elt not in other:
379 del self._data[elt]
380 return self
381
Raymond Hettinger1b9f5d42002-08-24 06:19:02 +0000382 def intersection_update(self, other):
383 """Update a set with the intersection of itself and another."""
384 self &= other
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000385
Raymond Hettinger1b9f5d42002-08-24 06:19:02 +0000386 def __ixor__(self, other):
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000387 """Update a set with the symmetric difference of itself and another."""
388 self._binary_sanity_check(other)
389 data = self._data
390 value = True
391 for elt in other:
392 if elt in data:
393 del data[elt]
394 else:
395 data[elt] = value
396 return self
397
Raymond Hettinger1b9f5d42002-08-24 06:19:02 +0000398 def symmetric_difference_update(self, other):
399 """Update a set with the symmetric difference of itself and another."""
400 self ^= other
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000401
Raymond Hettinger1b9f5d42002-08-24 06:19:02 +0000402 def __isub__(self, other):
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000403 """Remove all elements of another set from this set."""
404 self._binary_sanity_check(other)
405 data = self._data
406 for elt in other:
407 if elt in data:
408 del data[elt]
409 return self
410
Raymond Hettinger1b9f5d42002-08-24 06:19:02 +0000411 def difference_update(self, other):
412 """Remove all elements of another set from this set."""
413 self -= other
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000414
415 # Python dict-like mass mutations: update, clear
416
417 def update(self, iterable):
418 """Add all values from an iterable (such as a list or file)."""
Guido van Rossum9f872932002-08-21 03:20:44 +0000419 self._update(iterable)
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000420
421 def clear(self):
422 """Remove all elements from this set."""
423 self._data.clear()
424
425 # Single-element mutations: add, remove, discard
426
427 def add(self, element):
428 """Add an element to a set.
429
430 This has no effect if the element is already present.
431 """
432 try:
Raymond Hettingerde6d6972002-08-21 01:35:29 +0000433 self._data[element] = True
434 except TypeError:
Guido van Rossum9f872932002-08-21 03:20:44 +0000435 transform = getattr(element, "_as_immutable", None)
Raymond Hettingerde6d6972002-08-21 01:35:29 +0000436 if transform is None:
437 raise # re-raise the TypeError exception we caught
438 self._data[transform()] = True
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000439
440 def remove(self, element):
441 """Remove an element from a set; it must be a member.
442
443 If the element is not a member, raise a KeyError.
444 """
445 try:
Raymond Hettingerde6d6972002-08-21 01:35:29 +0000446 del self._data[element]
447 except TypeError:
Guido van Rossum9f872932002-08-21 03:20:44 +0000448 transform = getattr(element, "_as_temporarily_immutable", None)
Raymond Hettingerde6d6972002-08-21 01:35:29 +0000449 if transform is None:
450 raise # re-raise the TypeError exception we caught
451 del self._data[transform()]
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000452
453 def discard(self, element):
454 """Remove an element from a set if it is a member.
455
456 If the element is not a member, do nothing.
457 """
458 try:
Guido van Rossume399d082002-08-23 14:45:02 +0000459 self.remove(element)
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000460 except KeyError:
461 pass
462
Guido van Rossumc9196bc2002-08-20 21:51:59 +0000463 def pop(self):
Tim Peters53506be2002-08-23 20:36:58 +0000464 """Remove and return an arbitrary set element."""
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000465 return self._data.popitem()[0]
466
467 def _as_immutable(self):
468 # Return a copy of self as an immutable set
469 return ImmutableSet(self)
470
471 def _as_temporarily_immutable(self):
472 # Return self wrapped in a temporarily immutable set
473 return _TemporarilyImmutableSet(self)
474
475
Raymond Hettingerfa1480f2002-08-24 02:35:48 +0000476class _TemporarilyImmutableSet(BaseSet):
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000477 # Wrap a mutable set as if it was temporarily immutable.
478 # This only supplies hashing and equality comparisons.
479
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000480 def __init__(self, set):
481 self._set = set
Raymond Hettingerfa1480f2002-08-24 02:35:48 +0000482 self._data = set._data # Needed by ImmutableSet.__eq__()
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000483
484 def __hash__(self):
Raymond Hettingerd5018512002-08-24 04:47:42 +0000485 return self._set._compute_hash()