Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(python): Allow is_in values to be given as custom Collection #20801

Merged
merged 1 commit into from
Jan 20, 2025
Merged
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
4 changes: 2 additions & 2 deletions py-polars/polars/expr/expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -5807,8 +5807,8 @@ def is_in(self, other: Expr | Collection[Any] | Series) -> Expr:
└───────────┴──────────────────┴──────────┘
"""
if isinstance(other, Collection) and not isinstance(other, str):
if isinstance(other, (set, frozenset)):
other = list(other)
if not isinstance(other, (Sequence, pl.Series)):
other = list(other) # eg: set, frozenset
other = F.lit(pl.Series(other))._pyexpr
else:
other = parse_into_expression(other)
Expand Down
34 changes: 34 additions & 0 deletions py-polars/tests/unit/operations/test_is_in.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

from collections.abc import Collection
from datetime import date
from decimal import Decimal as D
from typing import TYPE_CHECKING
Expand All @@ -12,6 +13,8 @@
from polars.testing import assert_frame_equal, assert_series_equal

if TYPE_CHECKING:
from collections.abc import Iterator

from polars._typing import PolarsDataType


Expand Down Expand Up @@ -426,3 +429,34 @@ def test_is_in_decimal() -> None:
assert pl.DataFrame({"a": [D("0.0"), D("0.2"), D("0.1")]}).select(
pl.col("a").is_in([1, 0, 2])
)["a"].to_list() == [True, False, False]


def test_is_in_collection() -> None:
df = pl.DataFrame(
{
"lbl": ["aa", "bb", "cc", "dd", "ee"],
"val": [0, 1, 2, 3, 4],
}
)

class CustomCollection(Collection[int]):
def __init__(self, vals: Collection[int]) -> None:
super().__init__()
self.vals = vals

def __contains__(self, x: object) -> bool:
return x in self.vals

def __iter__(self) -> Iterator[int]:
yield from self.vals

def __len__(self) -> int:
return len(self.vals)

for constraint_values in (
{3, 2, 1},
frozenset({3, 2, 1}),
CustomCollection([3, 2, 1]),
):
res = df.filter(pl.col("val").is_in(constraint_values))
assert set(res["lbl"]) == {"bb", "cc", "dd"}
Loading