Skip to content

Commit

Permalink
proposal: implement __bool__ for pl.Expr (#1368)
Browse files Browse the repository at this point in the history
  • Loading branch information
wseaton committed Sep 16, 2021
1 parent 6a8d202 commit 72b790b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
6 changes: 6 additions & 0 deletions py-polars/polars/lazy/expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,12 @@ def __to_expr(self, other: Any) -> "Expr":
return other
return lit(other)

def __bool__(self) -> "Expr":
raise ValueError(
"Since Expr are lazy, the truthiness of an Expr is ambiguous. \
Hint: use '&' or '|' to chain Expr together, not and/or."
)

def __invert__(self) -> "Expr":
return self.is_not()

Expand Down
13 changes: 13 additions & 0 deletions py-polars/tests/test_lazy.py
Original file line number Diff line number Diff line change
Expand Up @@ -549,3 +549,16 @@ def test_argminmax():
)
assert out["max"][0] == 4
assert out["min"][0] == 0


def test_expr_bool_cmp():
# Since expressions are lazy they should not be evaluated as
# bool(x), this has the nice side effect of throwing an error
# if someone tries to chain them via the and|or operators
df = pl.DataFrame({"a": [1, 2, 3, 4, 5], "b": [1, 2, 3, 4, 5]})

with pytest.raises(ValueError):
df[[pl.col("a").gt(pl.col("b")) and pl.col("b").gt(pl.col("b"))]]

with pytest.raises(ValueError):
df[[pl.col("a").gt(pl.col("b")) or pl.col("b").gt(pl.col("b"))]]

0 comments on commit 72b790b

Please sign in to comment.