from enum import Enum
from dataclasses import dataclass
from .util import is_value_equal
from .value import Value
__all__ = (
'Comp',
'Predicate',
)
[docs]
class Comp(Enum):
"""
A comparison operator for predicates.
"""
EQ = '='
"""Compare whether the target value is equal to the predicate value."""
NE = '<>'
"""Compare whether the target value is not equal to the predicate value."""
LT = '<'
"""Compare whether the target value is less than the predicate value."""
LE = '<='
"""Compare whether the target value is less than or equal to the predicate value."""
GT = '>'
"""Compare whether the target value is greater than the predicate value."""
GE = '>='
"""Compare whether the target value is greater than or equal to the predicate value."""
[docs]
@dataclass(frozen=True, slots=True)
class Predicate:
"""
A predicate for evaluating a value.
Attributes:
name: the name of the attribute
comp: the comparison operator
value: the reference value of the predicate
"""
name: str
comp: Comp
value: Value
[docs]
def evaluate(self, value: Value) -> bool:
"""
Evaluate whether a value satisfies the predicate.
"""
equal = is_value_equal(value, self.value)
match self.comp:
case Comp.EQ:
return equal
case Comp.NE:
return not equal
case Comp.LT:
return value < self.value # type: ignore
case Comp.LE:
return equal or (value < self.value) # type: ignore
case Comp.GT:
return value > self.value # type: ignore
case Comp.GE:
return equal or (value > self.value) # type: ignore
case _: # pragma: no cover
assert False
def verbose(self) -> str: # pragma: no cover
return f"{self.name}{self.comp.value}{self.value}"