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): Raise if pass a negative n into clear #15432

Merged
merged 2 commits into from
Apr 3, 2024
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
17 changes: 9 additions & 8 deletions py-polars/polars/dataframe/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -6912,17 +6912,18 @@ def clear(self, n: int = 0) -> Self:
│ null ┆ null ┆ null │
└──────┴──────┴──────┘
"""
if n < 0:
msg = f"`n` should be greater than or equal to 0, got {n}"
raise ValueError(msg)
# faster path
if n == 0:
return self._from_pydf(self._df.clear())
if n > 0 or len(self) > 0:
return self.__class__(
{
nm: pl.Series(name=nm, dtype=tp).extend_constant(None, n)
for nm, tp in self.schema.items()
}
)
return self.clone()
return self.__class__(
{
nm: pl.Series(name=nm, dtype=tp).extend_constant(None, n)
for nm, tp in self.schema.items()
}
)

def clone(self) -> Self:
"""
Expand Down
4 changes: 4 additions & 0 deletions py-polars/polars/series/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -4759,6 +4759,10 @@ def clear(self, n: int = 0) -> Series:
null
]
"""
if n < 0:
msg = f"`n` should be greater than or equal to 0, got {n}"
raise ValueError(msg)
# faster path
if n == 0:
return self._from_pyseries(self._s.clear())
s = (
Expand Down
10 changes: 10 additions & 0 deletions py-polars/tests/unit/operations/test_clear.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,13 @@ def test_clear_series_object_starting_with_null() -> None:
assert result.dtype == s.dtype
assert result.name == s.name
assert result.is_empty()


def test_clear_raise_negative_n() -> None:
s = pl.Series([1, 2, 3])

msg = "`n` should be greater than or equal to 0, got -1"
with pytest.raises(ValueError, match=msg):
s.clear(-1)
with pytest.raises(ValueError, match=msg):
s.to_frame().clear(-1)
Loading