summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--Doc/Makefile.deps1
-rw-r--r--Doc/lib/lib.tex1
-rw-r--r--Doc/lib/libsets.tex264
-rw-r--r--Doc/lib/libstdtypes.tex10
-rw-r--r--Lib/msilib/__init__.py10
-rw-r--r--Lib/sets.py577
-rw-r--r--Lib/test/test_cookielib.py1
-rw-r--r--Lib/test/test_set.py1
-rw-r--r--Lib/test/test_sets.py853
9 files changed, 5 insertions, 1713 deletions
diff --git a/Doc/Makefile.deps b/Doc/Makefile.deps
index f828e1b..3371f61 100644
--- a/Doc/Makefile.deps
+++ b/Doc/Makefile.deps
@@ -109,7 +109,6 @@ LIBFILES= $(MANSTYLES) $(INDEXSTYLES) $(COMMONTEX) \
lib/libplatform.tex \
lib/libfpectl.tex \
lib/libgc.tex \
- lib/libsets.tex \
lib/libweakref.tex \
lib/libinspect.tex \
lib/libpydoc.tex \
diff --git a/Doc/lib/lib.tex b/Doc/lib/lib.tex
index 837c759..427d71d 100644
--- a/Doc/lib/lib.tex
+++ b/Doc/lib/lib.tex
@@ -104,7 +104,6 @@ and how to embed it in other applications.
\input{libheapq}
\input{libbisect}
\input{libarray}
-\input{libsets}
\input{libsched}
\input{libmutex}
\input{libqueue}
diff --git a/Doc/lib/libsets.tex b/Doc/lib/libsets.tex
index 22bf34b..e69de29 100644
--- a/Doc/lib/libsets.tex
+++ b/Doc/lib/libsets.tex
@@ -1,264 +0,0 @@
-\section{\module{sets} ---
- Unordered collections of unique elements}
-
-\declaremodule{standard}{sets}
-\modulesynopsis{Implementation of sets of unique elements.}
-\moduleauthor{Greg V. Wilson}{gvwilson@nevex.com}
-\moduleauthor{Alex Martelli}{aleax@aleax.it}
-\moduleauthor{Guido van Rossum}{guido@python.org}
-\sectionauthor{Raymond D. Hettinger}{python@rcn.com}
-
-\versionadded{2.3}
-
-The \module{sets} module provides classes for constructing and manipulating
-unordered collections of unique elements. Common uses include membership
-testing, removing duplicates from a sequence, and computing standard math
-operations on sets such as intersection, union, difference, and symmetric
-difference.
-
-Like other collections, sets support \code{\var{x} in \var{set}},
-\code{len(\var{set})}, and \code{for \var{x} in \var{set}}. Being an
-unordered collection, sets do not record element position or order of
-insertion. Accordingly, sets do not support indexing, slicing, or
-other sequence-like behavior.
-
-Most set applications use the \class{Set} class which provides every set
-method except for \method{__hash__()}. For advanced applications requiring
-a hash method, the \class{ImmutableSet} class adds a \method{__hash__()}
-method but omits methods which alter the contents of the set. Both
-\class{Set} and \class{ImmutableSet} derive from \class{BaseSet}, an
-abstract class useful for determining whether something is a set:
-\code{isinstance(\var{obj}, BaseSet)}.
-
-The set classes are implemented using dictionaries. Accordingly, the
-requirements for set elements are the same as those for dictionary keys;
-namely, that the element defines both \method{__eq__} and \method{__hash__}.
-As a result, sets
-cannot contain mutable elements such as lists or dictionaries.
-However, they can contain immutable collections such as tuples or
-instances of \class{ImmutableSet}. For convenience in implementing
-sets of sets, inner sets are automatically converted to immutable
-form, for example, \code{Set([Set(['dog'])])} is transformed to
-\code{Set([ImmutableSet(['dog'])])}.
-
-\begin{classdesc}{Set}{\optional{iterable}}
-Constructs a new empty \class{Set} object. If the optional \var{iterable}
-parameter is supplied, updates the set with elements obtained from iteration.
-All of the elements in \var{iterable} should be immutable or be transformable
-to an immutable using the protocol described in
-section~\ref{immutable-transforms}.
-\end{classdesc}
-
-\begin{classdesc}{ImmutableSet}{\optional{iterable}}
-Constructs a new empty \class{ImmutableSet} object. If the optional
-\var{iterable} parameter is supplied, updates the set with elements obtained
-from iteration. All of the elements in \var{iterable} should be immutable or
-be transformable to an immutable using the protocol described in
-section~\ref{immutable-transforms}.
-
-Because \class{ImmutableSet} objects provide a \method{__hash__()} method,
-they can be used as set elements or as dictionary keys. \class{ImmutableSet}
-objects do not have methods for adding or removing elements, so all of the
-elements must be known when the constructor is called.
-\end{classdesc}
-
-
-\subsection{Set Objects \label{set-objects}}
-
-Instances of \class{Set} and \class{ImmutableSet} both provide
-the following operations:
-
-\begin{tableiii}{c|c|l}{code}{Operation}{Equivalent}{Result}
- \lineiii{len(\var{s})}{}{cardinality of set \var{s}}
-
- \hline
- \lineiii{\var{x} in \var{s}}{}
- {test \var{x} for membership in \var{s}}
- \lineiii{\var{x} not in \var{s}}{}
- {test \var{x} for non-membership in \var{s}}
- \lineiii{\var{s}.issubset(\var{t})}{\code{\var{s} <= \var{t}}}
- {test whether every element in \var{s} is in \var{t}}
- \lineiii{\var{s}.issuperset(\var{t})}{\code{\var{s} >= \var{t}}}
- {test whether every element in \var{t} is in \var{s}}
-
- \hline
- \lineiii{\var{s}.union(\var{t})}{\var{s} \textbar{} \var{t}}
- {new set with elements from both \var{s} and \var{t}}
- \lineiii{\var{s}.intersection(\var{t})}{\var{s} \&\ \var{t}}
- {new set with elements common to \var{s} and \var{t}}
- \lineiii{\var{s}.difference(\var{t})}{\var{s} - \var{t}}
- {new set with elements in \var{s} but not in \var{t}}
- \lineiii{\var{s}.symmetric_difference(\var{t})}{\var{s} \^\ \var{t}}
- {new set with elements in either \var{s} or \var{t} but not both}
- \lineiii{\var{s}.copy()}{}
- {new set with a shallow copy of \var{s}}
-\end{tableiii}
-
-Note, the non-operator versions of \method{union()},
-\method{intersection()}, \method{difference()}, and
-\method{symmetric_difference()} will accept any iterable as an argument.
-In contrast, their operator based counterparts require their arguments to
-be sets. This precludes error-prone constructions like
-\code{Set('abc') \&\ 'cbs'} in favor of the more readable
-\code{Set('abc').intersection('cbs')}.
-\versionchanged[Formerly all arguments were required to be sets]{2.3.1}
-
-In addition, both \class{Set} and \class{ImmutableSet}
-support set to set comparisons. Two sets are equal if and only if
-every element of each set is contained in the other (each is a subset
-of the other).
-A set is less than another set if and only if the first set is a proper
-subset of the second set (is a subset, but is not equal).
-A set is greater than another set if and only if the first set is a proper
-superset of the second set (is a superset, but is not equal).
-
-The subset and equality comparisons do not generalize to a complete
-ordering function. For example, any two disjoint sets are not equal and
-are not subsets of each other, so \emph{all} of the following return
-\code{False}: \code{\var{a}<\var{b}}, \code{\var{a}==\var{b}}, or
-\code{\var{a}>\var{b}}.
-Accordingly, sets do not implement the \method{__cmp__} method.
-
-Since sets only define partial ordering (subset relationships), the output
-of the \method{list.sort()} method is undefined for lists of sets.
-
-The following table lists operations available in \class{ImmutableSet}
-but not found in \class{Set}:
-
-\begin{tableii}{c|l}{code}{Operation}{Result}
- \lineii{hash(\var{s})}{returns a hash value for \var{s}}
-\end{tableii}
-
-The following table lists operations available in \class{Set}
-but not found in \class{ImmutableSet}:
-
-\begin{tableiii}{c|c|l}{code}{Operation}{Equivalent}{Result}
- \lineiii{\var{s}.update(\var{t})}
- {\var{s} \textbar= \var{t}}
- {return set \var{s} with elements added from \var{t}}
- \lineiii{\var{s}.intersection_update(\var{t})}
- {\var{s} \&= \var{t}}
- {return set \var{s} keeping only elements also found in \var{t}}
- \lineiii{\var{s}.difference_update(\var{t})}
- {\var{s} -= \var{t}}
- {return set \var{s} after removing elements found in \var{t}}
- \lineiii{\var{s}.symmetric_difference_update(\var{t})}
- {\var{s} \textasciicircum= \var{t}}
- {return set \var{s} with elements from \var{s} or \var{t}
- but not both}
-
- \hline
- \lineiii{\var{s}.add(\var{x})}{}
- {add element \var{x} to set \var{s}}
- \lineiii{\var{s}.remove(\var{x})}{}
- {remove \var{x} from set \var{s}; raises \exception{KeyError}
- if not present}
- \lineiii{\var{s}.discard(\var{x})}{}
- {removes \var{x} from set \var{s} if present}
- \lineiii{\var{s}.pop()}{}
- {remove and return an arbitrary element from \var{s}; raises
- \exception{KeyError} if empty}
- \lineiii{\var{s}.clear()}{}
- {remove all elements from set \var{s}}
-\end{tableiii}
-
-Note, the non-operator versions of \method{update()},
-\method{intersection_update()}, \method{difference_update()}, and
-\method{symmetric_difference_update()} will accept any iterable as
-an argument.
-\versionchanged[Formerly all arguments were required to be sets]{2.3.1}
-
-Also note, the module also includes a \method{union_update()} method
-which is an alias for \method{update()}. The method is included for
-backwards compatibility. Programmers should prefer the
-\method{update()} method because it is supported by the builtin
-\class{set()} and \class{frozenset()} types.
-
-\subsection{Example \label{set-example}}
-
-\begin{verbatim}
->>> from sets import Set
->>> engineers = Set(['John', 'Jane', 'Jack', 'Janice'])
->>> programmers = Set(['Jack', 'Sam', 'Susan', 'Janice'])
->>> managers = Set(['Jane', 'Jack', 'Susan', 'Zack'])
->>> employees = engineers | programmers | managers # union
->>> engineering_management = engineers & managers # intersection
->>> fulltime_management = managers - engineers - programmers # difference
->>> engineers.add('Marvin') # add element
->>> print engineers
-Set(['Jane', 'Marvin', 'Janice', 'John', 'Jack'])
->>> employees.issuperset(engineers) # superset test
-False
->>> employees.union_update(engineers) # update from another set
->>> employees.issuperset(engineers)
-True
->>> for group in [engineers, programmers, managers, employees]:
-... group.discard('Susan') # unconditionally remove element
-... print group
-...
-Set(['Jane', 'Marvin', 'Janice', 'John', 'Jack'])
-Set(['Janice', 'Jack', 'Sam'])
-Set(['Jane', 'Zack', 'Jack'])
-Set(['Jack', 'Sam', 'Jane', 'Marvin', 'Janice', 'John', 'Zack'])
-\end{verbatim}
-
-
-\subsection{Protocol for automatic conversion to immutable
- \label{immutable-transforms}}
-
-Sets can only contain immutable elements. For convenience, mutable
-\class{Set} objects are automatically copied to an \class{ImmutableSet}
-before being added as a set element.
-
-The mechanism is to always add a hashable element, or if it is not
-hashable, the element is checked to see if it has an
-\method{__as_immutable__()} method which returns an immutable equivalent.
-
-Since \class{Set} objects have a \method{__as_immutable__()} method
-returning an instance of \class{ImmutableSet}, it is possible to
-construct sets of sets.
-
-A similar mechanism is needed by the \method{__contains__()} and
-\method{remove()} methods which need to hash an element to check
-for membership in a set. Those methods check an element for hashability
-and, if not, check for a \method{__as_temporarily_immutable__()} method
-which returns the element wrapped by a class that provides temporary
-methods for \method{__hash__()}, \method{__eq__()}, and \method{__ne__()}.
-
-The alternate mechanism spares the need to build a separate copy of
-the original mutable object.
-
-\class{Set} objects implement the \method{__as_temporarily_immutable__()}
-method which returns the \class{Set} object wrapped by a new class
-\class{_TemporarilyImmutableSet}.
-
-The two mechanisms for adding hashability are normally invisible to the
-user; however, a conflict can arise in a multi-threaded environment
-where one thread is updating a set while another has temporarily wrapped it
-in \class{_TemporarilyImmutableSet}. In other words, sets of mutable sets
-are not thread-safe.
-
-
-\subsection{Comparison to the built-in \class{set} types
- \label{comparison-to-builtin-set}}
-
-The built-in \class{set} and \class{frozenset} types were designed based
-on lessons learned from the \module{sets} module. The key differences are:
-
-\begin{itemize}
-\item \class{Set} and \class{ImmutableSet} were renamed to \class{set} and
- \class{frozenset}.
-\item There is no equivalent to \class{BaseSet}. Instead, use
- \code{isinstance(x, (set, frozenset))}.
-\item The hash algorithm for the built-ins performs significantly better
- (fewer collisions) for most datasets.
-\item The built-in versions have more space efficient pickles.
-\item The built-in versions do not have a \method{union_update()} method.
- Instead, use the \method{update()} method which is equivalent.
-\item The built-in versions do not have a \method{_repr(sorted=True)} method.
- Instead, use the built-in \function{repr()} and \function{sorted()}
- functions: \code{repr(sorted(s))}.
-\item The built-in version does not have a protocol for automatic conversion
- to immutable. Many found this feature to be confusing and no one
- in the community reported having found real uses for it.
-\end{itemize}
diff --git a/Doc/lib/libstdtypes.tex b/Doc/lib/libstdtypes.tex
index 8a527f6..a07e7d7 100644
--- a/Doc/lib/libstdtypes.tex
+++ b/Doc/lib/libstdtypes.tex
@@ -1334,16 +1334,6 @@ Note, the non-operator versions of the \method{update()},
\method{intersection_update()}, \method{difference_update()}, and
\method{symmetric_difference_update()} methods will accept any iterable
as an argument.
-
-The design of the set types was based on lessons learned from the
-\module{sets} module.
-
-\begin{seealso}
- \seelink{comparison-to-builtin-set.html}
- {Comparison to the built-in set types}
- {Differences between the \module{sets} module and the
- built-in set types.}
-\end{seealso}
\section{Mapping Types --- \class{dict} \label{typesmapping}}
diff --git a/Lib/msilib/__init__.py b/Lib/msilib/__init__.py
index 07053ba..9efef91 100644
--- a/Lib/msilib/__init__.py
+++ b/Lib/msilib/__init__.py
@@ -2,7 +2,7 @@
# Copyright (C) 2005 Martin v. Löwis
# Licensed to PSF under a Contributor Agreement.
from _msi import *
-import sets, os, string, re
+import os, string, re
Win64=0
@@ -184,7 +184,7 @@ class CAB:
def __init__(self, name):
self.name = name
self.files = []
- self.filenames = sets.Set()
+ self.filenames = set()
self.index = 0
def gen_id(self, file):
@@ -215,7 +215,7 @@ class CAB:
os.unlink(filename)
db.Commit()
-_directories = sets.Set()
+_directories = set()
class Directory:
def __init__(self, db, cab, basedir, physical, _logical, default, componentflags=None):
"""Create a new directory in the Directory table. There is a current component
@@ -239,8 +239,8 @@ class Directory:
self.physical = physical
self.logical = logical
self.component = None
- self.short_names = sets.Set()
- self.ids = sets.Set()
+ self.short_names = set()
+ self.ids = set()
self.keyfiles = {}
self.componentflags = componentflags
if basedir:
diff --git a/Lib/sets.py b/Lib/sets.py
deleted file mode 100644
index 55f93a6d..0000000
--- a/Lib/sets.py
+++ /dev/null
@@ -1,577 +0,0 @@
-"""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.
-
-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]).
-
-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.
-
-_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.
-
-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
-actually added is an ImmutableSet built from it (it compares equal to
-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.
-#
-# - Raymond Hettinger added a number of speedups and other
-# improvements.
-
-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
- try:
- True, False
- except NameError:
- True, False = (0==0, 0!=0)
-
-__all__ = ['BaseSet', 'Set', 'ImmutableSet']
-
-class BaseSet(object):
- """Common base class for mutable and immutable sets."""
-
- __slots__ = ['_data']
-
- # Constructor
-
- def __init__(self):
- """This is an abstract class."""
- # Don't call this from a concrete subclass!
- if self.__class__ is BaseSet:
- raise TypeError, ("BaseSet is an abstract class. "
- "Use Set or ImmutableSet.")
-
- # 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()
-
- # 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).
-
- def __cmp__(self, other):
- raise TypeError, "can't compare sets using cmp()"
-
- # 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.
-
- def __eq__(self, other):
- if isinstance(other, BaseSet):
- return self._data == other._data
- else:
- return False
-
- def __ne__(self, other):
- if isinstance(other, BaseSet):
- return self._data != other._data
- else:
- return True
-
- # Copying operations
-
- def copy(self):
- """Return a shallow copy of a set."""
- result = self.__class__()
- result._data.update(self._data)
- return result
-
- __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
- result = self.__class__()
- memo[id(self)] = result
- data = result._data
- value = True
- for elt in self:
- data[deepcopy(elt, memo)] = value
- return result
-
- # Standard set operations: union, intersection, both differences.
- # Each has an operator version (e.g. __or__, invoked with |) and a
- # method version (e.g. union).
- # 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).
-
- def __or__(self, other):
- """Return the union of two sets as a new set.
-
- (I.e. all elements that are in either set.)
- """
- if not isinstance(other, BaseSet):
- return NotImplemented
- return self.union(other)
-
- def union(self, other):
- """Return the union of two sets as a new set.
-
- (I.e. all elements that are in either set.)
- """
- result = self.__class__(self)
- result._update(other)
- return result
-
- def __and__(self, other):
- """Return the intersection of two sets as a new set.
-
- (I.e. all elements that are in both sets.)
- """
- if not isinstance(other, BaseSet):
- return NotImplemented
- return self.intersection(other)
-
- def intersection(self, other):
- """Return the intersection of two sets as a new set.
-
- (I.e. all elements that are in both sets.)
- """
- if not isinstance(other, BaseSet):
- other = Set(other)
- if len(self) <= len(other):
- little, big = self, other
- else:
- little, big = other, self
- common = ifilter(big._data.__contains__, little)
- return self.__class__(common)
-
- def __xor__(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.)
- """
- if not isinstance(other, BaseSet):
- return NotImplemented
- 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.)
- """
- result = self.__class__()
- data = result._data
- value = True
- selfdata = self._data
- try:
- otherdata = other._data
- except AttributeError:
- otherdata = Set(other)._data
- for elt in ifilterfalse(otherdata.__contains__, selfdata):
- data[elt] = value
- for elt in ifilterfalse(selfdata.__contains__, otherdata):
- data[elt] = value
- return result
-
- def __sub__(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.)
- """
- if not isinstance(other, BaseSet):
- return NotImplemented
- return self.difference(other)
-
- 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.)
- """
- result = self.__class__()
- data = result._data
- try:
- otherdata = other._data
- except AttributeError:
- otherdata = Set(other)._data
- value = True
- for elt in ifilterfalse(otherdata.__contains__, self):
- data[elt] = value
- return result
-
- # 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:
- return element in self._data
- except TypeError:
- transform = getattr(element, "__as_temporarily_immutable__", None)
- if transform is None:
- raise # re-raise the TypeError exception we caught
- return transform() in self._data
-
- # Subset and superset test
-
- def issubset(self, other):
- """Report whether another set contains this set."""
- self._binary_sanity_check(other)
- if len(self) > len(other): # Fast check for obvious cases
- return False
- for elt in ifilterfalse(other._data.__contains__, self):
- return False
- return True
-
- def issuperset(self, other):
- """Report whether this set contains another set."""
- self._binary_sanity_check(other)
- if len(self) < len(other): # Fast check for obvious cases
- return False
- for elt in ifilterfalse(self._data.__contains__, other):
- return False
- return True
-
- # 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)
-
- # 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
- # 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.
- result = 0
- for elt in self:
- result ^= hash(elt)
- return result
-
- def _update(self, iterable):
- # The main loop for update() and the subclass __init__() methods.
- data = self._data
-
- # Use the fast update() method when a dictionary is available.
- if isinstance(iterable, BaseSet):
- data.update(iterable._data)
- return
-
- value = True
-
- 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:
- transform = getattr(element, "__as_immutable__", None)
- 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:
- data[element] = value
- except TypeError:
- transform = getattr(element, "__as_immutable__", None)
- if transform is None:
- raise # re-raise the TypeError exception we caught
- data[transform()] = value
-
-
-class ImmutableSet(BaseSet):
- """Immutable set class."""
-
- __slots__ = ['_hashcode']
-
- # BaseSet + hashing
-
- def __init__(self, iterable=None):
- """Construct an immutable set from an optional iterable."""
- self._hashcode = None
- self._data = {}
- if iterable is not None:
- self._update(iterable)
-
- def __hash__(self):
- if self._hashcode is None:
- self._hashcode = self._compute_hash()
- return self._hashcode
-
- def __getstate__(self):
- return self._data, self._hashcode
-
- def __setstate__(self, state):
- self._data, self._hashcode = state
-
-class Set(BaseSet):
- """ Mutable set class."""
-
- __slots__ = []
-
- # BaseSet + operations requiring mutability; no hashing
-
- def __init__(self, iterable=None):
- """Construct a set from an optional iterable."""
- self._data = {}
- if iterable is not None:
- self._update(iterable)
-
- def __getstate__(self):
- # getstate's results are ignored if it is not
- return self._data,
-
- def __setstate__(self, data):
- self._data, = data
-
- 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."
-
- # 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.
-
- def __ior__(self, other):
- """Update a set with the union of itself and another."""
- self._binary_sanity_check(other)
- self._data.update(other._data)
- return self
-
- def union_update(self, other):
- """Update a set with the union of itself and another."""
- self._update(other)
-
- def __iand__(self, other):
- """Update a set with the intersection of itself and another."""
- self._binary_sanity_check(other)
- self._data = (self & other)._data
- return self
-
- def intersection_update(self, other):
- """Update a set with the intersection of itself and another."""
- if isinstance(other, BaseSet):
- self &= other
- else:
- self._data = (self.intersection(other))._data
-
- def __ixor__(self, other):
- """Update a set with the symmetric difference of itself and another."""
- self._binary_sanity_check(other)
- self.symmetric_difference_update(other)
- return self
-
- def symmetric_difference_update(self, other):
- """Update a set with the symmetric difference of itself and another."""
- data = self._data
- value = True
- if not isinstance(other, BaseSet):
- other = Set(other)
- if self is other:
- self.clear()
- for elt in other:
- if elt in data:
- del data[elt]
- else:
- data[elt] = value
-
- def __isub__(self, other):
- """Remove all elements of another set from this set."""
- self._binary_sanity_check(other)
- self.difference_update(other)
- return self
-
- def difference_update(self, other):
- """Remove all elements of another set from this set."""
- data = self._data
- if not isinstance(other, BaseSet):
- other = Set(other)
- if self is other:
- self.clear()
- for elt in ifilter(data.__contains__, other):
- del data[elt]
-
- # Python dict-like mass mutations: update, clear
-
- def update(self, iterable):
- """Add all values from an iterable (such as a list or file)."""
- self._update(iterable)
-
- 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:
- self._data[element] = True
- except TypeError:
- transform = getattr(element, "__as_immutable__", None)
- if transform is None:
- raise # re-raise the TypeError exception we caught
- self._data[transform()] = True
-
- 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:
- del self._data[element]
- except TypeError:
- transform = getattr(element, "__as_temporarily_immutable__", None)
- if transform is None:
- raise # re-raise the TypeError exception we caught
- del self._data[transform()]
-
- 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:
- self.remove(element)
- except KeyError:
- pass
-
- def pop(self):
- """Remove and return an arbitrary set element."""
- return self._data.popitem()[0]
-
- def __as_immutable__(self):
- # Return a copy of self as an immutable set
- return ImmutableSet(self)
-
- def __as_temporarily_immutable__(self):
- # Return self wrapped in a temporarily immutable set
- return _TemporarilyImmutableSet(self)
-
-
-class _TemporarilyImmutableSet(BaseSet):
- # Wrap a mutable set as if it was temporarily immutable.
- # This only supplies hashing and equality comparisons.
-
- def __init__(self, set):
- self._set = set
- self._data = set._data # Needed by ImmutableSet.__eq__()
-
- def __hash__(self):
- return self._set._compute_hash()
diff --git a/Lib/test/test_cookielib.py b/Lib/test/test_cookielib.py
index 991506c..544f29f 100644
--- a/Lib/test/test_cookielib.py
+++ b/Lib/test/test_cookielib.py
@@ -1723,7 +1723,6 @@ class LWPCookieTests(TestCase):
def test_main(verbose=None):
- from test import test_sets
test_support.run_unittest(
DateTimeTests,
HeaderTests,
diff --git a/Lib/test/test_set.py b/Lib/test/test_set.py
index 6641ff8..9bd0d43 100644
--- a/Lib/test/test_set.py
+++ b/Lib/test/test_set.py
@@ -1451,7 +1451,6 @@ class TestVariousIteratorArgs(unittest.TestCase):
#==============================================================================
def test_main(verbose=None):
- from test import test_sets
test_classes = (
TestSet,
TestSetSubclass,
diff --git a/Lib/test/test_sets.py b/Lib/test/test_sets.py
deleted file mode 100644
index 88cfcac..0000000
--- a/Lib/test/test_sets.py
+++ /dev/null
@@ -1,853 +0,0 @@
-#!/usr/bin/env python
-
-import unittest, operator, copy, pickle, random
-from sets import Set, ImmutableSet
-from test import test_support
-
-empty_set = Set()
-
-#==============================================================================
-
-class TestBasicOps(unittest.TestCase):
-
- def test_repr(self):
- if self.repr is not None:
- self.assertEqual(repr(self.set), self.repr)
-
- def test_length(self):
- self.assertEqual(len(self.set), self.length)
-
- def test_self_equality(self):
- self.assertEqual(self.set, self.set)
-
- def test_equivalent_equality(self):
- self.assertEqual(self.set, self.dup)
-
- def test_copy(self):
- self.assertEqual(self.set.copy(), self.dup)
-
- def test_self_union(self):
- result = self.set | self.set
- self.assertEqual(result, self.dup)
-
- def test_empty_union(self):
- result = self.set | empty_set
- self.assertEqual(result, self.dup)
-
- def test_union_empty(self):
- result = empty_set | self.set
- self.assertEqual(result, self.dup)
-
- def test_self_intersection(self):
- result = self.set & self.set
- self.assertEqual(result, self.dup)
-
- def test_empty_intersection(self):
- result = self.set & empty_set
- self.assertEqual(result, empty_set)
-
- def test_intersection_empty(self):
- result = empty_set & self.set
- self.assertEqual(result, empty_set)
-
- def test_self_symmetric_difference(self):
- result = self.set ^ self.set
- self.assertEqual(result, empty_set)
-
- def checkempty_symmetric_difference(self):
- result = self.set ^ empty_set
- self.assertEqual(result, self.set)
-
- def test_self_difference(self):
- result = self.set - self.set
- self.assertEqual(result, empty_set)
-
- def test_empty_difference(self):
- result = self.set - empty_set
- self.assertEqual(result, self.dup)
-
- def test_empty_difference_rev(self):
- result = empty_set - self.set
- self.assertEqual(result, empty_set)
-
- def test_iteration(self):
- for v in self.set:
- self.assert_(v in self.values)
-
- def test_pickling(self):
- p = pickle.dumps(self.set)
- copy = pickle.loads(p)
- self.assertEqual(self.set, copy,
- "%s != %s" % (self.set, copy))
-
-#------------------------------------------------------------------------------
-
-class TestBasicOpsEmpty(TestBasicOps):
- def setUp(self):
- self.case = "empty set"
- self.values = []
- self.set = Set(self.values)
- self.dup = Set(self.values)
- self.length = 0
- self.repr = "Set([])"
-
-#------------------------------------------------------------------------------
-
-class TestBasicOpsSingleton(TestBasicOps):
- def setUp(self):
- self.case = "unit set (number)"
- self.values = [3]
- self.set = Set(self.values)
- self.dup = Set(self.values)
- self.length = 1
- self.repr = "Set([3])"
-
- def test_in(self):
- self.failUnless(3 in self.set)
-
- def test_not_in(self):
- self.failUnless(2 not in self.set)
-
-#------------------------------------------------------------------------------
-
-class TestBasicOpsTuple(TestBasicOps):
- def setUp(self):
- self.case = "unit set (tuple)"
- self.values = [(0, "zero")]
- self.set = Set(self.values)
- self.dup = Set(self.values)
- self.length = 1
- self.repr = "Set([(0, 'zero')])"
-
- def test_in(self):
- self.failUnless((0, "zero") in self.set)
-
- def test_not_in(self):
- self.failUnless(9 not in self.set)
-
-#------------------------------------------------------------------------------
-
-class TestBasicOpsTriple(TestBasicOps):
- def setUp(self):
- self.case = "triple set"
- self.values = [0, "zero", operator.add]
- self.set = Set(self.values)
- self.dup = Set(self.values)
- self.length = 3
- self.repr = None
-
-#==============================================================================
-
-def baditer():
- raise TypeError
- yield True
-
-def gooditer():
- yield True
-
-class TestExceptionPropagation(unittest.TestCase):
- """SF 628246: Set constructor should not trap iterator TypeErrors"""
-
- def test_instanceWithException(self):
- self.assertRaises(TypeError, Set, baditer())
-
- def test_instancesWithoutException(self):
- # All of these iterables should load without exception.
- Set([1,2,3])
- Set((1,2,3))
- Set({'one':1, 'two':2, 'three':3})
- Set(xrange(3))
- Set('abc')
- Set(gooditer())
-
-#==============================================================================
-
-class TestSetOfSets(unittest.TestCase):
- def test_constructor(self):
- inner = Set([1])
- outer = Set([inner])
- element = outer.pop()
- self.assertEqual(type(element), ImmutableSet)
- outer.add(inner) # Rebuild set of sets with .add method
- outer.remove(inner)
- self.assertEqual(outer, Set()) # Verify that remove worked
- outer.discard(inner) # Absence of KeyError indicates working fine
-
-#==============================================================================
-
-class TestBinaryOps(unittest.TestCase):
- def setUp(self):
- self.set = Set((2, 4, 6))
-
- def test_eq(self): # SF bug 643115
- self.assertEqual(self.set, Set({2:1,4:3,6:5}))
-
- def test_union_subset(self):
- result = self.set | Set([2])
- self.assertEqual(result, Set((2, 4, 6)))
-
- def test_union_superset(self):
- result = self.set | Set([2, 4, 6, 8])
- self.assertEqual(result, Set([2, 4, 6, 8]))
-
- def test_union_overlap(self):
- result = self.set | Set([3, 4, 5])
- self.assertEqual(result, Set([2, 3, 4, 5, 6]))
-
- def test_union_non_overlap(self):
- result = self.set | Set([8])
- self.assertEqual(result, Set([2, 4, 6, 8]))
-
- def test_intersection_subset(self):
- result = self.set & Set((2, 4))
- self.assertEqual(result, Set((2, 4)))
-
- def test_intersection_superset(self):
- result = self.set & Set([2, 4, 6, 8])
- self.assertEqual(result, Set([2, 4, 6]))
-
- def test_intersection_overlap(self):
- result = self.set & Set([3, 4, 5])
- self.assertEqual(result, Set([4]))
-
- def test_intersection_non_overlap(self):
- result = self.set & Set([8])
- self.assertEqual(result, empty_set)
-
- def test_sym_difference_subset(self):
- result = self.set ^ Set((2, 4))
- self.assertEqual(result, Set([6]))
-
- def test_sym_difference_superset(self):
- result = self.set ^ Set((2, 4, 6, 8))
- self.assertEqual(result, Set([8]))
-
- def test_sym_difference_overlap(self):
- result = self.set ^ Set((3, 4, 5))
- self.assertEqual(result, Set([2, 3, 5, 6]))
-
- def test_sym_difference_non_overlap(self):
- result = self.set ^ Set([8])
- self.assertEqual(result, Set([2, 4, 6, 8]))
-
- def test_cmp(self):
- a, b = Set('a'), Set('b')
- self.assertRaises(TypeError, cmp, a, b)
-
- # In py3k, this works!
- self.assertRaises(TypeError, cmp, a, a)
-
- self.assertRaises(TypeError, cmp, a, 12)
- self.assertRaises(TypeError, cmp, "abc", a)
-
- def test_inplace_on_self(self):
- t = self.set.copy()
- t |= t
- self.assertEqual(t, self.set)
- t &= t
- self.assertEqual(t, self.set)
- t -= t
- self.assertEqual(len(t), 0)
- t = self.set.copy()
- t ^= t
- self.assertEqual(len(t), 0)
-
-
-#==============================================================================
-
-class TestUpdateOps(unittest.TestCase):
- def setUp(self):
- self.set = Set((2, 4, 6))
-
- def test_union_subset(self):
- self.set |= Set([2])
- self.assertEqual(self.set, Set((2, 4, 6)))
-
- def test_union_superset(self):
- self.set |= Set([2, 4, 6, 8])
- self.assertEqual(self.set, Set([2, 4, 6, 8]))
-
- def test_union_overlap(self):
- self.set |= Set([3, 4, 5])
- self.assertEqual(self.set, Set([2, 3, 4, 5, 6]))
-
- def test_union_non_overlap(self):
- self.set |= Set([8])
- self.assertEqual(self.set, Set([2, 4, 6, 8]))
-
- def test_union_method_call(self):
- self.set.union_update(Set([3, 4, 5]))
- self.assertEqual(self.set, Set([2, 3, 4, 5, 6]))
-
- def test_intersection_subset(self):
- self.set &= Set((2, 4))
- self.assertEqual(self.set, Set((2, 4)))
-
- def test_intersection_superset(self):
- self.set &= Set([2, 4, 6, 8])
- self.assertEqual(self.set, Set([2, 4, 6]))
-
- def test_intersection_overlap(self):
- self.set &= Set([3, 4, 5])
- self.assertEqual(self.set, Set([4]))
-
- def test_intersection_non_overlap(self):
- self.set &= Set([8])
- self.assertEqual(self.set, empty_set)
-
- def test_intersection_method_call(self):
- self.set.intersection_update(Set([3, 4, 5]))
- self.assertEqual(self.set, Set([4]))
-
- def test_sym_difference_subset(self):
- self.set ^= Set((2, 4))
- self.assertEqual(self.set, Set([6]))
-
- def test_sym_difference_superset(self):
- self.set ^= Set((2, 4, 6, 8))
- self.assertEqual(self.set, Set([8]))
-
- def test_sym_difference_overlap(self):
- self.set ^= Set((3, 4, 5))
- self.assertEqual(self.set, Set([2, 3, 5, 6]))
-
- def test_sym_difference_non_overlap(self):
- self.set ^= Set([8])
- self.assertEqual(self.set, Set([2, 4, 6, 8]))
-
- def test_sym_difference_method_call(self):
- self.set.symmetric_difference_update(Set([3, 4, 5]))
- self.assertEqual(self.set, Set([2, 3, 5, 6]))
-
- def test_difference_subset(self):
- self.set -= Set((2, 4))
- self.assertEqual(self.set, Set([6]))
-
- def test_difference_superset(self):
- self.set -= Set((2, 4, 6, 8))
- self.assertEqual(self.set, Set([]))
-
- def test_difference_overlap(self):
- self.set -= Set((3, 4, 5))
- self.assertEqual(self.set, Set([2, 6]))
-
- def test_difference_non_overlap(self):
- self.set -= Set([8])
- self.assertEqual(self.set, Set([2, 4, 6]))
-
- def test_difference_method_call(self):
- self.set.difference_update(Set([3, 4, 5]))
- self.assertEqual(self.set, Set([2, 6]))
-
-#==============================================================================
-
-class TestMutate(unittest.TestCase):
- def setUp(self):
- self.values = ["a", "b", "c"]
- self.set = Set(self.values)
-
- def test_add_present(self):
- self.set.add("c")
- self.assertEqual(self.set, Set("abc"))
-
- def test_add_absent(self):
- self.set.add("d")
- self.assertEqual(self.set, Set("abcd"))
-
- def test_add_until_full(self):
- tmp = Set()
- expected_len = 0
- for v in self.values:
- tmp.add(v)
- expected_len += 1
- self.assertEqual(len(tmp), expected_len)
- self.assertEqual(tmp, self.set)
-
- def test_remove_present(self):
- self.set.remove("b")
- self.assertEqual(self.set, Set("ac"))
-
- def test_remove_absent(self):
- try:
- self.set.remove("d")
- self.fail("Removing missing element should have raised LookupError")
- except LookupError:
- pass
-
- def test_remove_until_empty(self):
- expected_len = len(self.set)
- for v in self.values:
- self.set.remove(v)
- expected_len -= 1
- self.assertEqual(len(self.set), expected_len)
-
- def test_discard_present(self):
- self.set.discard("c")
- self.assertEqual(self.set, Set("ab"))
-
- def test_discard_absent(self):
- self.set.discard("d")
- self.assertEqual(self.set, Set("abc"))
-
- def test_clear(self):
- self.set.clear()
- self.assertEqual(len(self.set), 0)
-
- def test_pop(self):
- popped = {}
- while self.set:
- popped[self.set.pop()] = None
- self.assertEqual(len(popped), len(self.values))
- for v in self.values:
- self.failUnless(v in popped)
-
- def test_update_empty_tuple(self):
- self.set.union_update(())
- self.assertEqual(self.set, Set(self.values))
-
- def test_update_unit_tuple_overlap(self):
- self.set.union_update(("a",))
- self.assertEqual(self.set, Set(self.values))
-
- def test_update_unit_tuple_non_overlap(self):
- self.set.union_update(("a", "z"))
- self.assertEqual(self.set, Set(self.values + ["z"]))
-
-#==============================================================================
-
-class TestSubsets(unittest.TestCase):
-
- case2method = {"<=": "issubset",
- ">=": "issuperset",
- }
-
- reverse = {"==": "==",
- "!=": "!=",
- "<": ">",
- ">": "<",
- "<=": ">=",
- ">=": "<=",
- }
-
- def test_issubset(self):
- x = self.left
- y = self.right
- for case in "!=", "==", "<", "<=", ">", ">=":
- expected = case in self.cases
- # Test the binary infix spelling.
- result = eval("x" + case + "y", locals())
- self.assertEqual(result, expected)
- # Test the "friendly" method-name spelling, if one exists.
- if case in TestSubsets.case2method:
- method = getattr(x, TestSubsets.case2method[case])
- result = method(y)
- self.assertEqual(result, expected)
-
- # Now do the same for the operands reversed.
- rcase = TestSubsets.reverse[case]
- result = eval("y" + rcase + "x", locals())
- self.assertEqual(result, expected)
- if rcase in TestSubsets.case2method:
- method = getattr(y, TestSubsets.case2method[rcase])
- result = method(x)
- self.assertEqual(result, expected)
-#------------------------------------------------------------------------------
-
-class TestSubsetEqualEmpty(TestSubsets):
- left = Set()
- right = Set()
- name = "both empty"
- cases = "==", "<=", ">="
-
-#------------------------------------------------------------------------------
-
-class TestSubsetEqualNonEmpty(TestSubsets):
- left = Set([1, 2])
- right = Set([1, 2])
- name = "equal pair"
- cases = "==", "<=", ">="
-
-#------------------------------------------------------------------------------
-
-class TestSubsetEmptyNonEmpty(TestSubsets):
- left = Set()
- right = Set([1, 2])
- name = "one empty, one non-empty"
- cases = "!=", "<", "<="
-
-#------------------------------------------------------------------------------
-
-class TestSubsetPartial(TestSubsets):
- left = Set([1])
- right = Set([1, 2])
- name = "one a non-empty proper subset of other"
- cases = "!=", "<", "<="
-
-#------------------------------------------------------------------------------
-
-class TestSubsetNonOverlap(TestSubsets):
- left = Set([1])
- right = Set([2])
- name = "neither empty, neither contains"
- cases = "!="
-
-#==============================================================================
-
-class TestOnlySetsInBinaryOps(unittest.TestCase):
-
- def test_eq_ne(self):
- # Unlike the others, this is testing that == and != *are* allowed.
- self.assertEqual(self.other == self.set, False)
- self.assertEqual(self.set == self.other, False)
- self.assertEqual(self.other != self.set, True)
- self.assertEqual(self.set != self.other, True)
-
- def test_ge_gt_le_lt(self):
- self.assertRaises(TypeError, lambda: self.set < self.other)
- self.assertRaises(TypeError, lambda: self.set <= self.other)
- self.assertRaises(TypeError, lambda: self.set > self.other)
- self.assertRaises(TypeError, lambda: self.set >= self.other)
-
- self.assertRaises(TypeError, lambda: self.other < self.set)
- self.assertRaises(TypeError, lambda: self.other <= self.set)
- self.assertRaises(TypeError, lambda: self.other > self.set)
- self.assertRaises(TypeError, lambda: self.other >= self.set)
-
- def test_union_update_operator(self):
- try:
- self.set |= self.other
- except TypeError:
- pass
- else:
- self.fail("expected TypeError")
-
- def test_union_update(self):
- if self.otherIsIterable:
- self.set.union_update(self.other)
- else:
- self.assertRaises(TypeError, self.set.union_update, self.other)
-
- def test_union(self):
- self.assertRaises(TypeError, lambda: self.set | self.other)
- self.assertRaises(TypeError, lambda: self.other | self.set)
- if self.otherIsIterable:
- self.set.union(self.other)
- else:
- self.assertRaises(TypeError, self.set.union, self.other)
-
- def test_intersection_update_operator(self):
- try:
- self.set &= self.other
- except TypeError:
- pass
- else:
- self.fail("expected TypeError")
-
- def test_intersection_update(self):
- if self.otherIsIterable:
- self.set.intersection_update(self.other)
- else:
- self.assertRaises(TypeError,
- self.set.intersection_update,
- self.other)
-
- def test_intersection(self):
- self.assertRaises(TypeError, lambda: self.set & self.other)
- self.assertRaises(TypeError, lambda: self.other & self.set)
- if self.otherIsIterable:
- self.set.intersection(self.other)
- else:
- self.assertRaises(TypeError, self.set.intersection, self.other)
-
- def test_sym_difference_update_operator(self):
- try:
- self.set ^= self.other
- except TypeError:
- pass
- else:
- self.fail("expected TypeError")
-
- def test_sym_difference_update(self):
- if self.otherIsIterable:
- self.set.symmetric_difference_update(self.other)
- else:
- self.assertRaises(TypeError,
- self.set.symmetric_difference_update,
- self.other)
-
- def test_sym_difference(self):
- self.assertRaises(TypeError, lambda: self.set ^ self.other)
- self.assertRaises(TypeError, lambda: self.other ^ self.set)
- if self.otherIsIterable:
- self.set.symmetric_difference(self.other)
- else:
- self.assertRaises(TypeError, self.set.symmetric_difference, self.other)
-
- def test_difference_update_operator(self):
- try:
- self.set -= self.other
- except TypeError:
- pass
- else:
- self.fail("expected TypeError")
-
- def test_difference_update(self):
- if self.otherIsIterable:
- self.set.difference_update(self.other)
- else:
- self.assertRaises(TypeError,
- self.set.difference_update,
- self.other)
-
- def test_difference(self):
- self.assertRaises(TypeError, lambda: self.set - self.other)
- self.assertRaises(TypeError, lambda: self.other - self.set)
- if self.otherIsIterable:
- self.set.difference(self.other)
- else:
- self.assertRaises(TypeError, self.set.difference, self.other)
-
-#------------------------------------------------------------------------------
-
-class TestOnlySetsNumeric(TestOnlySetsInBinaryOps):
- def setUp(self):
- self.set = Set((1, 2, 3))
- self.other = 19
- self.otherIsIterable = False
-
-#------------------------------------------------------------------------------
-
-class TestOnlySetsDict(TestOnlySetsInBinaryOps):
- def setUp(self):
- self.set = Set((1, 2, 3))
- self.other = {1:2, 3:4}
- self.otherIsIterable = True
-
-#------------------------------------------------------------------------------
-
-class TestOnlySetsOperator(TestOnlySetsInBinaryOps):
- def setUp(self):
- self.set = Set((1, 2, 3))
- self.other = operator.add
- self.otherIsIterable = False
-
-#------------------------------------------------------------------------------
-
-class TestOnlySetsTuple(TestOnlySetsInBinaryOps):
- def setUp(self):
- self.set = Set((1, 2, 3))
- self.other = (2, 4, 6)
- self.otherIsIterable = True
-
-#------------------------------------------------------------------------------
-
-class TestOnlySetsString(TestOnlySetsInBinaryOps):
- def setUp(self):
- self.set = Set((1, 2, 3))
- self.other = 'abc'
- self.otherIsIterable = True
-
-#------------------------------------------------------------------------------
-
-class TestOnlySetsGenerator(TestOnlySetsInBinaryOps):
- def setUp(self):
- def gen():
- for i in xrange(0, 10, 2):
- yield i
- self.set = Set((1, 2, 3))
- self.other = gen()
- self.otherIsIterable = True
-
-#------------------------------------------------------------------------------
-
-class TestOnlySetsofSets(TestOnlySetsInBinaryOps):
- def setUp(self):
- self.set = Set((1, 2, 3))
- self.other = [Set('ab'), ImmutableSet('cd')]
- self.otherIsIterable = True
-
-#==============================================================================
-
-class TestCopying(unittest.TestCase):
-
- def test_copy(self):
- dup = self.set.copy()
- dup_list = sorted(dup, key=repr)
- set_list = sorted(self.set, key=repr)
- self.assertEqual(len(dup_list), len(set_list))
- for i in range(len(dup_list)):
- self.failUnless(dup_list[i] is set_list[i])
-
- def test_deep_copy(self):
- dup = copy.deepcopy(self.set)
- ##print type(dup), repr(dup)
- dup_list = sorted(dup, key=repr)
- set_list = sorted(self.set, key=repr)
- self.assertEqual(len(dup_list), len(set_list))
- for i in range(len(dup_list)):
- self.assertEqual(dup_list[i], set_list[i])
-
-#------------------------------------------------------------------------------
-
-class TestCopyingEmpty(TestCopying):
- def setUp(self):
- self.set = Set()
-
-#------------------------------------------------------------------------------
-
-class TestCopyingSingleton(TestCopying):
- def setUp(self):
- self.set = Set(["hello"])
-
-#------------------------------------------------------------------------------
-
-class TestCopyingTriple(TestCopying):
- def setUp(self):
- self.set = Set(["zero", 0, None])
-
-#------------------------------------------------------------------------------
-
-class TestCopyingTuple(TestCopying):
- def setUp(self):
- self.set = Set([(1, 2)])
-
-#------------------------------------------------------------------------------
-
-class TestCopyingNested(TestCopying):
- def setUp(self):
- self.set = Set([((1, 2), (3, 4))])
-
-#==============================================================================
-
-class TestIdentities(unittest.TestCase):
- def setUp(self):
- self.a = Set([random.randrange(100) for i in xrange(50)])
- self.b = Set([random.randrange(100) for i in xrange(50)])
-
- def test_binopsVsSubsets(self):
- a, b = self.a, self.b
- self.assert_(a - b <= a)
- self.assert_(b - a <= b)
- self.assert_(a & b <= a)
- self.assert_(a & b <= b)
- self.assert_(a | b >= a)
- self.assert_(a | b >= b)
- self.assert_(a ^ b <= a | b)
-
- def test_commutativity(self):
- a, b = self.a, self.b
- self.assertEqual(a&b, b&a)
- self.assertEqual(a|b, b|a)
- self.assertEqual(a^b, b^a)
- if a != b:
- self.assertNotEqual(a-b, b-a)
-
- def test_reflexsive_relations(self):
- a, zero = self.a, Set()
- self.assertEqual(a ^ a, zero)
- self.assertEqual(a - a, zero)
- self.assertEqual(a | a, a)
- self.assertEqual(a & a, a)
- self.assert_(a <= a)
- self.assert_(a >= a)
- self.assert_(a == a)
-
- def test_summations(self):
- # check that sums of parts equal the whole
- a, b = self.a, self.b
- self.assertEqual((a-b)|(a&b)|(b-a), a|b)
- self.assertEqual((a&b)|(a^b), a|b)
- self.assertEqual(a|(b-a), a|b)
- self.assertEqual((a-b)|b, a|b)
- self.assertEqual((a-b)|(a&b), a)
- self.assertEqual((b-a)|(a&b), b)
- self.assertEqual((a-b)|(b-a), a^b)
-
- def test_exclusion(self):
- # check that inverse operations do not overlap
- a, b, zero = self.a, self.b, Set()
- self.assertEqual((a-b)&b, zero)
- self.assertEqual((b-a)&a, zero)
- self.assertEqual((a&b)&(a^b), zero)
-
- def test_cardinality_relations(self):
- a, b = self.a, self.b
- self.assertEqual(len(a), len(a-b) + len(a&b))
- self.assertEqual(len(b), len(b-a) + len(a&b))
- self.assertEqual(len(a^b), len(a-b) + len(b-a))
- self.assertEqual(len(a|b), len(a-b) + len(a&b) + len(b-a))
- self.assertEqual(len(a^b) + len(a&b), len(a|b))
-
-#==============================================================================
-
-libreftest = """
-Example from the Library Reference: Doc/lib/libsets.tex
-
->>> from sets import Set as Base # override _repr to get sorted output
->>> class Set(Base):
-... def _repr(self):
-... return Base._repr(self, sorted=True)
->>> engineers = Set(['John', 'Jane', 'Jack', 'Janice'])
->>> programmers = Set(['Jack', 'Sam', 'Susan', 'Janice'])
->>> managers = Set(['Jane', 'Jack', 'Susan', 'Zack'])
->>> employees = engineers | programmers | managers # union
->>> engineering_management = engineers & managers # intersection
->>> fulltime_management = managers - engineers - programmers # difference
->>> engineers.add('Marvin')
->>> print engineers
-Set(['Jack', 'Jane', 'Janice', 'John', 'Marvin'])
->>> employees.issuperset(engineers) # superset test
-False
->>> employees.union_update(engineers) # update from another set
->>> employees.issuperset(engineers)
-True
->>> for group in [engineers, programmers, managers, employees]:
-... group.discard('Susan') # unconditionally remove element
-... print group
-...
-Set(['Jack', 'Jane', 'Janice', 'John', 'Marvin'])
-Set(['Jack', 'Janice', 'Sam'])
-Set(['Jack', 'Jane', 'Zack'])
-Set(['Jack', 'Jane', 'Janice', 'John', 'Marvin', 'Sam', 'Zack'])
-"""
-
-#==============================================================================
-
-__test__ = {'libreftest' : libreftest}
-
-def test_main(verbose=None):
- import doctest
- from test import test_sets
- test_support.run_unittest(
- TestSetOfSets,
- TestExceptionPropagation,
- TestBasicOpsEmpty,
- TestBasicOpsSingleton,
- TestBasicOpsTuple,
- TestBasicOpsTriple,
- TestBinaryOps,
- TestUpdateOps,
- TestMutate,
- TestSubsetEqualEmpty,
- TestSubsetEqualNonEmpty,
- TestSubsetEmptyNonEmpty,
- TestSubsetPartial,
- TestSubsetNonOverlap,
- TestOnlySetsNumeric,
- TestOnlySetsDict,
- TestOnlySetsOperator,
- TestOnlySetsTuple,
- TestOnlySetsString,
- TestOnlySetsGenerator,
- TestOnlySetsofSets,
- TestCopyingEmpty,
- TestCopyingSingleton,
- TestCopyingTriple,
- TestCopyingTuple,
- TestCopyingNested,
- TestIdentities,
- doctest.DocTestSuite(test_sets),
- )
-
-if __name__ == "__main__":
- test_main(verbose=True)