Repository: Textualize/textual

Issue:
DataTable.add_row gives misleading error with too many arguments.
Create a DataTable with one column.   Do a `table.add_row("A", "B")`.  
Get `AttributeError: 'NoneType' object has no attribute 'key'`, which is an odd error.
Instead I should get `ValueError:  Too many column values provided to add_row`

Caused by  widgets/_data_table.py:1583, `for column, cell in zip_longest(self.ordered_columns, cells)`

Will put in  a PR that checks the length and puts an error message that doesn't have me pull hair out for ten minutes.


Discussion:

Patch:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ed46c3a9f..70011f7fc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
 ### Added
 
 - `TextArea.line_number_start` reactive attribute https://github.com/Textualize/textual/pull/4471
+- Raise `ValueError` with improved error message when number of cells inserted using `DataTable.add_row` doesn't match the number of columns in the table https://github.com/Textualize/textual/pull/4742
 
 ### Fixed
 
diff --git a/src/textual/widgets/_data_table.py b/src/textual/widgets/_data_table.py
index 4d335feca..ee77bddbe 100644
--- a/src/textual/widgets/_data_table.py
+++ b/src/textual/widgets/_data_table.py
@@ -1576,6 +1576,9 @@ class DataTable(ScrollView, Generic[CellType], can_focus=True):
         #  If we don't do this, users will be required to call add_column(s)
         #  Before they call add_row.
 
+        if len(cells) > len(self.ordered_columns):
+            raise ValueError("More values provided than there are columns.")
+
         row_index = self.row_count
         # Map the key of this row to its current index
         self._row_locations[row_key] = row_index


Test patch:
diff --git a/tests/test_data_table.py b/tests/test_data_table.py
index 1320d853f..63736e519 100644
--- a/tests/test_data_table.py
+++ b/tests/test_data_table.py
@@ -254,6 +254,14 @@ async def test_add_row_duplicate_key():
         with pytest.raises(DuplicateKey):
             table.add_row("2", key="1")  # Duplicate row key
 
+async def test_add_row_too_many_values():
+    app = DataTableApp()
+    async with app.run_test():
+        table = app.query_one(DataTable)
+        table.add_column("A")
+        table.add_row("1", key="1")
+        with pytest.raises(ValueError):
+            table.add_row("1", "2")
 
 async def test_add_column_duplicate_key():
     app = DataTableApp()