Skip to content

Commit 68a08b1

Browse files
authored
Add syntactic sugar for and and or operation (apache#1697)
I got inspired by Arrow that also allows for this.
1 parent f1c1f8f commit 68a08b1

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

pyiceberg/expressions/__init__.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,20 @@ class BooleanExpression(ABC):
6464
def __invert__(self) -> BooleanExpression:
6565
"""Transform the Expression into its negated version."""
6666

67+
def __and__(self, other: BooleanExpression) -> BooleanExpression:
68+
"""Perform and operation on another expression."""
69+
if not isinstance(other, BooleanExpression):
70+
raise ValueError(f"Expected BooleanExpression, got: {other}")
71+
72+
return And(self, other)
73+
74+
def __or__(self, other: BooleanExpression) -> BooleanExpression:
75+
"""Perform or operation on another expression."""
76+
if not isinstance(other, BooleanExpression):
77+
raise ValueError(f"Expected BooleanExpression, got: {other}")
78+
79+
return Or(self, other)
80+
6781

6882
class Term(Generic[L], ABC):
6983
"""A simple expression that evaluates to a value."""

tests/expressions/test_expressions.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -698,21 +698,35 @@ def test_and() -> None:
698698
null = IsNull(Reference("a"))
699699
nan = IsNaN(Reference("b"))
700700
and_ = And(null, nan)
701+
702+
# Some syntactic sugar
703+
assert and_ == null & nan
704+
701705
assert str(and_) == f"And(left={str(null)}, right={str(nan)})"
702706
assert repr(and_) == f"And(left={repr(null)}, right={repr(nan)})"
703707
assert and_ == eval(repr(and_))
704708
assert and_ == pickle.loads(pickle.dumps(and_))
705709

710+
with pytest.raises(ValueError, match="Expected BooleanExpression, got: abc"):
711+
null & "abc" # type: ignore
712+
706713

707714
def test_or() -> None:
708715
null = IsNull(Reference("a"))
709716
nan = IsNaN(Reference("b"))
710717
or_ = Or(null, nan)
718+
719+
# Some syntactic sugar
720+
assert or_ == null | nan
721+
711722
assert str(or_) == f"Or(left={str(null)}, right={str(nan)})"
712723
assert repr(or_) == f"Or(left={repr(null)}, right={repr(nan)})"
713724
assert or_ == eval(repr(or_))
714725
assert or_ == pickle.loads(pickle.dumps(or_))
715726

727+
with pytest.raises(ValueError, match="Expected BooleanExpression, got: abc"):
728+
null | "abc" # type: ignore
729+
716730

717731
def test_not() -> None:
718732
null = IsNull(Reference("a"))

0 commit comments

Comments
 (0)