blob: ff0ace0fc70d2ebbf40a2af34f3449e725605eca [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
Raymond Hettingerfa1480f2002-08-24 02:35:48 +0000179 result = self.__class__()
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000180 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 Rossumdc61cdf2002-08-22 17:23:33 +0000187 def intersection(self, other):
188 """Return the intersection of two sets as a new set.
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000189
Guido van Rossumdc61cdf2002-08-22 17:23:33 +0000190 (I.e. all elements that are in both sets.)
191 """
192 return self & other
193
194 def __xor__(self, other):
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000195 """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 Rossumdc61cdf2002-08-22 17:23:33 +0000199 if not isinstance(other, BaseSet):
200 return NotImplemented
Raymond Hettingerfa1480f2002-08-24 02:35:48 +0000201 result = self.__class__()
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000202 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 Rossumdc61cdf2002-08-22 17:23:33 +0000212 def symmetric_difference(self, other):
213 """Return the symmetric difference of two sets as a new set.
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000214
Guido van Rossumdc61cdf2002-08-22 17:23:33 +0000215 (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 Rossumd6cf3af2002-08-19 16:19:15 +0000220 """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 Rossumdc61cdf2002-08-22 17:23:33 +0000224 if not isinstance(other, BaseSet):
225 return NotImplemented
Raymond Hettingerfa1480f2002-08-24 02:35:48 +0000226 result = self.__class__()
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000227 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 Rossumdc61cdf2002-08-22 17:23:33 +0000234 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 Rossumd6cf3af2002-08-19 16:19:15 +0000240
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 Hettingerde6d6972002-08-21 01:35:29 +0000249 return element in self._data
250 except TypeError:
Guido van Rossum9f872932002-08-21 03:20:44 +0000251 transform = getattr(element, "_as_temporarily_immutable", None)
Raymond Hettingerde6d6972002-08-21 01:35:29 +0000252 if transform is None:
253 raise # re-raise the TypeError exception we caught
254 return transform() in self._data
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000255
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 Hettinger43db0d62002-08-21 02:22:08 +0000261 if len(self) > len(other): # Fast check for obvious cases
262 return False
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000263 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 Hettinger43db0d62002-08-21 02:22:08 +0000271 if len(self) < len(other): # Fast check for obvious cases
272 return False
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000273 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 Petersd06d0302002-08-23 20:06:42 +0000288 # 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 Rossumd6cf3af2002-08-19 16:19:15 +0000292 result = 0
293 for elt in self:
294 result ^= hash(elt)
295 return result
296
Guido van Rossum9f872932002-08-21 03:20:44 +0000297 def _update(self, iterable):
298 # The main loop for update() and the subclass __init__() methods.
Guido van Rossum9f872932002-08-21 03:20:44 +0000299 data = self._data
300 value = True
Raymond Hettinger80d21af2002-08-21 04:12:03 +0000301 it = iter(iterable)
302 while True:
Guido van Rossum9f872932002-08-21 03:20:44 +0000303 try:
Raymond Hettinger80d21af2002-08-21 04:12:03 +0000304 for element in it:
305 data[element] = value
306 return
Guido van Rossum9f872932002-08-21 03:20:44 +0000307 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 Rossumd6cf3af2002-08-19 16:19:15 +0000313
314class ImmutableSet(BaseSet):
315 """Immutable set class."""
316
Guido van Rossum0b650d72002-08-19 16:29:58 +0000317 __slots__ = ['_hashcode']
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000318
319 # BaseSet + hashing
320
Guido van Rossum9f872932002-08-21 03:20:44 +0000321 def __init__(self, iterable=None):
322 """Construct an immutable set from an optional iterable."""
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000323 self._hashcode = None
Guido van Rossum9f872932002-08-21 03:20:44 +0000324 self._data = {}
325 if iterable is not None:
326 self._update(iterable)
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000327
328 def __hash__(self):
329 if self._hashcode is None:
330 self._hashcode = self._compute_hash()
331 return self._hashcode
332
333
334class Set(BaseSet):
335 """ Mutable set class."""
336
337 __slots__ = []
338
339 # BaseSet + operations requiring mutability; no hashing
340
Guido van Rossum9f872932002-08-21 03:20:44 +0000341 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 Rossum5033b362002-08-20 21:38:37 +0000351
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000352 # In-place union, intersection, differences
353
Raymond Hettinger1b9f5d42002-08-24 06:19:02 +0000354 def __ior__(self, other):
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000355 """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 Hettinger1b9f5d42002-08-24 06:19:02 +0000360 def union_update(self, other):
361 """Update a set with the union of itself and another."""
362 self |= other
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000363
Raymond Hettinger1b9f5d42002-08-24 06:19:02 +0000364 def __iand__(self, other):
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000365 """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 Hettinger1b9f5d42002-08-24 06:19:02 +0000372 def intersection_update(self, other):
373 """Update a set with the intersection of itself and another."""
374 self &= other
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000375
Raymond Hettinger1b9f5d42002-08-24 06:19:02 +0000376 def __ixor__(self, other):
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000377 """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 Hettinger1b9f5d42002-08-24 06:19:02 +0000388 def symmetric_difference_update(self, other):
389 """Update a set with the symmetric difference of itself and another."""
390 self ^= other
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000391
Raymond Hettinger1b9f5d42002-08-24 06:19:02 +0000392 def __isub__(self, other):
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000393 """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 Hettinger1b9f5d42002-08-24 06:19:02 +0000401 def difference_update(self, other):
402 """Remove all elements of another set from this set."""
403 self -= other
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000404
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 Rossum9f872932002-08-21 03:20:44 +0000409 self._update(iterable)
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000410
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 Hettingerde6d6972002-08-21 01:35:29 +0000423 self._data[element] = True
424 except TypeError:
Guido van Rossum9f872932002-08-21 03:20:44 +0000425 transform = getattr(element, "_as_immutable", None)
Raymond Hettingerde6d6972002-08-21 01:35:29 +0000426 if transform is None:
427 raise # re-raise the TypeError exception we caught
428 self._data[transform()] = True
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000429
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 Hettingerde6d6972002-08-21 01:35:29 +0000436 del self._data[element]
437 except TypeError:
Guido van Rossum9f872932002-08-21 03:20:44 +0000438 transform = getattr(element, "_as_temporarily_immutable", None)
Raymond Hettingerde6d6972002-08-21 01:35:29 +0000439 if transform is None:
440 raise # re-raise the TypeError exception we caught
441 del self._data[transform()]
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000442
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 Rossume399d082002-08-23 14:45:02 +0000449 self.remove(element)
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000450 except KeyError:
451 pass
452
Guido van Rossumc9196bc2002-08-20 21:51:59 +0000453 def pop(self):
Tim Peters53506be2002-08-23 20:36:58 +0000454 """Remove and return an arbitrary set element."""
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000455 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 Hettingerfa1480f2002-08-24 02:35:48 +0000466class _TemporarilyImmutableSet(BaseSet):
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000467 # Wrap a mutable set as if it was temporarily immutable.
468 # This only supplies hashing and equality comparisons.
469
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000470 def __init__(self, set):
471 self._set = set
Raymond Hettingerfa1480f2002-08-24 02:35:48 +0000472 self._data = set._data # Needed by ImmutableSet.__eq__()
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000473
474 def __hash__(self):
Raymond Hettingerd5018512002-08-24 04:47:42 +0000475 return self._set._compute_hash()