sets.py 19 KB

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