Skip to content

Commit 681bd51

Browse files
committed
Fix IndexError with maxheadercolwidths on empty tables
When maxheadercolwidths is set and the table has no data rows, list_of_lists[0] raises an IndexError since the list is empty. Fall back to len(headers) when list_of_lists is empty to determine the number of columns, matching how maxcolwidths already handles the same scenario.
1 parent 74885be commit 681bd51

File tree

1 file changed

+17
-11
lines changed

1 file changed

+17
-11
lines changed

tabulate/__init__.py

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2262,18 +2262,24 @@ def tabulate(
22622262
)
22632263

22642264
if maxheadercolwidths is not None:
2265-
num_cols = len(list_of_lists[0])
2266-
if isinstance(maxheadercolwidths, int): # Expand scalar for all columns
2267-
maxheadercolwidths = _expand_iterable(
2268-
maxheadercolwidths, num_cols, maxheadercolwidths
2269-
)
2270-
else: # Ignore col width for any 'trailing' columns
2271-
maxheadercolwidths = _expand_iterable(maxheadercolwidths, num_cols, None)
2265+
if len(list_of_lists):
2266+
num_cols = len(list_of_lists[0])
2267+
elif len(headers):
2268+
num_cols = len(headers)
2269+
else:
2270+
num_cols = 0
2271+
if num_cols:
2272+
if isinstance(maxheadercolwidths, int): # Expand scalar for all columns
2273+
maxheadercolwidths = _expand_iterable(
2274+
maxheadercolwidths, num_cols, maxheadercolwidths
2275+
)
2276+
else: # Ignore col width for any 'trailing' columns
2277+
maxheadercolwidths = _expand_iterable(maxheadercolwidths, num_cols, None)
22722278

2273-
numparses = _expand_numparse(disable_numparse, num_cols)
2274-
headers = _wrap_text_to_colwidths(
2275-
[headers], maxheadercolwidths, numparses=numparses, break_long_words=break_long_words, break_on_hyphens=break_on_hyphens
2276-
)[0]
2279+
numparses = _expand_numparse(disable_numparse, num_cols)
2280+
headers = _wrap_text_to_colwidths(
2281+
[headers], maxheadercolwidths, numparses=numparses, break_long_words=break_long_words, break_on_hyphens=break_on_hyphens
2282+
)[0]
22772283

22782284
# empty values in the first column of RST tables should be escaped (issue #82)
22792285
# "" should be escaped as "\\ " or ".."

0 commit comments

Comments
 (0)