Source code for phantom.predicates.boolean

from typing import Iterable
from typing import Literal

from .base import Predicate
from .base import T


[docs]def true(_value: object, /) -> Literal[True]: """Always return :py:const:`True`.""" return True
[docs]def false(_value: object, /) -> Literal[False]: """Always return :py:const:`False`.""" return False
[docs]def negate(predicate: Predicate[T]) -> Predicate[T]: """Negate a given predicate.""" def check(value: T, /) -> bool: return not predicate(value) return check
[docs]def truthy(value: object, /) -> bool: """Return :py:const:`True` for truthy objects.""" return bool(value)
[docs]def falsy(value: object, /) -> bool: """Return :py:const:`True` for falsy objects.""" return negate(truthy)(value)
[docs]def both(p: Predicate[T], q: Predicate[T]) -> Predicate[T]: """ Create a new predicate that succeeds when both of the given predicates succeed. """ def check(value: T, /) -> bool: return p(value) and q(value) return check
[docs]def either(p: Predicate[T], q: Predicate[T]) -> Predicate[T]: """ Create a new predicate that succeeds when at least one of the given predicates succeed. """ def check(value: T, /) -> bool: return p(value) or q(value) return check
[docs]def xor(p: Predicate[T], q: Predicate[T]) -> Predicate[T]: """ Create a new predicate that succeeds when one of the given predicates succeed, but not both. """ def check(value: T, /) -> bool: return p(value) ^ q(value) return check
[docs]def all_of(predicates: Iterable[Predicate[T]]) -> Predicate[T]: """Create a new predicate that succeeds when all of the given predicates succeed.""" predicates = tuple(predicates) def check(value: T, /) -> bool: return all(p(value) for p in predicates) return check
[docs]def any_of(predicates: Iterable[Predicate[T]]) -> Predicate[T]: """ Create a new predicate that succeeds when at least one of the given predicates succeed. """ predicates = tuple(predicates) def check(value: T, /) -> bool: return any(p(value) for p in predicates) return check
[docs]def one_of(predicates: Iterable[Predicate[T]]) -> Predicate[T]: """ Create a new predicate that succeeds when exactly one of the given predicates succeed. """ predicates = tuple(predicates) def check(value: T, /) -> bool: return 1 == sum(p(value) for p in predicates) return check