Skip to content

Commit d81c20d

Browse files
committed
provide a parameter that allows for controlling header maxcolwidth
1 parent b2c26bc commit d81c20d

File tree

3 files changed

+24
-0
lines changed

3 files changed

+24
-0
lines changed

tabulate.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1251,6 +1251,7 @@ def tabulate(
12511251
disable_numparse=False,
12521252
colalign=None,
12531253
maxcolwidths=None,
1254+
maxheadercolwidths=None,
12541255
):
12551256
"""Format a fixed width table for pretty printing.
12561257
@@ -1572,6 +1573,7 @@ def tabulate(
15721573
| | | better if it is wrapped a bit |
15731574
+------------+------------+-------------------------------+
15741575
1576+
Header column width can be specified in a similar way using `maxheadercolwidth`
15751577
15761578
"""
15771579

@@ -1593,6 +1595,19 @@ def tabulate(
15931595
list_of_lists, maxcolwidths, numparses=numparses
15941596
)
15951597

1598+
if maxheadercolwidths is not None:
1599+
num_cols = len(list_of_lists[0])
1600+
if isinstance(maxheadercolwidths, int): # Expand scalar for all columns
1601+
maxheadercolwidths = _expand_iterable(maxheadercolwidths, num_cols, maxheadercolwidths)
1602+
else: # Ignore col width for any 'trailing' columns
1603+
maxheadercolwidths = _expand_iterable(maxheadercolwidths, num_cols, None)
1604+
1605+
numparses = _expand_numparse(disable_numparse, num_cols)
1606+
headers = _wrap_text_to_colwidths(
1607+
[headers], maxheadercolwidths, numparses=numparses
1608+
)[0]
1609+
1610+
15961611
# empty values in the first column of RST tables should be escaped (issue #82)
15971612
# "" should be escaped as "\\ " or ".."
15981613
if tablefmt == "rst":

test/test_api.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ def test_tabulate_signature():
5656
("disable_numparse", False),
5757
("colalign", None),
5858
("maxcolwidths", None),
59+
("maxheadercolwidths", None),
5960
]
6061
_check_signature(tabulate, expected_sig)
6162

test/test_output.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,14 @@ def test_maxcolwidth_honor_disable_parsenum():
200200
result = tabulate(table, tablefmt="grid", maxcolwidths=6, disable_numparse=[2])
201201
assert_equal(expected, result)
202202

203+
def test_plain_maxheadercolwidths_autowraps():
204+
"Output: maxheadercolwidths will result in autowrapping header cell"
205+
table = [["hdr", "fold"], ["1", "very long data"]]
206+
expected = "\n".join([" hdr fo"," ld", " 1 very long", " data"])
207+
result = tabulate(
208+
table, headers="firstrow", tablefmt="plain", maxcolwidths=[10, 10], maxheadercolwidths=[None, 2]
209+
)
210+
assert_equal(expected, result)
203211

204212
def test_simple():
205213
"Output: simple with headers"

0 commit comments

Comments
 (0)