Skip to content

Commit

Permalink
Merge pull request #210 from kurtbrose/complement-set
Browse files Browse the repository at this point in the history
added __rsub__ to complement-set
  • Loading branch information
mahmoud authored Oct 19, 2019
2 parents 67f32d5 + d28450f commit bf8a659
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
27 changes: 25 additions & 2 deletions boltons/setutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -861,6 +861,22 @@ def __sub__(self, other):
else: # + +
return _ComplementSet(included=self._included.difference(inc))

def __rsub__(self, other):
inc, exc = _norm_args_notimplemented(other)
if inc is NotImplemented:
return NotImplemented
# rsub, so the expression being evaluated is "other - self"
if self._included is None:
if exc is None: # - +
return _ComplementSet(included=inc & self._excluded)
else: # - -
return _ComplementSet(included=self._excluded - exc)
else:
if inc is None: # + -
return _ComplementSet(excluded=exc | self._included)
else: # + +
return _ComplementSet(included=inc.difference(self._included))

def difference_update(self, other):
try:
self -= other
Expand Down Expand Up @@ -894,11 +910,18 @@ def __hash__(self):
return hash(self._included) ^ hash(self._excluded)

def __len__(self):
if self._included:
if self._included is not None:
return len(self._included)
raise NotImplementedError('complemented sets have undefined length')

def __iter__(self):
if self._included:
if self._included is not None:
return iter(self._included)
raise NotImplementedError('complemented sets have undefined contents')

def __bool__(self):
if self._included is not None:
return bool(self._included)
return True

__nonzero__ = __bool__ # py2 compat
3 changes: 3 additions & 0 deletions tests/test_setutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,9 +113,12 @@ def test_complement_set():
assert (sab ^ cab) == (cbc ^ sbc)
assert cab - cc == sc
assert cab - sab == cab
assert sab - cab == sab
assert (cab ^ cbc | set('b')) == (sab | sbc)
everything = complement(frozenset())
assert everything in everything # https://en.wikipedia.org/wiki/Russell%27s_paradox
assert bool(cab)
assert not complement(u)
# destructive testing
cab ^= sab
cab ^= sab
Expand Down

0 comments on commit bf8a659

Please sign in to comment.