From 9829ac2afd9283758c2cb20dc9271f3e8c6c38c6 Mon Sep 17 00:00:00 2001 From: xbrxr03 Date: Mon, 22 Jun 2026 02:32:30 -0400 Subject: [PATCH] fix: prevent KeyError when clearing and re-rendering DataTable (fixes #4900) --- src/textual/widgets/_data_table.py | 2 ++ tests/test_data_table.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/src/textual/widgets/_data_table.py b/src/textual/widgets/_data_table.py index dd5f9c6d72..70ab42a89e 100644 --- a/src/textual/widgets/_data_table.py +++ b/src/textual/widgets/_data_table.py @@ -1592,6 +1592,8 @@ def clear(self, columns: bool = False) -> Self: self._y_offsets.clear() self._data.clear() self.rows.clear() + self._updated_cells.clear() + self._new_rows.clear() self._row_locations = TwoWayDict({}) if columns: self.columns.clear() diff --git a/tests/test_data_table.py b/tests/test_data_table.py index 6750c5ddbc..8fe4f397f4 100644 --- a/tests/test_data_table.py +++ b/tests/test_data_table.py @@ -1139,6 +1139,36 @@ async def test_reuse_row_key_after_clear(): assert table.get_row("ROW2") == [7, 8] +async def test_clear_clears_updated_cells_and_new_rows(): + """Regression test for https://github.com/Textualize/textual/issues/4900 + + After clear(), _updated_cells and _new_rows should be empty to prevent + stale RowKey references from causing KeyError on re-render. + """ + app = DataTableApp() + async with app.run_test(): + table = app.query_one(DataTable) + cols = table.add_columns("A", "B") + row = table.add_row("hello", "world") + table.update_cell(row, cols[0], "updated", update_width=True) + + # _updated_cells and _new_rows should have entries after adding/updating + assert len(table._updated_cells) > 0 + assert len(table._new_rows) > 0 + + # clear() should remove stale references + table.clear() + + assert len(table._updated_cells) == 0, ( + f"_updated_cells should be empty after clear, " + f"got {table._updated_cells}" + ) + assert len(table._new_rows) == 0, ( + f"_new_rows should be empty after clear, " + f"got {table._new_rows}" + ) + + async def test_reuse_column_key_after_clear(): """Regression test for https://github.com/Textualize/textual/issues/1806""" app = DataTableApp()