Skip to content

Commit 4505076

Browse files
committed
fix bug if list empty or first item is None
1 parent fd3af44 commit 4505076

File tree

3 files changed

+33
-12
lines changed

3 files changed

+33
-12
lines changed

pyduplicate/data/utils.py

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ def __init__(self, lst: list) -> None:
1515
self.indexes = {}
1616
self.lst = lst
1717
self.item_type = list
18+
if not self.lst:
19+
raise IndexError(f'You must not supply an empty list')
1820

1921
def create_list(self, key: str) -> None:
2022
"""
@@ -26,25 +28,27 @@ def create_list(self, key: str) -> None:
2628

2729
def get_type(self) -> None:
2830
"""
29-
Get the type of the first item
31+
Get the type of the first item which is not None
3032
"""
31-
item = self.lst[0]
32-
if isinstance(item, (int, float)):
33-
self.item_type = (int, float)
34-
elif isinstance(item, str):
35-
self.item_type = str
36-
elif isinstance(item, dict):
37-
self.item_type = dict
38-
elif isinstance(item, tuple):
39-
self.item_type = tuple
33+
for item in self.lst:
34+
if item:
35+
if isinstance(item, (int, float)):
36+
self.item_type = (int, float)
37+
elif isinstance(item, str):
38+
self.item_type = str
39+
elif isinstance(item, dict):
40+
self.item_type = dict
41+
elif isinstance(item, tuple):
42+
self.item_type = tuple
43+
break
4044

4145
def validate_items(self) -> None:
4246
"""
4347
Check if all items are of the same type
4448
4549
:raise TypeError: If items are NOT of the same type
4650
"""
47-
if not all(isinstance(x, self.item_type) for x in self.lst):
51+
if not all(isinstance(x, self.item_type) for x in self.lst if x):
4852
raise TypeError(f'An item has a different type than the others')
4953

5054
def create_update_feedback(self, index: int, value: any,

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
setup(
77
name="python-duplicate",
8-
version="1.0.2",
8+
version="1.0.4",
99
url="https://github.com/Clement-O/python-duplicate",
1010
license="MIT",
1111
author="Clément Omont--Agnes",

test/data/test_utils.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,23 @@
88

99
class TestUtils(unittest.TestCase):
1010

11+
def test_init_error(self):
12+
with self.assertRaises(IndexError):
13+
Utils([])
14+
15+
def test_get_type(self):
16+
value = [{}, {'id': 1}]
17+
utils = Utils(value)
18+
utils.create_list('id')
19+
utils.get_type()
20+
self.assertEqual(utils.item_type, (int, float))
21+
22+
value = [{}, {}]
23+
utils = Utils(value)
24+
utils.create_list('id')
25+
utils.get_type()
26+
self.assertEqual(utils.item_type, list) # default type
27+
1128
def test_validate_items(self):
1229
# mixed list (and dict without key)
1330
for index, value in enumerate(test_const.LIST_ERROR):

0 commit comments

Comments
 (0)