Skip to content

Commit

Permalink
fix(python): raise appropriate error from newly-optimised item on i…
Browse files Browse the repository at this point in the history
…nvalid (out of bounds) column index (pola-rs#10415)
  • Loading branch information
alexander-beedie authored Aug 11, 2023
1 parent 5249cb1 commit b3db64f
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 10 deletions.
13 changes: 7 additions & 6 deletions py-polars/polars/dataframe/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -1569,9 +1569,7 @@ def __getitem__(
if (col_selection >= 0 and col_selection >= self.width) or (
col_selection < 0 and col_selection < -self.width
):
raise ValueError(
f'Column index "{col_selection}" is out of bounds.'
)
raise ValueError(f"column index {col_selection!r} is out of bounds")
series = self.to_series(col_selection)
return series[row_selection]

Expand Down Expand Up @@ -1786,13 +1784,16 @@ def item(self, row: int | None = None, column: int | str | None = None) -> Any:
return self._df.select_at_idx(0).get_idx(0)

elif row is None or column is None:
raise ValueError("Cannot call '.item()' with only one of 'row' or 'column'")
raise ValueError("cannot call `.item()` with only one of `row` or `column`")

return (
s = (
self._df.select_at_idx(column)
if isinstance(column, int)
else self._df.column(column)
).get_idx(row)
)
if s is None:
raise ValueError(f"column index {column!r} is out of bounds")
return s.get_idx(row)

def to_arrow(self) -> pa.Table:
"""
Expand Down
2 changes: 1 addition & 1 deletion py-polars/polars/functions/lazy.py
Original file line number Diff line number Diff line change
Expand Up @@ -748,7 +748,7 @@ def last(column: str | Series | None = None) -> Expr:
if column.len() > 0:
return column[-1]
else:
raise IndexError("The series is empty, so no last value can be returned,")
raise IndexError("the series is empty, so no last value can be returned")
return col(column).last()


Expand Down
8 changes: 5 additions & 3 deletions py-polars/tests/unit/dataframe/test_df.py
Original file line number Diff line number Diff line change
Expand Up @@ -3253,22 +3253,24 @@ def test_item() -> None:
assert df.item() == 1

df = pl.DataFrame({"a": [1, 2]})
with pytest.raises(ValueError):
with pytest.raises(ValueError, match=r".* frame has shape \(2, 1\)"):
df.item()

assert df.item(0, 0) == 1
assert df.item(1, "a") == 2

df = pl.DataFrame({"a": [1], "b": [2]})
with pytest.raises(ValueError):
with pytest.raises(ValueError, match=r".* frame has shape \(1, 2\)"):
df.item()

assert df.item(0, "a") == 1
assert df.item(0, "b") == 2

df = pl.DataFrame({})
with pytest.raises(ValueError):
with pytest.raises(ValueError, match=r".* frame has shape \(0, 0\)"):
df.item()
with pytest.raises(ValueError, match="column index 10 is out of bounds"):
df.item(0, 10)


@pytest.mark.parametrize(
Expand Down

0 comments on commit b3db64f

Please sign in to comment.