Skip to content

Commit 541afc6

Browse files
authored
Merge pull request astanin#342 from astanin/pr-79
Merge changes from Pull Request astanin#79 (preserve_whitespace as an argument to tabulate())
2 parents ee0472e + 0d5d30e commit 541afc6

File tree

6 files changed

+59
-31
lines changed

6 files changed

+59
-31
lines changed

README.md

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ When data is a list of dictionaries, a dictionary can be passed as `headers`
131131
to replace the keys with other column labels:
132132

133133
```pycon
134-
>>> print(tabulate([{1: "Alice", 2: 24}, {1: "Bob", 2: 19}],
134+
>>> print(tabulate([{1: "Alice", 2: 24}, {1: "Bob", 2: 19}],
135135
... headers={1: "Name", 2: "Age"}))
136136
Name Age
137137
------ -----
@@ -739,13 +739,8 @@ column, in which case every column may have different number formatting:
739739
### Text formatting
740740

741741
By default, `tabulate` removes leading and trailing whitespace from text
742-
columns. To disable whitespace removal, set the global module-level flag
743-
`PRESERVE_WHITESPACE`:
744-
745-
```python
746-
import tabulate
747-
tabulate.PRESERVE_WHITESPACE = True
748-
```
742+
columns. To disable whitespace removal, pass `preserve_whitespace=True`.
743+
Older versions of the library used a global module-level flag PRESERVE_WHITESPACE.
749744

750745
### Wide (fullwidth CJK) symbols
751746

tabulate/__init__.py

Lines changed: 38 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,6 @@ def _is_file(f):
3333
# minimum extra space in headers
3434
MIN_PADDING = 2
3535

36-
# Whether or not to preserve leading/trailing whitespace in data.
37-
PRESERVE_WHITESPACE = False
38-
3936
_DEFAULT_FLOATFMT = "g"
4037
_DEFAULT_INTFMT = ""
4138
_DEFAULT_MISSINGVAL = ""
@@ -163,7 +160,6 @@ def _grid_line_with_colons(colwidths, colaligns):
163160
return "+" + "+".join(segments) + "+"
164161

165162

166-
167163
def _mediawiki_row_with_attrs(separator, cell_values, colwidths, colaligns):
168164
alignment = {
169165
"left": "",
@@ -1100,13 +1096,13 @@ def _choose_width_fn(has_invisible, enable_widechars, is_multiline):
11001096
return width_fn
11011097

11021098

1103-
def _align_column_choose_padfn(strings, alignment, has_invisible):
1099+
def _align_column_choose_padfn(strings, alignment, has_invisible, preserve_whitespace):
11041100
if alignment == "right":
1105-
if not PRESERVE_WHITESPACE:
1101+
if not preserve_whitespace:
11061102
strings = [s.strip() for s in strings]
11071103
padfn = _padleft
11081104
elif alignment == "center":
1109-
if not PRESERVE_WHITESPACE:
1105+
if not preserve_whitespace:
11101106
strings = [s.strip() for s in strings]
11111107
padfn = _padboth
11121108
elif alignment == "decimal":
@@ -1120,7 +1116,7 @@ def _align_column_choose_padfn(strings, alignment, has_invisible):
11201116
elif not alignment:
11211117
padfn = _padnone
11221118
else:
1123-
if not PRESERVE_WHITESPACE:
1119+
if not preserve_whitespace:
11241120
strings = [s.strip() for s in strings]
11251121
padfn = _padright
11261122
return strings, padfn
@@ -1163,9 +1159,12 @@ def _align_column(
11631159
has_invisible=True,
11641160
enable_widechars=False,
11651161
is_multiline=False,
1162+
preserve_whitespace=False,
11661163
):
11671164
"""[string] -> [padded_string]"""
1168-
strings, padfn = _align_column_choose_padfn(strings, alignment, has_invisible)
1165+
strings, padfn = _align_column_choose_padfn(
1166+
strings, alignment, has_invisible, preserve_whitespace
1167+
)
11691168
width_fn = _align_column_choose_width_fn(
11701169
has_invisible, enable_widechars, is_multiline
11711170
)
@@ -1271,15 +1270,21 @@ def _format(val, valtype, floatfmt, intfmt, missingval="", has_invisible=True):
12711270
return f"{val}"
12721271
elif valtype is int:
12731272
if isinstance(val, str):
1274-
val_striped = val.encode('unicode_escape').decode('utf-8')
1275-
colored = re.search(r'(\\[xX]+[0-9a-fA-F]+\[\d+[mM]+)([0-9.]+)(\\.*)$', val_striped)
1273+
val_striped = val.encode("unicode_escape").decode("utf-8")
1274+
colored = re.search(
1275+
r"(\\[xX]+[0-9a-fA-F]+\[\d+[mM]+)([0-9.]+)(\\.*)$", val_striped
1276+
)
12761277
if colored:
12771278
total_groups = len(colored.groups())
12781279
if total_groups == 3:
12791280
digits = colored.group(2)
12801281
if digits.isdigit():
1281-
val_new = colored.group(1) + format(int(digits), intfmt) + colored.group(3)
1282-
val = val_new.encode('utf-8').decode('unicode_escape')
1282+
val_new = (
1283+
colored.group(1)
1284+
+ format(int(digits), intfmt)
1285+
+ colored.group(3)
1286+
)
1287+
val = val_new.encode("utf-8").decode("unicode_escape")
12831288
intfmt = ""
12841289
return format(val, intfmt)
12851290
elif valtype is bytes:
@@ -1645,6 +1650,7 @@ def tabulate(
16451650
disable_numparse=False,
16461651
colglobalalign=None,
16471652
colalign=None,
1653+
preserve_whitespace=False,
16481654
maxcolwidths=None,
16491655
headersglobalalign=None,
16501656
headersalign=None,
@@ -2323,7 +2329,15 @@ def tabulate(
23232329
if tablefmt == "colon_grid":
23242330
aligns_copy = ["left"] * len(cols)
23252331
cols = [
2326-
_align_column(c, a, minw, has_invisible, enable_widechars, is_multiline)
2332+
_align_column(
2333+
c,
2334+
a,
2335+
minw,
2336+
has_invisible,
2337+
enable_widechars,
2338+
is_multiline,
2339+
preserve_whitespace,
2340+
)
23272341
for c, a, minw in zip(cols, aligns_copy, minwidths)
23282342
]
23292343

@@ -2820,7 +2834,16 @@ def _main():
28202834
opts, args = getopt.getopt(
28212835
sys.argv[1:],
28222836
"h1o:s:F:I:f:",
2823-
["help", "header", "output=", "sep=", "float=", "int=", "colalign=", "format="],
2837+
[
2838+
"help",
2839+
"header",
2840+
"output=",
2841+
"sep=",
2842+
"float=",
2843+
"int=",
2844+
"colalign=",
2845+
"format=",
2846+
],
28242847
)
28252848
except getopt.GetoptError as e:
28262849
print(e)

test/common.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,13 @@
22
from pytest import skip, raises # noqa
33
import warnings
44

5+
56
def assert_equal(expected, result):
67
print("Expected:\n%s\n" % expected)
78
print("Got:\n%s\n" % result)
89
assert expected == result
910

11+
1012
def assert_in(result, expected_set):
1113
nums = range(1, len(expected_set) + 1)
1214
for i, expected in zip(nums, expected_set):

test/test_api.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ def test_tabulate_signature():
5050
("disable_numparse", False),
5151
("colglobalalign", None),
5252
("colalign", None),
53+
("preserve_whitespace", False),
5354
("maxcolwidths", None),
5455
("headersglobalalign", None),
5556
("headersalign", None),

test/test_output.py

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
"""Test output of the various forms of tabular data."""
22
from pytest import mark
33

4-
import tabulate as tabulate_module
54
from common import assert_equal, raises, skip, check_warnings
65
from tabulate import tabulate, simple_separated_format, SEPARATING_LINE
76

@@ -1459,7 +1458,12 @@ def test_colon_grid():
14591458
"+------+------+",
14601459
]
14611460
)
1462-
result = tabulate([[3, 4]], headers=("H1", "H2"), tablefmt="colon_grid", colalign=["right", "center"])
1461+
result = tabulate(
1462+
[[3, 4]],
1463+
headers=("H1", "H2"),
1464+
tablefmt="colon_grid",
1465+
colalign=["right", "center"],
1466+
)
14631467
assert_equal(expected, result)
14641468

14651469

@@ -1482,7 +1486,9 @@ def test_colon_grid_wide_characters():
14821486
"+-----------+---------+",
14831487
]
14841488
)
1485-
result = tabulate(_test_table, headers, tablefmt="colon_grid", colalign=["left", "right"])
1489+
result = tabulate(
1490+
_test_table, headers, tablefmt="colon_grid", colalign=["left", "right"]
1491+
)
14861492
assert_equal(expected, result)
14871493

14881494

@@ -2773,7 +2779,9 @@ def test_intfmt_with_string_as_integer():
27732779
@mark.skip(reason="It detects all values as floats but there are strings and integers.")
27742780
def test_intfmt_with_string_with_floats():
27752781
"Output: integer format"
2776-
result = tabulate([[82000.38], ["1500.47"], ["2463"], [92165]], intfmt=",", tablefmt="plain")
2782+
result = tabulate(
2783+
[[82000.38], ["1500.47"], ["2463"], [92165]], intfmt=",", tablefmt="plain"
2784+
)
27772785
expected = "82000.4\n 1500.47\n 2463\n92,165"
27782786
assert_equal(expected, result)
27792787

@@ -3208,18 +3216,16 @@ def test_disable_numparse_list():
32083216

32093217
def test_preserve_whitespace():
32103218
"Output: Default table output, but with preserved leading whitespace."
3211-
tabulate_module.PRESERVE_WHITESPACE = True
32123219
table_headers = ["h1", "h2", "h3"]
32133220
test_table = [[" foo", " bar ", "foo"]]
32143221
expected = "\n".join(
32153222
["h1 h2 h3", "----- ------- ----", " foo bar foo"]
32163223
)
3217-
result = tabulate(test_table, table_headers)
3224+
result = tabulate(test_table, table_headers, preserve_whitespace=True)
32183225
assert_equal(expected, result)
32193226

3220-
tabulate_module.PRESERVE_WHITESPACE = False
32213227
table_headers = ["h1", "h2", "h3"]
32223228
test_table = [[" foo", " bar ", "foo"]]
32233229
expected = "\n".join(["h1 h2 h3", "---- ---- ----", "foo bar foo"])
3224-
result = tabulate(test_table, table_headers)
3230+
result = tabulate(test_table, table_headers, preserve_whitespace=False)
32253231
assert_equal(expected, result)

test/test_regression.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -513,6 +513,7 @@ def test_numpy_int64_as_integer():
513513
except ImportError:
514514
raise skip("")
515515

516+
516517
def test_empty_table_with_colalign():
517518
"Regression: empty table with colalign kwarg"
518519
table = tabulate([], ["a", "b", "c"], colalign=("center", "left", "left", "center"))

0 commit comments

Comments
 (0)