set.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
  2. # Copyright (C) 2003-2017 Nominum, Inc.
  3. #
  4. # Permission to use, copy, modify, and distribute this software and its
  5. # documentation for any purpose with or without fee is hereby granted,
  6. # provided that the above copyright notice and this permission notice
  7. # appear in all copies.
  8. #
  9. # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
  10. # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
  12. # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  14. # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  15. # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. import itertools
  17. class Set:
  18. """A simple set class.
  19. This class was originally used to deal with python not having a set class, and
  20. originally the class used lists in its implementation. The ordered and indexable
  21. nature of RRsets and Rdatasets is unfortunately widely used in dnspython
  22. applications, so for backwards compatibility sets continue to be a custom class, now
  23. based on an ordered dictionary.
  24. """
  25. __slots__ = ["items"]
  26. def __init__(self, items=None):
  27. """Initialize the set.
  28. *items*, an iterable or ``None``, the initial set of items.
  29. """
  30. self.items = dict()
  31. if items is not None:
  32. for item in items:
  33. # This is safe for how we use set, but if other code
  34. # subclasses it could be a legitimate issue.
  35. self.add(item) # lgtm[py/init-calls-subclass]
  36. def __repr__(self):
  37. return f"dns.set.Set({repr(list(self.items.keys()))})" # pragma: no cover
  38. def add(self, item):
  39. """Add an item to the set."""
  40. if item not in self.items:
  41. self.items[item] = None
  42. def remove(self, item):
  43. """Remove an item from the set."""
  44. try:
  45. del self.items[item]
  46. except KeyError:
  47. raise ValueError
  48. def discard(self, item):
  49. """Remove an item from the set if present."""
  50. self.items.pop(item, None)
  51. def pop(self):
  52. """Remove an arbitrary item from the set."""
  53. (k, _) = self.items.popitem()
  54. return k
  55. def _clone(self) -> "Set":
  56. """Make a (shallow) copy of the set.
  57. There is a 'clone protocol' that subclasses of this class
  58. should use. To make a copy, first call your super's _clone()
  59. method, and use the object returned as the new instance. Then
  60. make shallow copies of the attributes defined in the subclass.
  61. This protocol allows us to write the set algorithms that
  62. return new instances (e.g. union) once, and keep using them in
  63. subclasses.
  64. """
  65. if hasattr(self, "_clone_class"):
  66. cls = self._clone_class # type: ignore
  67. else:
  68. cls = self.__class__
  69. obj = cls.__new__(cls)
  70. obj.items = dict()
  71. obj.items.update(self.items)
  72. return obj
  73. def __copy__(self):
  74. """Make a (shallow) copy of the set."""
  75. return self._clone()
  76. def copy(self):
  77. """Make a (shallow) copy of the set."""
  78. return self._clone()
  79. def union_update(self, other):
  80. """Update the set, adding any elements from other which are not
  81. already in the set.
  82. """
  83. if not isinstance(other, Set):
  84. raise ValueError("other must be a Set instance")
  85. if self is other: # lgtm[py/comparison-using-is]
  86. return
  87. for item in other.items:
  88. self.add(item)
  89. def intersection_update(self, other):
  90. """Update the set, removing any elements from other which are not
  91. in both sets.
  92. """
  93. if not isinstance(other, Set):
  94. raise ValueError("other must be a Set instance")
  95. if self is other: # lgtm[py/comparison-using-is]
  96. return
  97. # we make a copy of the list so that we can remove items from
  98. # the list without breaking the iterator.
  99. for item in list(self.items):
  100. if item not in other.items:
  101. del self.items[item]
  102. def difference_update(self, other):
  103. """Update the set, removing any elements from other which are in
  104. the set.
  105. """
  106. if not isinstance(other, Set):
  107. raise ValueError("other must be a Set instance")
  108. if self is other: # lgtm[py/comparison-using-is]
  109. self.items.clear()
  110. else:
  111. for item in other.items:
  112. self.discard(item)
  113. def symmetric_difference_update(self, other):
  114. """Update the set, retaining only elements unique to both sets."""
  115. if not isinstance(other, Set):
  116. raise ValueError("other must be a Set instance")
  117. if self is other: # lgtm[py/comparison-using-is]
  118. self.items.clear()
  119. else:
  120. overlap = self.intersection(other)
  121. self.union_update(other)
  122. self.difference_update(overlap)
  123. def union(self, other):
  124. """Return a new set which is the union of ``self`` and ``other``.
  125. Returns the same Set type as this set.
  126. """
  127. obj = self._clone()
  128. obj.union_update(other)
  129. return obj
  130. def intersection(self, other):
  131. """Return a new set which is the intersection of ``self`` and
  132. ``other``.
  133. Returns the same Set type as this set.
  134. """
  135. obj = self._clone()
  136. obj.intersection_update(other)
  137. return obj
  138. def difference(self, other):
  139. """Return a new set which ``self`` - ``other``, i.e. the items
  140. in ``self`` which are not also in ``other``.
  141. Returns the same Set type as this set.
  142. """
  143. obj = self._clone()
  144. obj.difference_update(other)
  145. return obj
  146. def symmetric_difference(self, other):
  147. """Return a new set which (``self`` - ``other``) | (``other``
  148. - ``self), ie: the items in either ``self`` or ``other`` which
  149. are not contained in their intersection.
  150. Returns the same Set type as this set.
  151. """
  152. obj = self._clone()
  153. obj.symmetric_difference_update(other)
  154. return obj
  155. def __or__(self, other):
  156. return self.union(other)
  157. def __and__(self, other):
  158. return self.intersection(other)
  159. def __add__(self, other):
  160. return self.union(other)
  161. def __sub__(self, other):
  162. return self.difference(other)
  163. def __xor__(self, other):
  164. return self.symmetric_difference(other)
  165. def __ior__(self, other):
  166. self.union_update(other)
  167. return self
  168. def __iand__(self, other):
  169. self.intersection_update(other)
  170. return self
  171. def __iadd__(self, other):
  172. self.union_update(other)
  173. return self
  174. def __isub__(self, other):
  175. self.difference_update(other)
  176. return self
  177. def __ixor__(self, other):
  178. self.symmetric_difference_update(other)
  179. return self
  180. def update(self, other):
  181. """Update the set, adding any elements from other which are not
  182. already in the set.
  183. *other*, the collection of items with which to update the set, which
  184. may be any iterable type.
  185. """
  186. for item in other:
  187. self.add(item)
  188. def clear(self):
  189. """Make the set empty."""
  190. self.items.clear()
  191. def __eq__(self, other):
  192. return self.items == other.items
  193. def __ne__(self, other):
  194. return not self.__eq__(other)
  195. def __len__(self):
  196. return len(self.items)
  197. def __iter__(self):
  198. return iter(self.items)
  199. def __getitem__(self, i):
  200. if isinstance(i, slice):
  201. return list(itertools.islice(self.items, i.start, i.stop, i.step))
  202. else:
  203. return next(itertools.islice(self.items, i, i + 1))
  204. def __delitem__(self, i):
  205. if isinstance(i, slice):
  206. for elt in list(self[i]):
  207. del self.items[elt]
  208. else:
  209. del self.items[self[i]]
  210. def issubset(self, other):
  211. """Is this set a subset of *other*?
  212. Returns a ``bool``.
  213. """
  214. if not isinstance(other, Set):
  215. raise ValueError("other must be a Set instance")
  216. for item in self.items:
  217. if item not in other.items:
  218. return False
  219. return True
  220. def issuperset(self, other):
  221. """Is this set a superset of *other*?
  222. Returns a ``bool``.
  223. """
  224. if not isinstance(other, Set):
  225. raise ValueError("other must be a Set instance")
  226. for item in other.items:
  227. if item not in self.items:
  228. return False
  229. return True
  230. def isdisjoint(self, other):
  231. if not isinstance(other, Set):
  232. raise ValueError("other must be a Set instance")
  233. for item in other.items:
  234. if item in self.items:
  235. return False
  236. return True