Skip to content

Instantly share code, notes, and snippets.

@mrcljx
Created November 2, 2023 15:19
Show Gist options
  • Save mrcljx/3c43a4ea4ae8506140aa65f843716102 to your computer and use it in GitHub Desktop.
Save mrcljx/3c43a4ea4ae8506140aa65f843716102 to your computer and use it in GitHub Desktop.
class BooleanContainer(Container[_T]):
"""A container that supports boolean operations."""
def __init__(
self,
container: Container[_T] | None = None,
predicate: Callable[[object], _T] | None = None,
) -> None:
if container is not None:
assert predicate is None, "Cannot specify both container and predicate"
predicate = container.__contains__
self._predicate = predicate or (lambda _: False)
@override
def __contains__(self, item: _T) -> bool:
return self._predicate(item)
def __and__(self, other: Container[_T]) -> Container[_T]:
"""Supports `self & other`."""
if not isinstance(other, Container):
return NotImplemented
return BooleanContainer(lambda obj: obj in self and obj in other)
def __or__(self, other: Container[_T]) -> Container[_T]:
"""Supports `self | other`."""
if not isinstance(other, Container):
return NotImplemented
return BooleanContainer(lambda obj: obj in self or obj in other)
def __neg__(self) -> Container[_T]:
"""Supports `-self`."""
return BooleanContainer(lambda obj: obj not in self)
def __rsub__(self, other: Container[_T]) -> Container[_T]:
"""Supports `other - self`."""
if not isinstance(other, Container):
return NotImplemented
return BooleanContainer(lambda obj: obj in other and obj not in self)
@classmethod
def universal(cls) -> Container[_T]:
"""A container that contains everything."""
return BooleanContainer(lambda _: True)
@classmethod
def empty(cls) -> Container[_T]:
"""A container that contains nothing."""
return BooleanContainer(lambda _: False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment