Skip to content

🐛 Resolved issue for data getter when datagrid is empty #358

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

Merged
merged 3 commits into from
Nov 2, 2022
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
7 changes: 6 additions & 1 deletion ipydatagrid/datagrid.py
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,12 @@ def __handle_custom_msg(self, _, content, buffers): # noqa: U101,U100
@property
def data(self):
trimmed_primary_key = self._data["schema"]["primaryKey"][:-1]
df = pd.DataFrame(self._data["data"])
if self._data["data"]:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if self._data["data"]:
if "data" in self._data:

If the "data" key doesn't exist in self._data then self._data["data"] will throw an error. This is a bit safer 😊

df = pd.DataFrame(self._data["data"])
else:
df = pd.DataFrame(
{value["name"]: [] for value in self._data["schema"]["fields"]}
)
final_df = df.set_index(trimmed_primary_key)
final_df = final_df[final_df.columns[:-1]]
return final_df
Expand Down
21 changes: 19 additions & 2 deletions tests/test_datagrid.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,26 @@ def test_selections(clear: bool, dataframe: pd.DataFrame) -> None:
]


def test_data_getter(dataframe) -> None:
@pytest.mark.parametrize("drop_rows", [True, False])
def test_data_getter(drop_rows: bool, dataframe: pd.DataFrame) -> None:
"""Testing data getter of DataGrid to check it can be called when there is
data and when there isn't data (i.e. all rows have been deleted in the
dataframe).

Args:
drop_rows (bool): boolean determining whether to drop rows in dataframe.
dataframe (pd.DataFrame): initial dataframe passed.
"""
grid = DataGrid(dataframe)
assert grid.data.equals(dataframe)
if drop_rows:
grid.data = grid.data.drop(["One", "Two", "Three"]) # Drop all rows
grid_data = grid.data # calling data getter
assert list(grid_data.columns) == ["A", "B"]
assert grid_data.index.name == "key"
assert list(grid_data.values) == []
else:
grid_data = grid.data
assert grid_data.equals(dataframe)


def test_data_setter(dataframe) -> None:
Expand Down