Skip to content

Commit e8e3091

Browse files
committed
Wordwrapping should now work when provided with a datetime a cell to
wrap
1 parent bbb8317 commit e8e3091

File tree

2 files changed

+40
-2
lines changed

2 files changed

+40
-2
lines changed

tabulate.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1230,7 +1230,13 @@ def _wrap_text_to_colwidths(list_of_lists, colwidths, numparses=True):
12301230

12311231
if width is not None:
12321232
wrapper = _CustomTextWrap(width=width)
1233-
wrapped = wrapper.wrap(cell)
1233+
# Cast based on our internal type handling
1234+
# Any future custom formatting of types (such as datetimes)
1235+
# may need to be more explict than just `str` of the object
1236+
casted_cell = (
1237+
str(cell) if _isnumber(cell) else _type(cell, numparse)(cell)
1238+
)
1239+
wrapped = wrapper.wrap(casted_cell)
12341240
new_row.append("\n".join(wrapped))
12351241
else:
12361242
new_row.append(cell)
@@ -1862,6 +1868,7 @@ class _CustomTextWrap(textwrap.TextWrapper):
18621868

18631869
def __init__(self, *args, **kwargs):
18641870
self._active_codes = []
1871+
self.max_lines = None # For python2 compatibility
18651872
textwrap.TextWrapper.__init__(self, *args, **kwargs)
18661873

18671874
@staticmethod

test/test_textwrapper.py

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
# -*- coding: utf-8 -*-
22

33
"""Discretely test functionality of our custom TextWrapper"""
4+
from __future__ import unicode_literals
45

5-
from tabulate import _CustomTextWrap as CTW
6+
import datetime
7+
8+
from tabulate import _CustomTextWrap as CTW, tabulate
69
from textwrap import TextWrapper as OTW
710

811
from common import skip, assert_equal
@@ -155,3 +158,31 @@ def test_wrap_color_line_splillover():
155158
wrapper = CTW(width=25)
156159
result = wrapper.wrap(data)
157160
assert_equal(expected, result)
161+
162+
163+
def test_wrap_datetime():
164+
"""TextWrapper: Show that datetimes can be wrapped without crashing"""
165+
data = [
166+
["First Entry", datetime.datetime(2020, 1, 1, 5, 6, 7)],
167+
["Second Entry", datetime.datetime(2021, 2, 2, 0, 0, 0)],
168+
]
169+
headers = ["Title", "When"]
170+
result = tabulate(data, headers=headers, tablefmt="grid", maxcolwidths=[7, 5])
171+
172+
expected = [
173+
"+---------+--------+",
174+
"| Title | When |",
175+
"+=========+========+",
176+
"| First | 2020- |",
177+
"| Entry | 01-01 |",
178+
"| | 05:06 |",
179+
"| | :07 |",
180+
"+---------+--------+",
181+
"| Second | 2021- |",
182+
"| Entry | 02-02 |",
183+
"| | 00:00 |",
184+
"| | :00 |",
185+
"+---------+--------+",
186+
]
187+
expected = "\n".join(expected)
188+
assert_equal(expected, result)

0 commit comments

Comments
 (0)