Skip to content

Commit

Permalink
enh: added inverse operator ~
Browse files Browse the repository at this point in the history
One cannot override ! (easily), but ~ is also
used substantially.
  • Loading branch information
zerothi committed May 7, 2020
1 parent 99a7b59 commit 17749c1
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions sisl/category/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,9 @@ def __and__(self, other):
def __xor__(self, other):
return XOrCategory(self, other)

def __invert__(self):
return NotCategory(self)


@set_module("sisl.category")
class NullCategory(Category):
Expand Down Expand Up @@ -167,6 +170,46 @@ def name(self):
return "∅"


@set_module("sisl.category")
class NotCategory(Category):
""" A class returning the *opposite* of this class (NullCategory) if it is categorized as such """
__slots__ = ("_cat",)

def __init__(self, cat):
super().__init__()
if isinstance(cat, CompositeCategory):
self.set_name(f"~({cat})")
else:
self.set_name(f"~{cat}")
self._cat = cat

def categorize(self, *args, **kwargs):
r""" Base method for queriyng whether an object is a certain category """
cat = self._cat.categorize(*args, **kwargs)

def check(cat):
if isinstance(cat, NullCategory):
return self
return NullCategory()

if isinstance(cat, list):
return list(map(check, cat))
return check(cat)

@singledispatchmethod
def __eq__(self, other):
if isinstance(other, NotCategory):
return self._cat == other._cat
return False

@__eq__.register(list)
@__eq__.register(tuple)
@__eq__.register(np.ndarray)
def _(self, other):
# this will call the list approach
return super().__eq__(other)


@set_module("sisl.category")
class CompositeCategory(Category):
""" A composite class consisting of two categories
Expand Down

0 comments on commit 17749c1

Please sign in to comment.