Skip to content

Commit

Permalink
flake8 and black formatting changes
Browse files Browse the repository at this point in the history
  • Loading branch information
Stefan Sullivan committed May 13, 2024
1 parent c928342 commit 303a042
Show file tree
Hide file tree
Showing 4 changed files with 143 additions and 80 deletions.
90 changes: 63 additions & 27 deletions tabulate/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,15 +92,24 @@ class TableFormat:
- or a list of elements not to be displayed if the table has column headers.
"""
def __init__(self,
lineabove, linebelowheader, linebetweenrows, linebelow, headerrow, datarow, padding, with_header_hide,
min_padding=MIN_PADDING,
disable_numparse=None,
numalign="decimal",
stralign="left",
multiline=True,
escape_first_column=None,
):

def __init__(
self,
lineabove,
linebelowheader,
linebetweenrows,
linebelow,
headerrow,
datarow,
padding,
with_header_hide,
min_padding=MIN_PADDING,
disable_numparse=None,
numalign="decimal",
stralign="left",
multiline=True,
escape_first_column=None,
):
# tuple fields
self.lineabove = lineabove
self.linebelowheader = linebelowheader
Expand Down Expand Up @@ -308,7 +317,7 @@ def escape_char(c):
return _build_simple_row(escaped_values, rowfmt)


def _rst_escape_first_column(rows, headers, escape_value='..'):
def _rst_escape_first_column(rows, headers, escape_value=".."):
def escape_empty(val):
if isinstance(val, (str, bytes)) and not val.strip():
return escape_value
Expand Down Expand Up @@ -572,7 +581,7 @@ def escape_empty(val):
datarow=DataRow("", " ", ""),
padding=0,
with_header_hide=None,
escape_first_column='..',
escape_first_column="..",
),
"mediawiki": TableFormat(
lineabove=Line(
Expand Down Expand Up @@ -643,7 +652,7 @@ def escape_empty(val):
datarow=_latex_row,
padding=1,
with_header_hide=None,
multiline=False
multiline=False,
),
"latex_raw": TableFormat(
lineabove=_latex_line_begin_tabular,
Expand Down Expand Up @@ -830,7 +839,7 @@ def simple_separated_format(separator, **kwargs):
datarow=DataRow("", separator, ""),
padding=0,
with_header_hide=None,
**kwargs
**kwargs,
)


Expand Down Expand Up @@ -1308,7 +1317,7 @@ def _align_header(


def _remove_separating_lines(rows):
if type(rows) == list:
if isinstance(rows, list):
separating_lines = []
sans_rows = []
for index, row in enumerate(rows):
Expand Down Expand Up @@ -1356,7 +1365,8 @@ def _bool(val):


def _normalize_tabular_data(tabular_data, headers, showindex="default"):
"""Transform a supported data type to a list of lists, and a list of headers, with headers padding.
"""Transform a supported data type to a list of lists, and a list of headers, with headers
padding.
Supported tabular data types:
Expand Down Expand Up @@ -2162,9 +2172,15 @@ def tabulate(
# empty values in the first column of RST tables should be escaped (issue #82)
# "" should be escaped as "\\ " or ".."
if tablefmt.escape_first_column is not None:
list_of_lists, headers = _rst_escape_first_column(list_of_lists, headers, tablefmt.escape_first_column)
list_of_lists, headers = _rst_escape_first_column(
list_of_lists, headers, tablefmt.escape_first_column
)

disable_numparse = tablefmt.disable_numparse if tablefmt.disable_numparse is not None else disable_numparse
disable_numparse = (
tablefmt.disable_numparse
if tablefmt.disable_numparse is not None
else disable_numparse
)
numalign = tablefmt.numalign if numalign == _DEFAULT_ALIGN else numalign
stralign = tablefmt.stralign if stralign == _DEFAULT_ALIGN else stralign

Expand Down Expand Up @@ -2223,22 +2239,28 @@ def tabulate(

# align columns
# first set global alignment
if colglobalalign is not None: # if global alignment provided
if colglobalalign is not None: # if global alignment provided
aligns = [colglobalalign] * len(cols)
else: # default
else: # default
aligns = [numalign if ct in [int, float] else stralign for ct in coltypes]
# then specific alignements
if colalign is not None:
assert isinstance(colalign, Iterable)
if isinstance(colalign, str):
warnings.warn(f"As a string, `colalign` is interpreted as {[c for c in colalign]}. Did you mean `colglobalalign = \"{colalign}\"` or `colalign = (\"{colalign}\",)`?", stacklevel=2)
warnings.warn(
f"As a string, `colalign` is interpreted as {[c for c in colalign]}. "
f'Did you mean `colglobalalign = "{colalign}"` or `colalign = ("{colalign}",)`?',
stacklevel=2,
)
for idx, align in enumerate(colalign):
if not idx < len(aligns):
break
elif align != "global":
aligns[idx] = align
minwidths = (
[width_fn(h) + tablefmt.min_padding for h in headers] if headers else [0] * len(cols)
[width_fn(h) + tablefmt.min_padding for h in headers]
if headers
else [0] * len(cols)
)
cols = [
_align_column(c, a, minw, has_invisible, enable_widechars, tablefmt.multiline)
Expand All @@ -2250,20 +2272,25 @@ def tabulate(
# align headers and add headers
t_cols = cols or [[""]] * len(headers)
# first set global alignment
if headersglobalalign is not None: # if global alignment provided
if headersglobalalign is not None: # if global alignment provided
aligns_headers = [headersglobalalign] * len(t_cols)
else: # default
else: # default
aligns_headers = aligns or [stralign] * len(headers)
# then specific header alignements
if headersalign is not None:
assert isinstance(headersalign, Iterable)
if isinstance(headersalign, str):
warnings.warn(f"As a string, `headersalign` is interpreted as {[c for c in headersalign]}. Did you mean `headersglobalalign = \"{headersalign}\"` or `headersalign = (\"{headersalign}\",)`?", stacklevel=2)
warnings.warn(
f"As a string, `headersalign` is interpreted as {[c for c in headersalign]}. "
f'Did you mean `headersglobalalign = "{headersalign}"` '
f'or `headersalign = ("{headersalign}",)`?',
stacklevel=2,
)
for idx, align in enumerate(headersalign):
hidx = headers_pad + idx
if not hidx < len(aligns_headers):
break
elif align == "same" and hidx < len(aligns): # same as column align
elif align == "same" and hidx < len(aligns): # same as column align
aligns_headers[hidx] = aligns[hidx]
elif align != "global":
aligns_headers[hidx] = align
Expand All @@ -2285,7 +2312,14 @@ def tabulate(
_reinsert_separating_lines(rows, separating_lines)

return _format_table(
tablefmt, headers, aligns_headers, rows, minwidths, aligns, tablefmt.multiline, rowaligns=rowaligns
tablefmt,
headers,
aligns_headers,
rows,
minwidths,
aligns,
tablefmt.multiline,
rowaligns=rowaligns,
)


Expand Down Expand Up @@ -2416,7 +2450,9 @@ def str(self):
return self


def _format_table(fmt, headers, headersaligns, rows, colwidths, colaligns, is_multiline, rowaligns):
def _format_table(
fmt, headers, headersaligns, rows, colwidths, colaligns, is_multiline, rowaligns
):
"""Produce a plain-text representation of the table."""
lines = []
hidden = fmt.with_header_hide if (headers and fmt.with_header_hide) else []
Expand Down
2 changes: 1 addition & 1 deletion test/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ def rows_to_pipe_table_str(rows):

return "\n".join(lines)


def check_warnings(func_args_kwargs, *, num=None, category=None, contain=None):
func, args, kwargs = func_args_kwargs
with warnings.catch_warnings(record=True) as W:
Expand All @@ -28,4 +29,3 @@ def check_warnings(func_args_kwargs, *, num=None, category=None, contain=None):
assert all([issubclass(w.category, category) for w in W])
if contain is not None:
assert all([contain in str(w.message) for w in W])

5 changes: 4 additions & 1 deletion test/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,10 @@ def sample_input(sep=" ", with_headers=False):


def run_and_capture_stdout(cmd, input=None):
return subprocess.run(cmd, input=input, check=True, capture_output=True, encoding='utf-8').stdout
proc = subprocess.run(
cmd, input=input, check=True, capture_output=True, encoding="utf-8"
)
return proc.stdout


class TemporaryTextFile:
Expand Down
126 changes: 75 additions & 51 deletions test/test_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,21 +244,33 @@ def test_simple():


def test_simple_with_zero_padding():
""" Output custom simple table built with a new column separator """
expected = textwrap.dedent("""\
"""Output custom simple table built with a new column separator"""
expected = textwrap.dedent(
"""\
strings numbers
eggs 451""")
result = tabulate([_test_table[-1]], _test_table_headers, tablefmt=simple_separated_format(" ", min_padding=0))
eggs 451"""
)
result = tabulate(
[_test_table[-1]],
_test_table_headers,
tablefmt=simple_separated_format(" ", min_padding=0),
)
assert result == expected


def test_simple_with_zero_padding_and_alignment():
""" Output custom simple table built with a new column separator """
expected = textwrap.dedent("""\
"""Output custom simple table built with a new column separator"""
expected = textwrap.dedent(
"""\
strings numbers
spam 41.9999
eggs 451""")
result = tabulate(_test_table, _test_table_headers, tablefmt=simple_separated_format(" ", min_padding=0))
eggs 451"""
)
result = tabulate(
_test_table,
_test_table_headers,
tablefmt=simple_separated_format(" ", min_padding=0),
)
assert result == expected


Expand Down Expand Up @@ -2700,60 +2712,72 @@ def test_colalign_multi_with_sep_line():
expected = " one two\n\nthree four"
assert expected == result


def test_column_global_and_specific_alignment():
""" Test `colglobalalign` and `"global"` parameter for `colalign`. """
table = [[1,2,3,4],[111,222,333,444]]
colglobalalign = 'center'
colalign = ('global','left', 'right')
"""Test `colglobalalign` and `"global"` parameter for `colalign`."""
table = [[1, 2, 3, 4], [111, 222, 333, 444]]
colglobalalign = "center"
colalign = ("global", "left", "right")
result = tabulate(table, colglobalalign=colglobalalign, colalign=colalign)
expected = '\n'.join([
"--- --- --- ---",
" 1 2 3 4",
"111 222 333 444",
"--- --- --- ---"])
expected = "\n".join(
[
"--- --- --- ---",
" 1 2 3 4",
"111 222 333 444",
"--- --- --- ---",
]
)
assert expected == result


def test_headers_global_and_specific_alignment():
""" Test `headersglobalalign` and `headersalign`. """
table = [[1,2,3,4,5,6],[111,222,333,444,555,666]]
colglobalalign = 'center'
colalign = ('left',)
headers = ['h', 'e', 'a', 'd', 'e', 'r']
headersglobalalign = 'right'
headersalign = ('same', 'same', 'left', 'global', 'center')
result = tabulate(table, headers=headers, colglobalalign=colglobalalign, colalign=colalign, headersglobalalign=headersglobalalign, headersalign=headersalign)
expected = '\n'.join([
"h e a d e r",
"--- --- --- --- --- ---",
"1 2 3 4 5 6",
"111 222 333 444 555 666"])
"""Test `headersglobalalign` and `headersalign`."""
table = [[1, 2, 3, 4, 5, 6], [111, 222, 333, 444, 555, 666]]
colglobalalign = "center"
colalign = ("left",)
headers = ["h", "e", "a", "d", "e", "r"]
headersglobalalign = "right"
headersalign = ("same", "same", "left", "global", "center")
result = tabulate(
table,
headers=headers,
colglobalalign=colglobalalign,
colalign=colalign,
headersglobalalign=headersglobalalign,
headersalign=headersalign,
)
expected = "\n".join(
[
"h e a d e r",
"--- --- --- --- --- ---",
"1 2 3 4 5 6",
"111 222 333 444 555 666",
]
)
assert expected == result


def test_colalign_or_headersalign_too_long():
""" Test `colalign` and `headersalign` too long. """
table = [[1,2],[111,222]]
colalign = ('global', 'left', 'center')
headers = ['h']
headersalign = ('center', 'right', 'same')
result = tabulate(table, headers=headers, colalign=colalign, headersalign=headersalign)
expected = '\n'.join([
" h",
"--- ---",
" 1 2",
"111 222"])
"""Test `colalign` and `headersalign` too long."""
table = [[1, 2], [111, 222]]
colalign = ("global", "left", "center")
headers = ["h"]
headersalign = ("center", "right", "same")
result = tabulate(
table, headers=headers, colalign=colalign, headersalign=headersalign
)
expected = "\n".join([" h", "--- ---", " 1 2", "111 222"])
assert expected == result


def test_warning_when_colalign_or_headersalign_is_string():
""" Test user warnings when `colalign` or `headersalign` is a string. """
table = [[1,"bar"]]
opt = {
'colalign': "center",
'headers': ['foo', '2'],
'headersalign': "center"}
check_warnings((tabulate, [table], opt),
num = 2,
category = UserWarning,
contain = "As a string")
"""Test user warnings when `colalign` or `headersalign` is a string."""
table = [[1, "bar"]]
opt = {"colalign": "center", "headers": ["foo", "2"], "headersalign": "center"}
check_warnings(
(tabulate, [table], opt), num=2, category=UserWarning, contain="As a string"
)


def test_float_conversions():
"Output: float format parsed"
Expand Down

0 comments on commit 303a042

Please sign in to comment.