Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions pyiceberg/expressions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,13 @@ def _to_literal(value: L | Literal[L]) -> Literal[L]:
class BooleanExpression(IcebergBaseModel, ABC):
"""An expression that evaluates to a boolean."""

def __bool__(self) -> bool:
"""Raise an error to prevent truthiness evaluation of non-constant expressions."""
raise TypeError(
f"Cannot evaluate truthiness of non-constant BooleanExpression: {self}. "
"Use bitwise operators (~, &, |) for expressions or comparison with AlwaysTrue()/AlwaysFalse()."
)

@abstractmethod
def __invert__(self) -> BooleanExpression:
"""Transform the Expression into its negated version."""
Expand Down Expand Up @@ -452,6 +459,10 @@ class AlwaysTrue(BooleanExpression, Singleton, IcebergRootModel[bool]):

root: bool = True

def __bool__(self) -> bool:
"""Return True for AlwaysTrue."""
return True

def __invert__(self) -> AlwaysFalse:
"""Transform the Expression into its negated version."""
return AlwaysFalse()
Expand All @@ -470,6 +481,10 @@ class AlwaysFalse(BooleanExpression, Singleton, IcebergRootModel[bool]):

root: bool = False

def __bool__(self) -> bool:
"""Return False for AlwaysFalse."""
return False

def __invert__(self) -> AlwaysTrue:
"""Transform the Expression into its negated version."""
return AlwaysTrue()
Expand Down
41 changes: 41 additions & 0 deletions tests/expressions/test_expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -1397,6 +1397,47 @@ def test_deepcopy_then_pickle() -> None:
assert restored == expr


def test_always_true_truthiness() -> None:
expr = AlwaysTrue()
assert bool(expr) is True
assert (not expr) is False
executed = False
if expr:
executed = True
assert executed is True


def test_always_false_truthiness() -> None:
expr = AlwaysFalse()
assert bool(expr) is False
assert (not expr) is True
executed = False
if not expr:
executed = True
assert executed is True


@pytest.mark.parametrize(
"expr",
[
EqualTo("a", 1),
NotEqualTo("a", 1),
And(AlwaysTrue(), EqualTo("a", 1)),
Or(AlwaysFalse(), EqualTo("a", 1)),
Not(EqualTo("a", 1)),
In("a", (1, 2)),
NotIn("a", (1, 2)),
],
)
def test_non_constant_boolean_expression_truthiness_raises(expr: BooleanExpression) -> None:
with pytest.raises(TypeError, match="Cannot evaluate truthiness of non-constant BooleanExpression"):
bool(expr)

with pytest.raises(TypeError, match="Cannot evaluate truthiness of non-constant BooleanExpression"):
if expr:
pass


# __ __ ___
# | \/ |_ _| _ \_ _
# | |\/| | || | _/ || |
Expand Down
Loading