From ce279fcd4597a0d911b9da3c024f248c7d66f106 Mon Sep 17 00:00:00 2001 From: Francesco Witte Date: Mon, 15 Apr 2024 09:02:45 +0200 Subject: [PATCH 1/2] Add a type check for the sheetname If you provide a non-string type as sheetname, e.g. integer or you end up with an error message, that tells that a variable of type int does not have a len. Especially for python beginners this is kind of difficult to understand, so I'd prefer having a clear message, to what the issue actually is. --- xlsxwriter/workbook.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/xlsxwriter/workbook.py b/xlsxwriter/workbook.py index c0994a7d0..708ffbddf 100644 --- a/xlsxwriter/workbook.py +++ b/xlsxwriter/workbook.py @@ -841,6 +841,11 @@ def _check_sheetname(self, sheetname, is_chartsheet=False): else: sheetname = self.sheet_name + str(self.sheetname_count) + if not isinstance(sheetname, str): + raise TypeError( + "The sheet name must be of type str, is type %s." % type(sheetname) + ) + # Check that sheet sheetname is <= 31. Excel limit. if len(sheetname) > 31: raise InvalidWorksheetName( From 51842d8df5eafba32a9ceda0695d330a28532d9c Mon Sep 17 00:00:00 2001 From: Francesco Witte Date: Mon, 15 Apr 2024 09:29:22 +0200 Subject: [PATCH 2/2] Add a test for the new exception --- xlsxwriter/test/workbook/test_check_sheetname.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/xlsxwriter/test/workbook/test_check_sheetname.py b/xlsxwriter/test/workbook/test_check_sheetname.py index 25a54bf16..62e84f670 100644 --- a/xlsxwriter/test/workbook/test_check_sheetname.py +++ b/xlsxwriter/test/workbook/test_check_sheetname.py @@ -40,6 +40,12 @@ def test_check_sheetname(self): exp = "Sheet4" self.assertEqual(got, exp) + def test_check_sheetname_with_incorrect_dtype(self): + """Test the _check_sheetname() method with exception""" + + name = 42 + self.assertRaises(TypeError, self.workbook._check_sheetname, name) + def test_check_sheetname_with_long_name(self): """Test the _check_sheetname() method with exception"""