blob: d42259108cdb81695ca70d3ce7618c101d942f4d [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).
144
145 def __or__(self, other):
146 """Return the union of two sets as a new set.
147
148 (I.e. all elements that are in either set.)
149 """
150 if not isinstance(other, BaseSet):
151 return NotImplemented
152 result = self.__class__(self._data)
153 result._data.update(other._data)
154 return result
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000155
156 def union(self, other):
157 """Return the union of two sets as a new set.
158
159 (I.e. all elements that are in either set.)
160 """
Guido van Rossumdc61cdf2002-08-22 17:23:33 +0000161 return self | other
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000162
Guido van Rossumdc61cdf2002-08-22 17:23:33 +0000163 def __and__(self, other):
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000164 """Return the intersection of two sets as a new set.
165
166 (I.e. all elements that are in both sets.)
167 """
Guido van Rossumdc61cdf2002-08-22 17:23:33 +0000168 if not isinstance(other, BaseSet):
169 return NotImplemented
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000170 if len(self) <= len(other):
171 little, big = self, other
172 else:
173 little, big = other, self
Raymond Hettingerfa1480f2002-08-24 02:35:48 +0000174 result = self.__class__()
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000175 data = result._data
176 value = True
177 for elt in little:
178 if elt in big:
179 data[elt] = value
180 return result
181
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
273 # Assorted helpers
274
275 def _binary_sanity_check(self, other):
276 # Check that the other argument to a binary operation is also
277 # a set, raising a TypeError otherwise.
278 if not isinstance(other, BaseSet):
279 raise TypeError, "Binary operation only permitted between sets"
280
281 def _compute_hash(self):
282 # Calculate hash code for a set by xor'ing the hash codes of
Tim Petersd06d0302002-08-23 20:06:42 +0000283 # the elements. This ensures that the hash code does not depend
284 # on the order in which elements are added to the set. This is
285 # not called __hash__ because a BaseSet should not be hashable;
286 # only an ImmutableSet is hashable.
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000287 result = 0
288 for elt in self:
289 result ^= hash(elt)
290 return result
291
Guido van Rossum9f872932002-08-21 03:20:44 +0000292 def _update(self, iterable):
293 # The main loop for update() and the subclass __init__() methods.
Guido van Rossum9f872932002-08-21 03:20:44 +0000294 data = self._data
295 value = True
Raymond Hettinger80d21af2002-08-21 04:12:03 +0000296 it = iter(iterable)
297 while True:
Guido van Rossum9f872932002-08-21 03:20:44 +0000298 try:
Raymond Hettinger80d21af2002-08-21 04:12:03 +0000299 for element in it:
300 data[element] = value
301 return
Guido van Rossum9f872932002-08-21 03:20:44 +0000302 except TypeError:
303 transform = getattr(element, "_as_immutable", None)
304 if transform is None:
305 raise # re-raise the TypeError exception we caught
306 data[transform()] = value
307
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000308
309class ImmutableSet(BaseSet):
310 """Immutable set class."""
311
Guido van Rossum0b650d72002-08-19 16:29:58 +0000312 __slots__ = ['_hashcode']
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000313
314 # BaseSet + hashing
315
Guido van Rossum9f872932002-08-21 03:20:44 +0000316 def __init__(self, iterable=None):
317 """Construct an immutable set from an optional iterable."""
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000318 self._hashcode = None
Guido van Rossum9f872932002-08-21 03:20:44 +0000319 self._data = {}
320 if iterable is not None:
321 self._update(iterable)
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000322
323 def __hash__(self):
324 if self._hashcode is None:
325 self._hashcode = self._compute_hash()
326 return self._hashcode
327
328
329class Set(BaseSet):
330 """ Mutable set class."""
331
332 __slots__ = []
333
334 # BaseSet + operations requiring mutability; no hashing
335
Guido van Rossum9f872932002-08-21 03:20:44 +0000336 def __init__(self, iterable=None):
337 """Construct a set from an optional iterable."""
338 self._data = {}
339 if iterable is not None:
340 self._update(iterable)
341
342 def __hash__(self):
343 """A Set cannot be hashed."""
344 # We inherit object.__hash__, so we must deny this explicitly
345 raise TypeError, "Can't hash a Set, only an ImmutableSet."
Guido van Rossum5033b362002-08-20 21:38:37 +0000346
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000347 # In-place union, intersection, differences
348
Raymond Hettinger1b9f5d42002-08-24 06:19:02 +0000349 def __ior__(self, other):
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000350 """Update a set with the union of itself and another."""
351 self._binary_sanity_check(other)
352 self._data.update(other._data)
353 return self
354
Raymond Hettinger1b9f5d42002-08-24 06:19:02 +0000355 def union_update(self, other):
356 """Update a set with the union of itself and another."""
357 self |= other
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000358
Raymond Hettinger1b9f5d42002-08-24 06:19:02 +0000359 def __iand__(self, other):
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000360 """Update a set with the intersection of itself and another."""
361 self._binary_sanity_check(other)
362 for elt in self._data.keys():
363 if elt not in other:
364 del self._data[elt]
365 return self
366
Raymond Hettinger1b9f5d42002-08-24 06:19:02 +0000367 def intersection_update(self, other):
368 """Update a set with the intersection of itself and another."""
369 self &= other
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000370
Raymond Hettinger1b9f5d42002-08-24 06:19:02 +0000371 def __ixor__(self, other):
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000372 """Update a set with the symmetric difference of itself and another."""
373 self._binary_sanity_check(other)
374 data = self._data
375 value = True
376 for elt in other:
377 if elt in data:
378 del data[elt]
379 else:
380 data[elt] = value
381 return self
382
Raymond Hettinger1b9f5d42002-08-24 06:19:02 +0000383 def symmetric_difference_update(self, other):
384 """Update a set with the symmetric difference of itself and another."""
385 self ^= other
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000386
Raymond Hettinger1b9f5d42002-08-24 06:19:02 +0000387 def __isub__(self, other):
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000388 """Remove all elements of another set from this set."""
389 self._binary_sanity_check(other)
390 data = self._data
391 for elt in other:
392 if elt in data:
393 del data[elt]
394 return self
395
Raymond Hettinger1b9f5d42002-08-24 06:19:02 +0000396 def difference_update(self, other):
397 """Remove all elements of another set from this set."""
398 self -= other
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000399
400 # Python dict-like mass mutations: update, clear
401
402 def update(self, iterable):
403 """Add all values from an iterable (such as a list or file)."""
Guido van Rossum9f872932002-08-21 03:20:44 +0000404 self._update(iterable)
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000405
406 def clear(self):
407 """Remove all elements from this set."""
408 self._data.clear()
409
410 # Single-element mutations: add, remove, discard
411
412 def add(self, element):
413 """Add an element to a set.
414
415 This has no effect if the element is already present.
416 """
417 try:
Raymond Hettingerde6d6972002-08-21 01:35:29 +0000418 self._data[element] = True
419 except TypeError:
Guido van Rossum9f872932002-08-21 03:20:44 +0000420 transform = getattr(element, "_as_immutable", None)
Raymond Hettingerde6d6972002-08-21 01:35:29 +0000421 if transform is None:
422 raise # re-raise the TypeError exception we caught
423 self._data[transform()] = True
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000424
425 def remove(self, element):
426 """Remove an element from a set; it must be a member.
427
428 If the element is not a member, raise a KeyError.
429 """
430 try:
Raymond Hettingerde6d6972002-08-21 01:35:29 +0000431 del self._data[element]
432 except TypeError:
Guido van Rossum9f872932002-08-21 03:20:44 +0000433 transform = getattr(element, "_as_temporarily_immutable", None)
Raymond Hettingerde6d6972002-08-21 01:35:29 +0000434 if transform is None:
435 raise # re-raise the TypeError exception we caught
436 del self._data[transform()]
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000437
438 def discard(self, element):
439 """Remove an element from a set if it is a member.
440
441 If the element is not a member, do nothing.
442 """
443 try:
Guido van Rossume399d082002-08-23 14:45:02 +0000444 self.remove(element)
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000445 except KeyError:
446 pass
447
Guido van Rossumc9196bc2002-08-20 21:51:59 +0000448 def pop(self):
Tim Peters53506be2002-08-23 20:36:58 +0000449 """Remove and return an arbitrary set element."""
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000450 return self._data.popitem()[0]
451
452 def _as_immutable(self):
453 # Return a copy of self as an immutable set
454 return ImmutableSet(self)
455
456 def _as_temporarily_immutable(self):
457 # Return self wrapped in a temporarily immutable set
458 return _TemporarilyImmutableSet(self)
459
460
Raymond Hettingerfa1480f2002-08-24 02:35:48 +0000461class _TemporarilyImmutableSet(BaseSet):
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000462 # Wrap a mutable set as if it was temporarily immutable.
463 # This only supplies hashing and equality comparisons.
464
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000465 def __init__(self, set):
466 self._set = set
Raymond Hettingerfa1480f2002-08-24 02:35:48 +0000467 self._data = set._data # Needed by ImmutableSet.__eq__()
Guido van Rossumd6cf3af2002-08-19 16:19:15 +0000468
469 def __hash__(self):
Raymond Hettingerd5018512002-08-24 04:47:42 +0000470 return self._set._compute_hash()