2002-08-19 13:19:15 -03:00
|
|
|
"""Classes to represent arbitrary sets (including sets of sets).
|
|
|
|
|
|
|
|
This module implements sets using dictionaries whose values are
|
|
|
|
ignored. The usual operations (union, intersection, deletion, etc.)
|
|
|
|
are provided as both methods and operators.
|
|
|
|
|
2002-08-20 17:05:23 -03:00
|
|
|
Important: sets are not sequences! While they support 'x in s',
|
|
|
|
'len(s)', and 'for x in s', none of those operations are unique for
|
|
|
|
sequences; for example, mappings support all three as well. The
|
|
|
|
characteristic operation for sequences is subscripting with small
|
|
|
|
integers: s[i], for i in range(len(s)). Sets don't support
|
|
|
|
subscripting at all. Also, sequences allow multiple occurrences and
|
|
|
|
their elements have a definite order; sets on the other hand don't
|
|
|
|
record multiple occurrences and don't remember the order of element
|
|
|
|
insertion (which is why they don't support s[i]).
|
|
|
|
|
2002-08-19 13:19:15 -03:00
|
|
|
The following classes are provided:
|
|
|
|
|
|
|
|
BaseSet -- All the operations common to both mutable and immutable
|
|
|
|
sets. This is an abstract class, not meant to be directly
|
|
|
|
instantiated.
|
|
|
|
|
|
|
|
Set -- Mutable sets, subclass of BaseSet; not hashable.
|
|
|
|
|
|
|
|
ImmutableSet -- Immutable sets, subclass of BaseSet; hashable.
|
|
|
|
An iterable argument is mandatory to create an ImmutableSet.
|
|
|
|
|
2003-06-26 15:49:28 -03:00
|
|
|
_TemporarilyImmutableSet -- A wrapper around a Set, hashable,
|
|
|
|
giving the same hash value as the immutable set equivalent
|
|
|
|
would have. Do not use this class directly.
|
2002-08-19 13:19:15 -03:00
|
|
|
|
|
|
|
Only hashable objects can be added to a Set. In particular, you cannot
|
|
|
|
really add a Set as an element to another Set; if you try, what is
|
2002-08-20 20:34:01 -03:00
|
|
|
actually added is an ImmutableSet built from it (it compares equal to
|
2002-08-19 13:19:15 -03:00
|
|
|
the one you tried adding).
|
|
|
|
|
|
|
|
When you ask if `x in y' where x is a Set and y is a Set or
|
|
|
|
ImmutableSet, x is wrapped into a _TemporarilyImmutableSet z, and
|
|
|
|
what's tested is actually `z in y'.
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
# Code history:
|
|
|
|
#
|
|
|
|
# - Greg V. Wilson wrote the first version, using a different approach
|
|
|
|
# to the mutable/immutable problem, and inheriting from dict.
|
|
|
|
#
|
|
|
|
# - Alex Martelli modified Greg's version to implement the current
|
|
|
|
# Set/ImmutableSet approach, and make the data an attribute.
|
|
|
|
#
|
|
|
|
# - Guido van Rossum rewrote much of the code, made some API changes,
|
|
|
|
# and cleaned up the docstrings.
|
2002-08-20 23:44:04 -03:00
|
|
|
#
|
Ouch. The test suite *really* needs work!!!!! There were several
superficial errors and one deep one that aren't currently caught. I'm
headed for bed after this checkin.
- Fixed several typos introduced by Raymond Hettinger (through
cut-n-paste from my template): it's _as_temporarily_immutable, not
_as_temporary_immutable, and moreover when the element is added, we
should use _as_immutable.
- Made the seq argument to ImmutableSet.__init__ optional, so we can
write ImmutableSet() to create an immutable empty set.
- Rename the seq argument to Set and ImmutableSet to iterable.
- Add a Set.__hash__ method that raises a TypeError. We inherit a
default __hash__ implementation from object, and we don't want that.
We can then catch this in update(), so that
e.g. s.update([Set([1])]) will transform the Set([1]) to
ImmutableSet([1]).
- Added the dance to catch TypeError and try _as_immutable in the
constructors too (by calling _update()). This is needed so that
Set([Set([1])]) is correctly interpreted as
Set([ImmutableSet([1])]). (I was puzzled by a side effect of this
and the inherited __hash__ when comparing two sets of sets while
testing different powerset implementations: the Set element passed
to a Set constructor wasn't transformed to an ImmutableSet, and then
the dictionary didn't believe the Set found in one dict it was the
same as ImmutableSet in the other, because the hashes were
different.)
- Refactored Set.update() and both __init__() methods; moved the body
of update() into BaseSet as _update(), and call this from __init__()
and update().
- Changed the NotImplementedError in BaseSet.__init__ to TypeError,
both for consistency with basestring() and because we have to use
TypeError when denying Set.__hash__. Together those provide
sufficient evidence that an unimplemented method needs to raise
TypeError.
2002-08-21 00:20:44 -03:00
|
|
|
# - Raymond Hettinger added a number of speedups and other
|
2002-08-22 14:23:33 -03:00
|
|
|
# improvements.
|
2002-08-19 13:19:15 -03:00
|
|
|
|
2003-08-15 18:17:04 -03:00
|
|
|
from __future__ import generators
|
|
|
|
try:
|
|
|
|
from itertools import ifilter, ifilterfalse
|
|
|
|
except ImportError:
|
|
|
|
# Code to make the module run under Py2.2
|
|
|
|
def ifilter(predicate, iterable):
|
|
|
|
if predicate is None:
|
|
|
|
def predicate(x):
|
|
|
|
return x
|
|
|
|
for x in iterable:
|
|
|
|
if predicate(x):
|
|
|
|
yield x
|
|
|
|
def ifilterfalse(predicate, iterable):
|
|
|
|
if predicate is None:
|
|
|
|
def predicate(x):
|
|
|
|
return x
|
|
|
|
for x in iterable:
|
|
|
|
if not predicate(x):
|
|
|
|
yield x
|
2003-11-12 11:21:20 -04:00
|
|
|
try:
|
|
|
|
True, False
|
|
|
|
except NameError:
|
|
|
|
True, False = (0==0, 0!=0)
|
2002-08-19 13:19:15 -03:00
|
|
|
|
|
|
|
__all__ = ['BaseSet', 'Set', 'ImmutableSet']
|
|
|
|
|
|
|
|
class BaseSet(object):
|
|
|
|
"""Common base class for mutable and immutable sets."""
|
|
|
|
|
|
|
|
__slots__ = ['_data']
|
|
|
|
|
|
|
|
# Constructor
|
|
|
|
|
2002-08-20 18:38:37 -03:00
|
|
|
def __init__(self):
|
|
|
|
"""This is an abstract class."""
|
|
|
|
# Don't call this from a concrete subclass!
|
|
|
|
if self.__class__ is BaseSet:
|
Ouch. The test suite *really* needs work!!!!! There were several
superficial errors and one deep one that aren't currently caught. I'm
headed for bed after this checkin.
- Fixed several typos introduced by Raymond Hettinger (through
cut-n-paste from my template): it's _as_temporarily_immutable, not
_as_temporary_immutable, and moreover when the element is added, we
should use _as_immutable.
- Made the seq argument to ImmutableSet.__init__ optional, so we can
write ImmutableSet() to create an immutable empty set.
- Rename the seq argument to Set and ImmutableSet to iterable.
- Add a Set.__hash__ method that raises a TypeError. We inherit a
default __hash__ implementation from object, and we don't want that.
We can then catch this in update(), so that
e.g. s.update([Set([1])]) will transform the Set([1]) to
ImmutableSet([1]).
- Added the dance to catch TypeError and try _as_immutable in the
constructors too (by calling _update()). This is needed so that
Set([Set([1])]) is correctly interpreted as
Set([ImmutableSet([1])]). (I was puzzled by a side effect of this
and the inherited __hash__ when comparing two sets of sets while
testing different powerset implementations: the Set element passed
to a Set constructor wasn't transformed to an ImmutableSet, and then
the dictionary didn't believe the Set found in one dict it was the
same as ImmutableSet in the other, because the hashes were
different.)
- Refactored Set.update() and both __init__() methods; moved the body
of update() into BaseSet as _update(), and call this from __init__()
and update().
- Changed the NotImplementedError in BaseSet.__init__ to TypeError,
both for consistency with basestring() and because we have to use
TypeError when denying Set.__hash__. Together those provide
sufficient evidence that an unimplemented method needs to raise
TypeError.
2002-08-21 00:20:44 -03:00
|
|
|
raise TypeError, ("BaseSet is an abstract class. "
|
|
|
|
"Use Set or ImmutableSet.")
|
2002-08-19 13:19:15 -03:00
|
|
|
|
|
|
|
# Standard protocols: __len__, __repr__, __str__, __iter__
|
|
|
|
|
|
|
|
def __len__(self):
|
|
|
|
"""Return the number of elements of a set."""
|
|
|
|
return len(self._data)
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
"""Return string representation of a set.
|
|
|
|
|
|
|
|
This looks like 'Set([<list of elements>])'.
|
|
|
|
"""
|
|
|
|
return self._repr()
|
|
|
|
|
|
|
|
# __str__ is the same as __repr__
|
|
|
|
__str__ = __repr__
|
|
|
|
|
|
|
|
def _repr(self, sorted=False):
|
|
|
|
elements = self._data.keys()
|
|
|
|
if sorted:
|
|
|
|
elements.sort()
|
|
|
|
return '%s(%r)' % (self.__class__.__name__, elements)
|
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
"""Return an iterator over the elements or a set.
|
|
|
|
|
|
|
|
This is the keys iterator for the underlying dict.
|
|
|
|
"""
|
|
|
|
return self._data.iterkeys()
|
|
|
|
|
2003-03-01 20:19:49 -04:00
|
|
|
# Three-way comparison is not supported. However, because __eq__ is
|
|
|
|
# tried before __cmp__, if Set x == Set y, x.__eq__(y) returns True and
|
|
|
|
# then cmp(x, y) returns 0 (Python doesn't actually call __cmp__ in this
|
|
|
|
# case).
|
2003-01-14 12:45:04 -04:00
|
|
|
|
|
|
|
def __cmp__(self, other):
|
|
|
|
raise TypeError, "can't compare sets using cmp()"
|
|
|
|
|
2003-03-01 20:19:49 -04:00
|
|
|
# Equality comparisons using the underlying dicts. Mixed-type comparisons
|
|
|
|
# are allowed here, where Set == z for non-Set z always returns False,
|
|
|
|
# and Set != z always True. This allows expressions like "x in y" to
|
|
|
|
# give the expected result when y is a sequence of mixed types, not
|
|
|
|
# raising a pointless TypeError just because y contains a Set, or x is
|
|
|
|
# a Set and y contain's a non-set ("in" invokes only __eq__).
|
|
|
|
# Subtle: it would be nicer if __eq__ and __ne__ could return
|
|
|
|
# NotImplemented instead of True or False. Then the other comparand
|
|
|
|
# would get a chance to determine the result, and if the other comparand
|
|
|
|
# also returned NotImplemented then it would fall back to object address
|
|
|
|
# comparison (which would always return False for __eq__ and always
|
|
|
|
# True for __ne__). However, that doesn't work, because this type
|
|
|
|
# *also* implements __cmp__: if, e.g., __eq__ returns NotImplemented,
|
|
|
|
# Python tries __cmp__ next, and the __cmp__ here then raises TypeError.
|
2002-08-19 13:19:15 -03:00
|
|
|
|
|
|
|
def __eq__(self, other):
|
2003-03-01 20:19:49 -04:00
|
|
|
if isinstance(other, BaseSet):
|
|
|
|
return self._data == other._data
|
|
|
|
else:
|
|
|
|
return False
|
2002-08-19 13:19:15 -03:00
|
|
|
|
|
|
|
def __ne__(self, other):
|
2003-03-01 20:19:49 -04:00
|
|
|
if isinstance(other, BaseSet):
|
|
|
|
return self._data != other._data
|
|
|
|
else:
|
|
|
|
return True
|
2002-08-19 13:19:15 -03:00
|
|
|
|
|
|
|
# Copying operations
|
|
|
|
|
|
|
|
def copy(self):
|
|
|
|
"""Return a shallow copy of a set."""
|
2002-08-23 23:35:48 -03:00
|
|
|
result = self.__class__()
|
2002-08-21 10:20:51 -03:00
|
|
|
result._data.update(self._data)
|
|
|
|
return result
|
2002-08-19 13:19:15 -03:00
|
|
|
|
|
|
|
__copy__ = copy # For the copy module
|
|
|
|
|
|
|
|
def __deepcopy__(self, memo):
|
|
|
|
"""Return a deep copy of a set; used by copy module."""
|
|
|
|
# This pre-creates the result and inserts it in the memo
|
|
|
|
# early, in case the deep copy recurses into another reference
|
|
|
|
# to this same set. A set can't be an element of itself, but
|
|
|
|
# it can certainly contain an object that has a reference to
|
|
|
|
# itself.
|
|
|
|
from copy import deepcopy
|
2002-08-23 23:35:48 -03:00
|
|
|
result = self.__class__()
|
2002-08-19 13:19:15 -03:00
|
|
|
memo[id(self)] = result
|
|
|
|
data = result._data
|
|
|
|
value = True
|
|
|
|
for elt in self:
|
|
|
|
data[deepcopy(elt, memo)] = value
|
|
|
|
return result
|
|
|
|
|
2002-08-22 14:23:33 -03:00
|
|
|
# Standard set operations: union, intersection, both differences.
|
|
|
|
# Each has an operator version (e.g. __or__, invoked with |) and a
|
|
|
|
# method version (e.g. union).
|
2002-08-25 14:10:17 -03:00
|
|
|
# Subtle: Each pair requires distinct code so that the outcome is
|
|
|
|
# correct when the type of other isn't suitable. For example, if
|
|
|
|
# we did "union = __or__" instead, then Set().union(3) would return
|
|
|
|
# NotImplemented instead of raising TypeError (albeit that *why* it
|
|
|
|
# raises TypeError as-is is also a bit subtle).
|
2002-08-19 13:19:15 -03:00
|
|
|
|
2002-08-22 14:23:33 -03:00
|
|
|
def __or__(self, other):
|
2002-08-19 13:19:15 -03:00
|
|
|
"""Return the union of two sets as a new set.
|
|
|
|
|
|
|
|
(I.e. all elements that are in either set.)
|
|
|
|
"""
|
2002-08-22 14:23:33 -03:00
|
|
|
if not isinstance(other, BaseSet):
|
|
|
|
return NotImplemented
|
2003-08-17 05:34:09 -03:00
|
|
|
return self.union(other)
|
2002-08-19 13:19:15 -03:00
|
|
|
|
2002-08-22 14:23:33 -03:00
|
|
|
def union(self, other):
|
|
|
|
"""Return the union of two sets as a new set.
|
2002-08-19 13:19:15 -03:00
|
|
|
|
2002-08-22 14:23:33 -03:00
|
|
|
(I.e. all elements that are in either set.)
|
|
|
|
"""
|
2003-08-17 05:34:09 -03:00
|
|
|
result = self.__class__(self)
|
|
|
|
result._update(other)
|
|
|
|
return result
|
2002-08-22 14:23:33 -03:00
|
|
|
|
|
|
|
def __and__(self, other):
|
2002-08-19 13:19:15 -03:00
|
|
|
"""Return the intersection of two sets as a new set.
|
|
|
|
|
|
|
|
(I.e. all elements that are in both sets.)
|
|
|
|
"""
|
2002-08-22 14:23:33 -03:00
|
|
|
if not isinstance(other, BaseSet):
|
|
|
|
return NotImplemented
|
2003-08-17 05:34:09 -03:00
|
|
|
return self.intersection(other)
|
2002-08-19 13:19:15 -03:00
|
|
|
|
2002-08-22 14:23:33 -03:00
|
|
|
def intersection(self, other):
|
|
|
|
"""Return the intersection of two sets as a new set.
|
2002-08-19 13:19:15 -03:00
|
|
|
|
2002-08-22 14:23:33 -03:00
|
|
|
(I.e. all elements that are in both sets.)
|
|
|
|
"""
|
2003-08-17 05:34:09 -03:00
|
|
|
if not isinstance(other, BaseSet):
|
|
|
|
other = Set(other)
|
|
|
|
if len(self) <= len(other):
|
|
|
|
little, big = self, other
|
|
|
|
else:
|
|
|
|
little, big = other, self
|
2006-08-18 19:13:04 -03:00
|
|
|
common = ifilter(big._data.__contains__, little)
|
2003-08-17 05:34:09 -03:00
|
|
|
return self.__class__(common)
|
2002-08-22 14:23:33 -03:00
|
|
|
|
|
|
|
def __xor__(self, other):
|
2002-08-19 13:19:15 -03:00
|
|
|
"""Return the symmetric difference of two sets as a new set.
|
|
|
|
|
|
|
|
(I.e. all elements that are in exactly one of the sets.)
|
|
|
|
"""
|
2002-08-22 14:23:33 -03:00
|
|
|
if not isinstance(other, BaseSet):
|
|
|
|
return NotImplemented
|
2003-08-17 05:34:09 -03:00
|
|
|
return self.symmetric_difference(other)
|
|
|
|
|
|
|
|
def symmetric_difference(self, other):
|
|
|
|
"""Return the symmetric difference of two sets as a new set.
|
|
|
|
|
|
|
|
(I.e. all elements that are in exactly one of the sets.)
|
|
|
|
"""
|
2002-08-23 23:35:48 -03:00
|
|
|
result = self.__class__()
|
2002-08-19 13:19:15 -03:00
|
|
|
data = result._data
|
|
|
|
value = True
|
2002-08-25 16:47:54 -03:00
|
|
|
selfdata = self._data
|
2003-08-17 05:34:09 -03:00
|
|
|
try:
|
|
|
|
otherdata = other._data
|
|
|
|
except AttributeError:
|
|
|
|
otherdata = Set(other)._data
|
2006-08-18 19:13:04 -03:00
|
|
|
for elt in ifilterfalse(otherdata.__contains__, selfdata):
|
2003-02-02 10:27:19 -04:00
|
|
|
data[elt] = value
|
2006-08-18 19:13:04 -03:00
|
|
|
for elt in ifilterfalse(selfdata.__contains__, otherdata):
|
2003-02-02 10:27:19 -04:00
|
|
|
data[elt] = value
|
2002-08-19 13:19:15 -03:00
|
|
|
return result
|
|
|
|
|
2002-08-22 14:23:33 -03:00
|
|
|
def __sub__(self, other):
|
2002-08-19 13:19:15 -03:00
|
|
|
"""Return the difference of two sets as a new Set.
|
|
|
|
|
|
|
|
(I.e. all elements that are in this set and not in the other.)
|
|
|
|
"""
|
2002-08-22 14:23:33 -03:00
|
|
|
if not isinstance(other, BaseSet):
|
|
|
|
return NotImplemented
|
2003-08-17 05:34:09 -03:00
|
|
|
return self.difference(other)
|
2002-08-19 13:19:15 -03:00
|
|
|
|
2002-08-22 14:23:33 -03:00
|
|
|
def difference(self, other):
|
|
|
|
"""Return the difference of two sets as a new Set.
|
|
|
|
|
|
|
|
(I.e. all elements that are in this set and not in the other.)
|
|
|
|
"""
|
2003-08-17 05:34:09 -03:00
|
|
|
result = self.__class__()
|
|
|
|
data = result._data
|
|
|
|
try:
|
|
|
|
otherdata = other._data
|
|
|
|
except AttributeError:
|
|
|
|
otherdata = Set(other)._data
|
|
|
|
value = True
|
2006-08-18 19:13:04 -03:00
|
|
|
for elt in ifilterfalse(otherdata.__contains__, self):
|
2003-08-17 05:34:09 -03:00
|
|
|
data[elt] = value
|
|
|
|
return result
|
2002-08-19 13:19:15 -03:00
|
|
|
|
|
|
|
# Membership test
|
|
|
|
|
|
|
|
def __contains__(self, element):
|
|
|
|
"""Report whether an element is a member of a set.
|
|
|
|
|
|
|
|
(Called in response to the expression `element in self'.)
|
|
|
|
"""
|
|
|
|
try:
|
2002-08-20 22:35:29 -03:00
|
|
|
return element in self._data
|
|
|
|
except TypeError:
|
2003-02-13 23:42:11 -04:00
|
|
|
transform = getattr(element, "__as_temporarily_immutable__", None)
|
2002-08-20 22:35:29 -03:00
|
|
|
if transform is None:
|
|
|
|
raise # re-raise the TypeError exception we caught
|
|
|
|
return transform() in self._data
|
2002-08-19 13:19:15 -03:00
|
|
|
|
|
|
|
# Subset and superset test
|
|
|
|
|
|
|
|
def issubset(self, other):
|
|
|
|
"""Report whether another set contains this set."""
|
|
|
|
self._binary_sanity_check(other)
|
2002-08-20 23:22:08 -03:00
|
|
|
if len(self) > len(other): # Fast check for obvious cases
|
|
|
|
return False
|
2006-08-18 19:13:04 -03:00
|
|
|
for elt in ifilterfalse(other._data.__contains__, self):
|
2003-02-02 10:27:19 -04:00
|
|
|
return False
|
2002-08-19 13:19:15 -03:00
|
|
|
return True
|
|
|
|
|
|
|
|
def issuperset(self, other):
|
|
|
|
"""Report whether this set contains another set."""
|
|
|
|
self._binary_sanity_check(other)
|
2002-08-20 23:22:08 -03:00
|
|
|
if len(self) < len(other): # Fast check for obvious cases
|
|
|
|
return False
|
2006-08-18 19:13:04 -03:00
|
|
|
for elt in ifilterfalse(self._data.__contains__, other):
|
2003-02-03 20:38:20 -04:00
|
|
|
return False
|
2002-08-19 13:19:15 -03:00
|
|
|
return True
|
|
|
|
|
2002-08-25 15:43:10 -03:00
|
|
|
# Inequality comparisons using the is-subset relation.
|
|
|
|
__le__ = issubset
|
|
|
|
__ge__ = issuperset
|
|
|
|
|
|
|
|
def __lt__(self, other):
|
|
|
|
self._binary_sanity_check(other)
|
|
|
|
return len(self) < len(other) and self.issubset(other)
|
|
|
|
|
|
|
|
def __gt__(self, other):
|
|
|
|
self._binary_sanity_check(other)
|
|
|
|
return len(self) > len(other) and self.issuperset(other)
|
|
|
|
|
2002-08-19 13:19:15 -03:00
|
|
|
# Assorted helpers
|
|
|
|
|
|
|
|
def _binary_sanity_check(self, other):
|
|
|
|
# Check that the other argument to a binary operation is also
|
|
|
|
# a set, raising a TypeError otherwise.
|
|
|
|
if not isinstance(other, BaseSet):
|
|
|
|
raise TypeError, "Binary operation only permitted between sets"
|
|
|
|
|
|
|
|
def _compute_hash(self):
|
|
|
|
# Calculate hash code for a set by xor'ing the hash codes of
|
2002-08-23 17:06:42 -03:00
|
|
|
# the elements. This ensures that the hash code does not depend
|
|
|
|
# on the order in which elements are added to the set. This is
|
|
|
|
# not called __hash__ because a BaseSet should not be hashable;
|
|
|
|
# only an ImmutableSet is hashable.
|
2002-08-19 13:19:15 -03:00
|
|
|
result = 0
|
|
|
|
for elt in self:
|
|
|
|
result ^= hash(elt)
|
|
|
|
return result
|
|
|
|
|
Ouch. The test suite *really* needs work!!!!! There were several
superficial errors and one deep one that aren't currently caught. I'm
headed for bed after this checkin.
- Fixed several typos introduced by Raymond Hettinger (through
cut-n-paste from my template): it's _as_temporarily_immutable, not
_as_temporary_immutable, and moreover when the element is added, we
should use _as_immutable.
- Made the seq argument to ImmutableSet.__init__ optional, so we can
write ImmutableSet() to create an immutable empty set.
- Rename the seq argument to Set and ImmutableSet to iterable.
- Add a Set.__hash__ method that raises a TypeError. We inherit a
default __hash__ implementation from object, and we don't want that.
We can then catch this in update(), so that
e.g. s.update([Set([1])]) will transform the Set([1]) to
ImmutableSet([1]).
- Added the dance to catch TypeError and try _as_immutable in the
constructors too (by calling _update()). This is needed so that
Set([Set([1])]) is correctly interpreted as
Set([ImmutableSet([1])]). (I was puzzled by a side effect of this
and the inherited __hash__ when comparing two sets of sets while
testing different powerset implementations: the Set element passed
to a Set constructor wasn't transformed to an ImmutableSet, and then
the dictionary didn't believe the Set found in one dict it was the
same as ImmutableSet in the other, because the hashes were
different.)
- Refactored Set.update() and both __init__() methods; moved the body
of update() into BaseSet as _update(), and call this from __init__()
and update().
- Changed the NotImplementedError in BaseSet.__init__ to TypeError,
both for consistency with basestring() and because we have to use
TypeError when denying Set.__hash__. Together those provide
sufficient evidence that an unimplemented method needs to raise
TypeError.
2002-08-21 00:20:44 -03:00
|
|
|
def _update(self, iterable):
|
|
|
|
# The main loop for update() and the subclass __init__() methods.
|
|
|
|
data = self._data
|
2002-08-29 12:13:50 -03:00
|
|
|
|
|
|
|
# Use the fast update() method when a dictionary is available.
|
|
|
|
if isinstance(iterable, BaseSet):
|
|
|
|
data.update(iterable._data)
|
|
|
|
return
|
|
|
|
|
2002-11-08 01:26:52 -04:00
|
|
|
value = True
|
2002-11-08 13:03:36 -04:00
|
|
|
|
|
|
|
if type(iterable) in (list, tuple, xrange):
|
|
|
|
# Optimized: we know that __iter__() and next() can't
|
|
|
|
# raise TypeError, so we can move 'try:' out of the loop.
|
|
|
|
it = iter(iterable)
|
|
|
|
while True:
|
|
|
|
try:
|
|
|
|
for element in it:
|
|
|
|
data[element] = value
|
|
|
|
return
|
|
|
|
except TypeError:
|
2003-02-13 23:42:11 -04:00
|
|
|
transform = getattr(element, "__as_immutable__", None)
|
2002-11-08 13:03:36 -04:00
|
|
|
if transform is None:
|
|
|
|
raise # re-raise the TypeError exception we caught
|
|
|
|
data[transform()] = value
|
|
|
|
else:
|
|
|
|
# Safe: only catch TypeError where intended
|
|
|
|
for element in iterable:
|
|
|
|
try:
|
2002-08-21 01:12:03 -03:00
|
|
|
data[element] = value
|
2002-11-08 13:03:36 -04:00
|
|
|
except TypeError:
|
2003-02-13 23:42:11 -04:00
|
|
|
transform = getattr(element, "__as_immutable__", None)
|
2002-11-08 13:03:36 -04:00
|
|
|
if transform is None:
|
|
|
|
raise # re-raise the TypeError exception we caught
|
|
|
|
data[transform()] = value
|
Ouch. The test suite *really* needs work!!!!! There were several
superficial errors and one deep one that aren't currently caught. I'm
headed for bed after this checkin.
- Fixed several typos introduced by Raymond Hettinger (through
cut-n-paste from my template): it's _as_temporarily_immutable, not
_as_temporary_immutable, and moreover when the element is added, we
should use _as_immutable.
- Made the seq argument to ImmutableSet.__init__ optional, so we can
write ImmutableSet() to create an immutable empty set.
- Rename the seq argument to Set and ImmutableSet to iterable.
- Add a Set.__hash__ method that raises a TypeError. We inherit a
default __hash__ implementation from object, and we don't want that.
We can then catch this in update(), so that
e.g. s.update([Set([1])]) will transform the Set([1]) to
ImmutableSet([1]).
- Added the dance to catch TypeError and try _as_immutable in the
constructors too (by calling _update()). This is needed so that
Set([Set([1])]) is correctly interpreted as
Set([ImmutableSet([1])]). (I was puzzled by a side effect of this
and the inherited __hash__ when comparing two sets of sets while
testing different powerset implementations: the Set element passed
to a Set constructor wasn't transformed to an ImmutableSet, and then
the dictionary didn't believe the Set found in one dict it was the
same as ImmutableSet in the other, because the hashes were
different.)
- Refactored Set.update() and both __init__() methods; moved the body
of update() into BaseSet as _update(), and call this from __init__()
and update().
- Changed the NotImplementedError in BaseSet.__init__ to TypeError,
both for consistency with basestring() and because we have to use
TypeError when denying Set.__hash__. Together those provide
sufficient evidence that an unimplemented method needs to raise
TypeError.
2002-08-21 00:20:44 -03:00
|
|
|
|
2002-08-19 13:19:15 -03:00
|
|
|
|
|
|
|
class ImmutableSet(BaseSet):
|
|
|
|
"""Immutable set class."""
|
|
|
|
|
2002-08-19 13:29:58 -03:00
|
|
|
__slots__ = ['_hashcode']
|
2002-08-19 13:19:15 -03:00
|
|
|
|
|
|
|
# BaseSet + hashing
|
|
|
|
|
Ouch. The test suite *really* needs work!!!!! There were several
superficial errors and one deep one that aren't currently caught. I'm
headed for bed after this checkin.
- Fixed several typos introduced by Raymond Hettinger (through
cut-n-paste from my template): it's _as_temporarily_immutable, not
_as_temporary_immutable, and moreover when the element is added, we
should use _as_immutable.
- Made the seq argument to ImmutableSet.__init__ optional, so we can
write ImmutableSet() to create an immutable empty set.
- Rename the seq argument to Set and ImmutableSet to iterable.
- Add a Set.__hash__ method that raises a TypeError. We inherit a
default __hash__ implementation from object, and we don't want that.
We can then catch this in update(), so that
e.g. s.update([Set([1])]) will transform the Set([1]) to
ImmutableSet([1]).
- Added the dance to catch TypeError and try _as_immutable in the
constructors too (by calling _update()). This is needed so that
Set([Set([1])]) is correctly interpreted as
Set([ImmutableSet([1])]). (I was puzzled by a side effect of this
and the inherited __hash__ when comparing two sets of sets while
testing different powerset implementations: the Set element passed
to a Set constructor wasn't transformed to an ImmutableSet, and then
the dictionary didn't believe the Set found in one dict it was the
same as ImmutableSet in the other, because the hashes were
different.)
- Refactored Set.update() and both __init__() methods; moved the body
of update() into BaseSet as _update(), and call this from __init__()
and update().
- Changed the NotImplementedError in BaseSet.__init__ to TypeError,
both for consistency with basestring() and because we have to use
TypeError when denying Set.__hash__. Together those provide
sufficient evidence that an unimplemented method needs to raise
TypeError.
2002-08-21 00:20:44 -03:00
|
|
|
def __init__(self, iterable=None):
|
|
|
|
"""Construct an immutable set from an optional iterable."""
|
2002-08-19 13:19:15 -03:00
|
|
|
self._hashcode = None
|
Ouch. The test suite *really* needs work!!!!! There were several
superficial errors and one deep one that aren't currently caught. I'm
headed for bed after this checkin.
- Fixed several typos introduced by Raymond Hettinger (through
cut-n-paste from my template): it's _as_temporarily_immutable, not
_as_temporary_immutable, and moreover when the element is added, we
should use _as_immutable.
- Made the seq argument to ImmutableSet.__init__ optional, so we can
write ImmutableSet() to create an immutable empty set.
- Rename the seq argument to Set and ImmutableSet to iterable.
- Add a Set.__hash__ method that raises a TypeError. We inherit a
default __hash__ implementation from object, and we don't want that.
We can then catch this in update(), so that
e.g. s.update([Set([1])]) will transform the Set([1]) to
ImmutableSet([1]).
- Added the dance to catch TypeError and try _as_immutable in the
constructors too (by calling _update()). This is needed so that
Set([Set([1])]) is correctly interpreted as
Set([ImmutableSet([1])]). (I was puzzled by a side effect of this
and the inherited __hash__ when comparing two sets of sets while
testing different powerset implementations: the Set element passed
to a Set constructor wasn't transformed to an ImmutableSet, and then
the dictionary didn't believe the Set found in one dict it was the
same as ImmutableSet in the other, because the hashes were
different.)
- Refactored Set.update() and both __init__() methods; moved the body
of update() into BaseSet as _update(), and call this from __init__()
and update().
- Changed the NotImplementedError in BaseSet.__init__ to TypeError,
both for consistency with basestring() and because we have to use
TypeError when denying Set.__hash__. Together those provide
sufficient evidence that an unimplemented method needs to raise
TypeError.
2002-08-21 00:20:44 -03:00
|
|
|
self._data = {}
|
|
|
|
if iterable is not None:
|
|
|
|
self._update(iterable)
|
2002-08-19 13:19:15 -03:00
|
|
|
|
|
|
|
def __hash__(self):
|
|
|
|
if self._hashcode is None:
|
|
|
|
self._hashcode = self._compute_hash()
|
|
|
|
return self._hashcode
|
|
|
|
|
2002-11-13 15:34:26 -04:00
|
|
|
def __getstate__(self):
|
|
|
|
return self._data, self._hashcode
|
|
|
|
|
|
|
|
def __setstate__(self, state):
|
|
|
|
self._data, self._hashcode = state
|
2002-08-19 13:19:15 -03:00
|
|
|
|
|
|
|
class Set(BaseSet):
|
|
|
|
""" Mutable set class."""
|
|
|
|
|
|
|
|
__slots__ = []
|
|
|
|
|
|
|
|
# BaseSet + operations requiring mutability; no hashing
|
|
|
|
|
Ouch. The test suite *really* needs work!!!!! There were several
superficial errors and one deep one that aren't currently caught. I'm
headed for bed after this checkin.
- Fixed several typos introduced by Raymond Hettinger (through
cut-n-paste from my template): it's _as_temporarily_immutable, not
_as_temporary_immutable, and moreover when the element is added, we
should use _as_immutable.
- Made the seq argument to ImmutableSet.__init__ optional, so we can
write ImmutableSet() to create an immutable empty set.
- Rename the seq argument to Set and ImmutableSet to iterable.
- Add a Set.__hash__ method that raises a TypeError. We inherit a
default __hash__ implementation from object, and we don't want that.
We can then catch this in update(), so that
e.g. s.update([Set([1])]) will transform the Set([1]) to
ImmutableSet([1]).
- Added the dance to catch TypeError and try _as_immutable in the
constructors too (by calling _update()). This is needed so that
Set([Set([1])]) is correctly interpreted as
Set([ImmutableSet([1])]). (I was puzzled by a side effect of this
and the inherited __hash__ when comparing two sets of sets while
testing different powerset implementations: the Set element passed
to a Set constructor wasn't transformed to an ImmutableSet, and then
the dictionary didn't believe the Set found in one dict it was the
same as ImmutableSet in the other, because the hashes were
different.)
- Refactored Set.update() and both __init__() methods; moved the body
of update() into BaseSet as _update(), and call this from __init__()
and update().
- Changed the NotImplementedError in BaseSet.__init__ to TypeError,
both for consistency with basestring() and because we have to use
TypeError when denying Set.__hash__. Together those provide
sufficient evidence that an unimplemented method needs to raise
TypeError.
2002-08-21 00:20:44 -03:00
|
|
|
def __init__(self, iterable=None):
|
|
|
|
"""Construct a set from an optional iterable."""
|
|
|
|
self._data = {}
|
|
|
|
if iterable is not None:
|
|
|
|
self._update(iterable)
|
|
|
|
|
2002-11-13 15:34:26 -04:00
|
|
|
def __getstate__(self):
|
|
|
|
# getstate's results are ignored if it is not
|
|
|
|
return self._data,
|
|
|
|
|
|
|
|
def __setstate__(self, data):
|
|
|
|
self._data, = data
|
|
|
|
|
Ouch. The test suite *really* needs work!!!!! There were several
superficial errors and one deep one that aren't currently caught. I'm
headed for bed after this checkin.
- Fixed several typos introduced by Raymond Hettinger (through
cut-n-paste from my template): it's _as_temporarily_immutable, not
_as_temporary_immutable, and moreover when the element is added, we
should use _as_immutable.
- Made the seq argument to ImmutableSet.__init__ optional, so we can
write ImmutableSet() to create an immutable empty set.
- Rename the seq argument to Set and ImmutableSet to iterable.
- Add a Set.__hash__ method that raises a TypeError. We inherit a
default __hash__ implementation from object, and we don't want that.
We can then catch this in update(), so that
e.g. s.update([Set([1])]) will transform the Set([1]) to
ImmutableSet([1]).
- Added the dance to catch TypeError and try _as_immutable in the
constructors too (by calling _update()). This is needed so that
Set([Set([1])]) is correctly interpreted as
Set([ImmutableSet([1])]). (I was puzzled by a side effect of this
and the inherited __hash__ when comparing two sets of sets while
testing different powerset implementations: the Set element passed
to a Set constructor wasn't transformed to an ImmutableSet, and then
the dictionary didn't believe the Set found in one dict it was the
same as ImmutableSet in the other, because the hashes were
different.)
- Refactored Set.update() and both __init__() methods; moved the body
of update() into BaseSet as _update(), and call this from __init__()
and update().
- Changed the NotImplementedError in BaseSet.__init__ to TypeError,
both for consistency with basestring() and because we have to use
TypeError when denying Set.__hash__. Together those provide
sufficient evidence that an unimplemented method needs to raise
TypeError.
2002-08-21 00:20:44 -03:00
|
|
|
def __hash__(self):
|
|
|
|
"""A Set cannot be hashed."""
|
|
|
|
# We inherit object.__hash__, so we must deny this explicitly
|
|
|
|
raise TypeError, "Can't hash a Set, only an ImmutableSet."
|
2002-08-20 18:38:37 -03:00
|
|
|
|
2002-08-25 15:59:04 -03:00
|
|
|
# In-place union, intersection, differences.
|
|
|
|
# Subtle: The xyz_update() functions deliberately return None,
|
|
|
|
# as do all mutating operations on built-in container types.
|
|
|
|
# The __xyz__ spellings have to return self, though.
|
2002-08-19 13:19:15 -03:00
|
|
|
|
2002-08-24 03:19:02 -03:00
|
|
|
def __ior__(self, other):
|
2002-08-19 13:19:15 -03:00
|
|
|
"""Update a set with the union of itself and another."""
|
|
|
|
self._binary_sanity_check(other)
|
|
|
|
self._data.update(other._data)
|
|
|
|
return self
|
|
|
|
|
2002-08-24 03:19:02 -03:00
|
|
|
def union_update(self, other):
|
|
|
|
"""Update a set with the union of itself and another."""
|
2003-08-17 05:34:09 -03:00
|
|
|
self._update(other)
|
2002-08-19 13:19:15 -03:00
|
|
|
|
2002-08-24 03:19:02 -03:00
|
|
|
def __iand__(self, other):
|
2002-08-19 13:19:15 -03:00
|
|
|
"""Update a set with the intersection of itself and another."""
|
|
|
|
self._binary_sanity_check(other)
|
2002-08-25 21:44:07 -03:00
|
|
|
self._data = (self & other)._data
|
2002-08-19 13:19:15 -03:00
|
|
|
return self
|
|
|
|
|
2002-08-24 03:19:02 -03:00
|
|
|
def intersection_update(self, other):
|
|
|
|
"""Update a set with the intersection of itself and another."""
|
2003-08-17 05:34:09 -03:00
|
|
|
if isinstance(other, BaseSet):
|
|
|
|
self &= other
|
|
|
|
else:
|
|
|
|
self._data = (self.intersection(other))._data
|
2002-08-19 13:19:15 -03:00
|
|
|
|
2002-08-24 03:19:02 -03:00
|
|
|
def __ixor__(self, other):
|
2002-08-19 13:19:15 -03:00
|
|
|
"""Update a set with the symmetric difference of itself and another."""
|
|
|
|
self._binary_sanity_check(other)
|
2003-08-17 05:34:09 -03:00
|
|
|
self.symmetric_difference_update(other)
|
|
|
|
return self
|
|
|
|
|
|
|
|
def symmetric_difference_update(self, other):
|
|
|
|
"""Update a set with the symmetric difference of itself and another."""
|
2002-08-19 13:19:15 -03:00
|
|
|
data = self._data
|
|
|
|
value = True
|
2003-08-17 05:34:09 -03:00
|
|
|
if not isinstance(other, BaseSet):
|
|
|
|
other = Set(other)
|
2005-08-12 23:29:58 -03:00
|
|
|
if self is other:
|
|
|
|
self.clear()
|
2002-08-19 13:19:15 -03:00
|
|
|
for elt in other:
|
|
|
|
if elt in data:
|
|
|
|
del data[elt]
|
|
|
|
else:
|
|
|
|
data[elt] = value
|
|
|
|
|
2002-08-24 03:19:02 -03:00
|
|
|
def __isub__(self, other):
|
2002-08-19 13:19:15 -03:00
|
|
|
"""Remove all elements of another set from this set."""
|
|
|
|
self._binary_sanity_check(other)
|
2003-08-17 05:34:09 -03:00
|
|
|
self.difference_update(other)
|
2002-08-19 13:19:15 -03:00
|
|
|
return self
|
|
|
|
|
2002-08-24 03:19:02 -03:00
|
|
|
def difference_update(self, other):
|
|
|
|
"""Remove all elements of another set from this set."""
|
2003-08-17 05:34:09 -03:00
|
|
|
data = self._data
|
|
|
|
if not isinstance(other, BaseSet):
|
|
|
|
other = Set(other)
|
2005-08-12 23:29:58 -03:00
|
|
|
if self is other:
|
|
|
|
self.clear()
|
2006-08-18 19:13:04 -03:00
|
|
|
for elt in ifilter(data.__contains__, other):
|
2003-08-17 05:34:09 -03:00
|
|
|
del data[elt]
|
2002-08-19 13:19:15 -03:00
|
|
|
|
|
|
|
# Python dict-like mass mutations: update, clear
|
|
|
|
|
|
|
|
def update(self, iterable):
|
|
|
|
"""Add all values from an iterable (such as a list or file)."""
|
Ouch. The test suite *really* needs work!!!!! There were several
superficial errors and one deep one that aren't currently caught. I'm
headed for bed after this checkin.
- Fixed several typos introduced by Raymond Hettinger (through
cut-n-paste from my template): it's _as_temporarily_immutable, not
_as_temporary_immutable, and moreover when the element is added, we
should use _as_immutable.
- Made the seq argument to ImmutableSet.__init__ optional, so we can
write ImmutableSet() to create an immutable empty set.
- Rename the seq argument to Set and ImmutableSet to iterable.
- Add a Set.__hash__ method that raises a TypeError. We inherit a
default __hash__ implementation from object, and we don't want that.
We can then catch this in update(), so that
e.g. s.update([Set([1])]) will transform the Set([1]) to
ImmutableSet([1]).
- Added the dance to catch TypeError and try _as_immutable in the
constructors too (by calling _update()). This is needed so that
Set([Set([1])]) is correctly interpreted as
Set([ImmutableSet([1])]). (I was puzzled by a side effect of this
and the inherited __hash__ when comparing two sets of sets while
testing different powerset implementations: the Set element passed
to a Set constructor wasn't transformed to an ImmutableSet, and then
the dictionary didn't believe the Set found in one dict it was the
same as ImmutableSet in the other, because the hashes were
different.)
- Refactored Set.update() and both __init__() methods; moved the body
of update() into BaseSet as _update(), and call this from __init__()
and update().
- Changed the NotImplementedError in BaseSet.__init__ to TypeError,
both for consistency with basestring() and because we have to use
TypeError when denying Set.__hash__. Together those provide
sufficient evidence that an unimplemented method needs to raise
TypeError.
2002-08-21 00:20:44 -03:00
|
|
|
self._update(iterable)
|
2002-08-19 13:19:15 -03:00
|
|
|
|
|
|
|
def clear(self):
|
|
|
|
"""Remove all elements from this set."""
|
|
|
|
self._data.clear()
|
|
|
|
|
|
|
|
# Single-element mutations: add, remove, discard
|
|
|
|
|
|
|
|
def add(self, element):
|
|
|
|
"""Add an element to a set.
|
|
|
|
|
|
|
|
This has no effect if the element is already present.
|
|
|
|
"""
|
|
|
|
try:
|
2002-08-20 22:35:29 -03:00
|
|
|
self._data[element] = True
|
|
|
|
except TypeError:
|
2003-02-13 23:42:11 -04:00
|
|
|
transform = getattr(element, "__as_immutable__", None)
|
2002-08-20 22:35:29 -03:00
|
|
|
if transform is None:
|
|
|
|
raise # re-raise the TypeError exception we caught
|
|
|
|
self._data[transform()] = True
|
2002-08-19 13:19:15 -03:00
|
|
|
|
|
|
|
def remove(self, element):
|
|
|
|
"""Remove an element from a set; it must be a member.
|
|
|
|
|
|
|
|
If the element is not a member, raise a KeyError.
|
|
|
|
"""
|
|
|
|
try:
|
2002-08-20 22:35:29 -03:00
|
|
|
del self._data[element]
|
|
|
|
except TypeError:
|
2003-02-13 23:42:11 -04:00
|
|
|
transform = getattr(element, "__as_temporarily_immutable__", None)
|
2002-08-20 22:35:29 -03:00
|
|
|
if transform is None:
|
|
|
|
raise # re-raise the TypeError exception we caught
|
|
|
|
del self._data[transform()]
|
2002-08-19 13:19:15 -03:00
|
|
|
|
|
|
|
def discard(self, element):
|
|
|
|
"""Remove an element from a set if it is a member.
|
|
|
|
|
|
|
|
If the element is not a member, do nothing.
|
|
|
|
"""
|
|
|
|
try:
|
2002-08-23 11:45:02 -03:00
|
|
|
self.remove(element)
|
2002-08-19 13:19:15 -03:00
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
|
2002-08-20 18:51:59 -03:00
|
|
|
def pop(self):
|
2002-08-23 17:36:58 -03:00
|
|
|
"""Remove and return an arbitrary set element."""
|
2002-08-19 13:19:15 -03:00
|
|
|
return self._data.popitem()[0]
|
|
|
|
|
2003-02-13 23:42:11 -04:00
|
|
|
def __as_immutable__(self):
|
2002-08-19 13:19:15 -03:00
|
|
|
# Return a copy of self as an immutable set
|
|
|
|
return ImmutableSet(self)
|
|
|
|
|
2003-02-13 23:42:11 -04:00
|
|
|
def __as_temporarily_immutable__(self):
|
2002-08-19 13:19:15 -03:00
|
|
|
# Return self wrapped in a temporarily immutable set
|
|
|
|
return _TemporarilyImmutableSet(self)
|
|
|
|
|
|
|
|
|
2002-08-23 23:35:48 -03:00
|
|
|
class _TemporarilyImmutableSet(BaseSet):
|
2002-08-19 13:19:15 -03:00
|
|
|
# Wrap a mutable set as if it was temporarily immutable.
|
|
|
|
# This only supplies hashing and equality comparisons.
|
|
|
|
|
|
|
|
def __init__(self, set):
|
|
|
|
self._set = set
|
2002-08-23 23:35:48 -03:00
|
|
|
self._data = set._data # Needed by ImmutableSet.__eq__()
|
2002-08-19 13:19:15 -03:00
|
|
|
|
|
|
|
def __hash__(self):
|
2002-08-24 01:47:42 -03:00
|
|
|
return self._set._compute_hash()
|