From 422b36ec1191f07ff0816a0e3701ee3874afdb96 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vladimir=20Vrzi=C4=87?= Date: Tue, 23 Feb 2021 19:27:21 +0100 Subject: [PATCH 001/204] Replace constant PRESERVE_WHITESPACE with an argument to tabulate() --- tabulate.py | 17 ++++++++--------- test/test_output.py | 6 ++---- 2 files changed, 10 insertions(+), 13 deletions(-) diff --git a/tabulate.py b/tabulate.py index 55b896e3..541cf297 100644 --- a/tabulate.py +++ b/tabulate.py @@ -68,9 +68,6 @@ def _is_file(f): # minimum extra space in headers MIN_PADDING = 2 -# Whether or not to preserve leading/trailing whitespace in data. -PRESERVE_WHITESPACE = False - _DEFAULT_FLOATFMT = "g" _DEFAULT_MISSINGVAL = "" # default align will be overwritten by "left", "center" or "decimal" @@ -810,13 +807,13 @@ def _choose_width_fn(has_invisible, enable_widechars, is_multiline): return width_fn -def _align_column_choose_padfn(strings, alignment, has_invisible): +def _align_column_choose_padfn(strings, alignment, has_invisible, preserve_whitespace): if alignment == "right": - if not PRESERVE_WHITESPACE: + if not preserve_whitespace: strings = [s.strip() for s in strings] padfn = _padleft elif alignment == "center": - if not PRESERVE_WHITESPACE: + if not preserve_whitespace: strings = [s.strip() for s in strings] padfn = _padboth elif alignment == "decimal": @@ -830,7 +827,7 @@ def _align_column_choose_padfn(strings, alignment, has_invisible): elif not alignment: padfn = _padnone else: - if not PRESERVE_WHITESPACE: + if not preserve_whitespace: strings = [s.strip() for s in strings] padfn = _padright return strings, padfn @@ -873,9 +870,10 @@ def _align_column( has_invisible=True, enable_widechars=False, is_multiline=False, + preserve_whitespace=False ): """[string] -> [padded_string]""" - strings, padfn = _align_column_choose_padfn(strings, alignment, has_invisible) + strings, padfn = _align_column_choose_padfn(strings, alignment, has_invisible, preserve_whitespace) width_fn = _align_column_choose_width_fn( has_invisible, enable_widechars, is_multiline ) @@ -1224,6 +1222,7 @@ def tabulate( showindex="default", disable_numparse=False, colalign=None, + preserve_whitespace=False ): """Format a fixed width table for pretty printing. @@ -1603,7 +1602,7 @@ def tabulate( [width_fn(h) + min_padding for h in headers] if headers else [0] * len(cols) ) cols = [ - _align_column(c, a, minw, has_invisible, enable_widechars, is_multiline) + _align_column(c, a, minw, has_invisible, enable_widechars, is_multiline, preserve_whitespace) for c, a, minw in zip(cols, aligns, minwidths) ] diff --git a/test/test_output.py b/test/test_output.py index abab439c..660f047b 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -1598,18 +1598,16 @@ def test_disable_numparse_list(): def test_preserve_whitespace(): "Output: Default table output, but with preserved leading whitespace." - tabulate_module.PRESERVE_WHITESPACE = True table_headers = ["h1", "h2", "h3"] test_table = [[" foo", " bar ", "foo"]] expected = "\n".join( ["h1 h2 h3", "----- ------- ----", " foo bar foo"] ) - result = tabulate(test_table, table_headers) + result = tabulate(test_table, table_headers, preserve_whitespace=True) assert_equal(expected, result) - tabulate_module.PRESERVE_WHITESPACE = False table_headers = ["h1", "h2", "h3"] test_table = [[" foo", " bar ", "foo"]] expected = "\n".join(["h1 h2 h3", "---- ---- ----", "foo bar foo"]) - result = tabulate(test_table, table_headers) + result = tabulate(test_table, table_headers, preserve_whitespace=False) assert_equal(expected, result) From fbdb1fd702d9c5f7c03dbd091d5208141697683e Mon Sep 17 00:00:00 2001 From: Racerroar888 Date: Sat, 5 Nov 2022 08:40:39 -0600 Subject: [PATCH 002/204] fix maxcolwidths doesn't accept tuple --- README.md | 2 +- tabulate/__init__.py | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index d64b99ab..3996f7d3 100644 --- a/README.md +++ b/README.md @@ -1123,5 +1123,5 @@ Bart Broere, Vilhelm Prytz, Alexander Gažo, Hugo van Kemenade, jamescooke, Matt Warner, Jérôme Provensal, Kevin Deldycke, Kian-Meng Ang, Kevin Patterson, Shodhan Save, cleoold, KOLANICH, Vijaya Krishna Kasula, Furcy Pin, Christian Fibich, Shaun Duncan, -Dimitri Papadopoulos. +Dimitri Papadopoulos, Racerroar. diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 3b1a1e11..23099058 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -2071,6 +2071,8 @@ def tabulate( list_of_lists, separating_lines = _remove_separating_lines(list_of_lists) if maxcolwidths is not None: + if type(maxcolwidths) is tuple: # Check if tuple, convert to list if so + maxcolwidths = list(maxcolwidths) if len(list_of_lists): num_cols = len(list_of_lists[0]) else: From 6ea172bca8d2c9c456696ecfa06018fae5ba2b9f Mon Sep 17 00:00:00 2001 From: Daniel Aslau Date: Wed, 16 Nov 2022 10:59:14 +0100 Subject: [PATCH 003/204] configure break long words and on hyphen for maxcolwidths --- tabulate/__init__.py | 6 +++++- test/test_output.py | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 3b1a1e11..1da11506 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -33,6 +33,10 @@ def _is_file(f): # Whether or not to preserve leading/trailing whitespace in data. PRESERVE_WHITESPACE = False +# TextWrapper breaks words longer than 'width'. +BREAK_LONG_WORDS = True +# TextWrapper is breaking hyphenated words. +BREAK_ON_HYPHENS = True _DEFAULT_FLOATFMT = "g" _DEFAULT_INTFMT = "" @@ -1524,7 +1528,7 @@ def _wrap_text_to_colwidths(list_of_lists, colwidths, numparses=True): continue if width is not None: - wrapper = _CustomTextWrap(width=width) + wrapper = _CustomTextWrap(width=width, break_long_words=BREAK_LONG_WORDS, break_on_hyphens=BREAK_ON_HYPHENS) # Cast based on our internal type handling # Any future custom formatting of types (such as datetimes) # may need to be more explicit than just `str` of the object diff --git a/test/test_output.py b/test/test_output.py index 9043aed3..61ec869f 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -2973,3 +2973,36 @@ def test_preserve_whitespace(): expected = "\n".join(["h1 h2 h3", "---- ---- ----", "foo bar foo"]) result = tabulate(test_table, table_headers) assert_equal(expected, result) + +def test_break_long_words(): + "Output: Default table output, with breakwords true." + table_headers = ["h1", "h2", "h3"] + test_table = [[" foo1", " bar2 ", "foo3"]] + + # Table is not wrapped + tabulate_module.BREAK_LONG_WORDS = False + expected = "h1 h2 h3\n---- ---- ----\nfoo1 bar2 foo3" + result = tabulate(test_table, table_headers, maxcolwidths=3) + assert_equal(expected, result) + + # Table is wrapped on 2 letters + tabulate_module.BREAK_LONG_WORDS = True + expected = "h1 h2 h3\n---- ---- ----\nf ba foo\noo1 r2 3" + result = tabulate(test_table, table_headers, maxcolwidths=3) + assert_equal(expected, result) + +def test_break_on_hyphens(): + "Output: Default table output, with break on hyphens true." + tabulate_module.BREAK_ON_HYPHENS = False + table_headers = ["h1", "h2", "h3"] + test_table = [[" foo-bar", " bar-bar ", "foo-foo"]] + # Table is wrapped on 2 letters + expected = "h1 h2 h3\n---- ---- -----\nfoo bar- foo-f\n-bar bar oo" + result = tabulate(test_table, table_headers, maxcolwidths=5) + assert_equal(expected, result) + + # Table is no longer wrapped + tabulate_module.BREAK_ON_HYPHENS = True + expected = "h1 h2 h3\n---- ---- ----\nfoo- bar- foo-\nbar bar foo" + result = tabulate(test_table, table_headers, maxcolwidths=5) + assert_equal(expected, result) From 95eb24e598076f20a6a48622086e8b24bc9f2e92 Mon Sep 17 00:00:00 2001 From: Daniel Aslau Date: Wed, 16 Nov 2022 16:02:53 +0100 Subject: [PATCH 004/204] break long words and on hyphen for maxcolwidths --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index d64b99ab..05c7a268 100644 --- a/README.md +++ b/README.md @@ -927,6 +927,14 @@ and thus no automate multiline wrapping will take place. The wrapping uses the python standard [textwrap.wrap](https://docs.python.org/3/library/textwrap.html#textwrap.wrap) function with default parameters - aside from width. +BREAK_LONG_WORDS and BREAK_LONG_WORDS can be used to turn off the TextWrapper break_long_words and break_on_hyphens options. + +```python +import tabulate +tabulate.BREAK_LONG_WORDS = False +tabulate.BREAK_ON_HYPHENS = False +``` + This example demonstrates usage of automatic multiline wrapping, though typically the lines being wrapped would probably be significantly longer than this. From ecbd67ce44cb0a47079f081326276dd153d11799 Mon Sep 17 00:00:00 2001 From: Daniel Aslau Date: Wed, 16 Nov 2022 16:37:36 +0100 Subject: [PATCH 005/204] break_long_words and break_on_hyphens as named arguments --- README.md | 33 +++++++++++++++++++++++++-------- tabulate/__init__.py | 15 +++++++++------ test/test_api.py | 2 ++ test/test_output.py | 20 ++++++++------------ 4 files changed, 44 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 05c7a268..069cb3e0 100644 --- a/README.md +++ b/README.md @@ -927,14 +927,6 @@ and thus no automate multiline wrapping will take place. The wrapping uses the python standard [textwrap.wrap](https://docs.python.org/3/library/textwrap.html#textwrap.wrap) function with default parameters - aside from width. -BREAK_LONG_WORDS and BREAK_LONG_WORDS can be used to turn off the TextWrapper break_long_words and break_on_hyphens options. - -```python -import tabulate -tabulate.BREAK_LONG_WORDS = False -tabulate.BREAK_ON_HYPHENS = False -``` - This example demonstrates usage of automatic multiline wrapping, though typically the lines being wrapped would probably be significantly longer than this. @@ -948,6 +940,31 @@ the lines being wrapped would probably be significantly longer than this. +------------+---------+ ``` +Text is preferably wrapped on whitespaces and right after the hyphens in hyphenated words. + +break_long_words (default: True) If true, then words longer than width will be broken in order to ensure that no lines are longer than width. +If it is false, long words will not be broken, and some lines may be longer than width. +(Long words will be put on a line by themselves, in order to minimize the amount by which width is exceeded.) + +break_on_hyphens (default: True) If true, wrapping will occur preferably on whitespaces and right after hyphens in compound words, as it is customary in English. +If false, only whitespaces will be considered as potentially good places for line breaks. + +```pycon +>>> print(tabulate([["John Smith", "Middle-Manager"]], headers=["Name", "Title"], tablefmt="grid", maxcolwidths=[None, 5], break_long_words=False)) ++------------+---------+ +| Name | Title | ++============+=========+ +| John Smith | Middle- | +| | Manager | ++------------+---------+ +>>> print(tabulate([["John Smith", "Middle-Manager"]], headers=["Name", "Title"], tablefmt="grid", maxcolwidths=[None, 5], break_long_words=False, break_on_hyphens=False)) ++------------+----------------+ +| Name | Title | ++============+================+ +| John Smith | Middle-Manager | ++------------+----------------+ +``` + ### Adding Separating lines One might want to add one or more separating lines to highlight different sections in a table. diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 1da11506..294e3b20 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -33,10 +33,11 @@ def _is_file(f): # Whether or not to preserve leading/trailing whitespace in data. PRESERVE_WHITESPACE = False + # TextWrapper breaks words longer than 'width'. -BREAK_LONG_WORDS = True +_BREAK_LONG_WORDS = True # TextWrapper is breaking hyphenated words. -BREAK_ON_HYPHENS = True +_BREAK_ON_HYPHENS = True _DEFAULT_FLOATFMT = "g" _DEFAULT_INTFMT = "" @@ -1511,7 +1512,7 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"): return rows, headers -def _wrap_text_to_colwidths(list_of_lists, colwidths, numparses=True): +def _wrap_text_to_colwidths(list_of_lists, colwidths, numparses=True, break_long_words=_BREAK_LONG_WORDS, break_on_hyphens=_BREAK_ON_HYPHENS): if len(list_of_lists): num_cols = len(list_of_lists[0]) else: @@ -1528,7 +1529,7 @@ def _wrap_text_to_colwidths(list_of_lists, colwidths, numparses=True): continue if width is not None: - wrapper = _CustomTextWrap(width=width, break_long_words=BREAK_LONG_WORDS, break_on_hyphens=BREAK_ON_HYPHENS) + wrapper = _CustomTextWrap(width=width, break_long_words=break_long_words, break_on_hyphens=break_on_hyphens) # Cast based on our internal type handling # Any future custom formatting of types (such as datetimes) # may need to be more explicit than just `str` of the object @@ -1588,6 +1589,8 @@ def tabulate( maxcolwidths=None, rowalign=None, maxheadercolwidths=None, + break_long_words=_BREAK_LONG_WORDS, + break_on_hyphens=_BREAK_ON_HYPHENS, ): """Format a fixed width table for pretty printing. @@ -2086,7 +2089,7 @@ def tabulate( numparses = _expand_numparse(disable_numparse, num_cols) list_of_lists = _wrap_text_to_colwidths( - list_of_lists, maxcolwidths, numparses=numparses + list_of_lists, maxcolwidths, numparses=numparses, break_long_words=break_long_words, break_on_hyphens=break_on_hyphens ) if maxheadercolwidths is not None: @@ -2100,7 +2103,7 @@ def tabulate( numparses = _expand_numparse(disable_numparse, num_cols) headers = _wrap_text_to_colwidths( - [headers], maxheadercolwidths, numparses=numparses + [headers], maxheadercolwidths, numparses=numparses, break_long_words=break_long_words, break_on_hyphens=break_on_hyphens )[0] # empty values in the first column of RST tables should be escaped (issue #82) diff --git a/test/test_api.py b/test/test_api.py index 046d7526..b70f2e0b 100644 --- a/test/test_api.py +++ b/test/test_api.py @@ -52,6 +52,8 @@ def test_tabulate_signature(): ("maxcolwidths", None), ("rowalign", None), ("maxheadercolwidths", None), + ("break_long_words", True), + ("break_on_hyphens", True), ] _check_signature(tabulate, expected_sig) diff --git a/test/test_output.py b/test/test_output.py index 61ec869f..932b6a5f 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -2979,30 +2979,26 @@ def test_break_long_words(): table_headers = ["h1", "h2", "h3"] test_table = [[" foo1", " bar2 ", "foo3"]] - # Table is not wrapped - tabulate_module.BREAK_LONG_WORDS = False + # Table is not wrapped on 3 letters due to long word expected = "h1 h2 h3\n---- ---- ----\nfoo1 bar2 foo3" - result = tabulate(test_table, table_headers, maxcolwidths=3) + result = tabulate(test_table, table_headers, maxcolwidths=3, break_long_words=False) assert_equal(expected, result) - # Table is wrapped on 2 letters - tabulate_module.BREAK_LONG_WORDS = True + # Table max width is 3 letters expected = "h1 h2 h3\n---- ---- ----\nf ba foo\noo1 r2 3" - result = tabulate(test_table, table_headers, maxcolwidths=3) + result = tabulate(test_table, table_headers, maxcolwidths=3, break_long_words=True) assert_equal(expected, result) def test_break_on_hyphens(): "Output: Default table output, with break on hyphens true." - tabulate_module.BREAK_ON_HYPHENS = False table_headers = ["h1", "h2", "h3"] test_table = [[" foo-bar", " bar-bar ", "foo-foo"]] - # Table is wrapped on 2 letters + # Table max width is 5, long lines breaks on hyphens expected = "h1 h2 h3\n---- ---- -----\nfoo bar- foo-f\n-bar bar oo" - result = tabulate(test_table, table_headers, maxcolwidths=5) + result = tabulate(test_table, table_headers, maxcolwidths=5, break_on_hyphens=False) assert_equal(expected, result) - # Table is no longer wrapped - tabulate_module.BREAK_ON_HYPHENS = True + # Table data is no longer breaks on hyphens expected = "h1 h2 h3\n---- ---- ----\nfoo- bar- foo-\nbar bar foo" - result = tabulate(test_table, table_headers, maxcolwidths=5) + result = tabulate(test_table, table_headers, maxcolwidths=5, break_on_hyphens=True) assert_equal(expected, result) From b50e9ce3bc3087d12821ac89b1cfa917c8877b68 Mon Sep 17 00:00:00 2001 From: Phill Zarfos Date: Thu, 22 Dec 2022 16:42:58 -0500 Subject: [PATCH 006/204] added regression test for maxcolwidths doesn't accept tuple issue --- test/test_regression.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/test/test_regression.py b/test/test_regression.py index 8f60ce74..29f275e3 100644 --- a/test/test_regression.py +++ b/test/test_regression.py @@ -488,6 +488,27 @@ def test_preserve_line_breaks_with_maxcolwidths(): assert_equal(expected, result) +def test_maxcolwidths_accepts_list_or_tuple(): + "Regression: maxcolwidths can accept a list or a tuple (github issue #214)" + table = [["lorem ipsum dolor sit amet"]*3] + expected = "\n".join( + [ + "+-------------+----------+----------------------------+", + "| lorem ipsum | lorem | lorem ipsum dolor sit amet |", + "| dolor sit | ipsum | |", + "| amet | dolor | |", + "| | sit amet | |", + "+-------------+----------+----------------------------+", + ] + ) + # test with maxcolwidths as a list + result = tabulate(table, tablefmt="grid", maxcolwidths=[12, 8]) + assert_equal(expected, result) + # test with maxcolwidths as a tuple + result = tabulate(table, tablefmt="grid", maxcolwidths=(12, 8)) + assert_equal(expected, result) + + def test_exception_on_empty_data_with_maxcolwidths(): "Regression: exception on empty data when using maxcolwidths (github issue #180)" result = tabulate([], maxcolwidths=5) From af40a322d6b889c9c1c2e5161a004c389401e754 Mon Sep 17 00:00:00 2001 From: jerome provensal Date: Mon, 26 Dec 2022 19:20:01 -0800 Subject: [PATCH 007/204] Fix bug/issue #231: SEPARATING_LINE feature doesn't work when the requested format pads columns --- tabulate/__init__.py | 9 +++++++-- test/test_output.py | 21 +++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 3b1a1e11..bf2ed78d 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -101,12 +101,17 @@ def _is_file(f): ) +def _is_separating_line_value(value): + return type(value) == str and value.strip() == SEPARATING_LINE + + def _is_separating_line(row): row_type = type(row) is_sl = (row_type == list or row_type == str) and ( - (len(row) >= 1 and row[0] == SEPARATING_LINE) - or (len(row) >= 2 and row[1] == SEPARATING_LINE) + (len(row) >= 1 and _is_separating_line_value(row[0])) + or (len(row) >= 2 and _is_separating_line_value(row[1])) ) + return is_sl diff --git a/test/test_output.py b/test/test_output.py index 9043aed3..b58b1871 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -2881,6 +2881,27 @@ def test_list_of_lists_with_index_with_sep_line(): assert_equal(expected, result) +def test_with_padded_columns_with_sep_line(): + table = [ + ["1", "one"], # "1" as a str on purpose + [1_000, "one K"], + SEPARATING_LINE, + [1_000_000, "one M"], + ] + expected = "\n".join( + [ + "+---------+-------+", + "| 1 | one |", + "| 1000 | one K |", + "|---------+-------|", + "| 1000000 | one M |", + "+---------+-------+", + ] + ) + result = tabulate(table, tablefmt="psql") + assert_equal(expected, result) + + def test_list_of_lists_with_supplied_index(): "Output: a table with a supplied index" dd = zip(*[list(range(3)), list(range(101, 104))]) From 96761ee53c01418cc347ae43deb829c5bcd6cd28 Mon Sep 17 00:00:00 2001 From: I Bo Date: Wed, 28 Dec 2022 16:52:04 +0300 Subject: [PATCH 008/204] Fix #124. Improve error reporting when non-iterable data provided. --- tabulate/__init__.py | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 3b1a1e11..0dbea615 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1357,15 +1357,24 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"): is_headers2bool_broken = True # noqa headers = list(headers) + err_msg = ( + "\n\nTo build a table python-tabulate requires two-dimensional data " + "like a list of lists or similar." + "\nDid you forget a pair of extra [] or ',' in ()?" + ) index = None if hasattr(tabular_data, "keys") and hasattr(tabular_data, "values"): # dict-like and pandas.DataFrame? if hasattr(tabular_data.values, "__call__"): # likely a conventional dict keys = tabular_data.keys() - rows = list( - izip_longest(*tabular_data.values()) - ) # columns have to be transposed + try: + rows = list( + izip_longest(*tabular_data.values()) + ) # columns have to be transposed + except TypeError: # not iterable + raise TypeError(err_msg) + elif hasattr(tabular_data, "index"): # values is a property, has .index => it's likely a pandas.DataFrame (pandas 0.11.0) keys = list(tabular_data) @@ -1388,7 +1397,10 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"): headers = list(map(str, keys)) # headers should be strings else: # it's a usual iterable of iterables, or a NumPy array, or an iterable of dataclasses - rows = list(tabular_data) + try: + rows = list(tabular_data) + except TypeError: # not iterable + raise TypeError(err_msg) if headers == "keys" and not rows: # an empty table (issue #81) From 72ac2ab05cbe6b7a56d6f456e07ed57bd3648483 Mon Sep 17 00:00:00 2001 From: I Bo Date: Thu, 29 Dec 2022 16:18:47 +0300 Subject: [PATCH 009/204] Fix #207. Update README: headers for dictionaries. --- README.md | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index d64b99ab..ea8df182 100644 --- a/README.md +++ b/README.md @@ -121,10 +121,22 @@ dictionaries or named tuples: ```pycon >>> print(tabulate({"Name": ["Alice", "Bob"], ... "Age": [24, 19]}, headers="keys")) - Age Name ------ ------ - 24 Alice - 19 Bob +Name Age +------ ----- +Alice 24 +Bob 19 +``` + +When data is a list of dictionaries, a dictionary can be passed as `headers` +to replace the keys with other column labels: + +```pycon +>>> print(tabulate([{1: "Alice", 2: 24}, {1: "Bob", 2: 19}], +... headers={1: "Name", 2: "Age"})) +Name Age +------ ----- +Alice 24 +Bob 19 ``` ### Row Indices From 475d0da54b4c1e40c207fbdb022e5e8c15dadf20 Mon Sep 17 00:00:00 2001 From: Arpit Jain <3242828+arpitjain099@users.noreply.github.com> Date: Sat, 29 Apr 2023 17:58:38 +0900 Subject: [PATCH 010/204] Update common.py --- test/common.py | 1 - 1 file changed, 1 deletion(-) diff --git a/test/common.py b/test/common.py index d95e84fb..e331e981 100644 --- a/test/common.py +++ b/test/common.py @@ -1,7 +1,6 @@ import pytest # noqa from pytest import skip, raises # noqa - def assert_equal(expected, result): print("Expected:\n%s\n" % expected) print("Got:\n%s\n" % result) From a8672a525e4144840120f275fcafc791728f5e8a Mon Sep 17 00:00:00 2001 From: Arpit Jain Date: Sat, 29 Apr 2023 18:10:53 +0900 Subject: [PATCH 011/204] add codeql file --- test/common.py | 1 - 1 file changed, 1 deletion(-) diff --git a/test/common.py b/test/common.py index e331e981..8cf09cd6 100644 --- a/test/common.py +++ b/test/common.py @@ -6,7 +6,6 @@ def assert_equal(expected, result): print("Got:\n%s\n" % result) assert expected == result - def assert_in(result, expected_set): nums = range(1, len(expected_set) + 1) for i, expected in zip(nums, expected_set): From d38740ca77a3b8efed9f8b3fcc82e121bde84205 Mon Sep 17 00:00:00 2001 From: Arpit Jain Date: Sat, 29 Apr 2023 18:16:05 +0900 Subject: [PATCH 012/204] move libraries --- tabulate/__init__.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 3b1a1e11..872e8638 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -10,6 +10,7 @@ import math import textwrap import dataclasses +import sys try: import wcwidth # optional wide-character (CJK) support @@ -1352,9 +1353,7 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"): try: bool(headers) - is_headers2bool_broken = False # noqa except ValueError: # numpy.ndarray, pandas.core.index.Index, ... - is_headers2bool_broken = True # noqa headers = list(headers) index = None @@ -2646,8 +2645,6 @@ def _main(): (default: simple) """ import getopt - import sys - import textwrap usage = textwrap.dedent(_main.__doc__) try: From 0978de5bb3a72d9b285d0e305aaf4574e9ffd5bd Mon Sep 17 00:00:00 2001 From: Bjorn Olsen Date: Tue, 23 May 2023 21:55:13 +0200 Subject: [PATCH 013/204] Fix separating line with dataclasses --- tabulate/__init__.py | 7 ++++++- test/test_input.py | 24 +++++++++++++++++++++++- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 11bb8655..f95da8e6 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1461,7 +1461,12 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"): field_names = [field.name for field in dataclasses.fields(rows[0])] if headers == "keys": headers = field_names - rows = [[getattr(row, f) for f in field_names] for row in rows] + rows = [ + [getattr(row, f) for f in field_names] + if not _is_separating_line(row) + else row + for row in rows + ] elif headers == "keys" and len(rows) > 0: # keys are column indices diff --git a/test/test_input.py b/test/test_input.py index a178bd9d..d52f10bc 100644 --- a/test/test_input.py +++ b/test/test_input.py @@ -1,6 +1,6 @@ """Test support of the various forms of tabular data.""" -from tabulate import tabulate +from tabulate import tabulate, SEPARATING_LINE from common import assert_equal, assert_in, raises, skip try: @@ -520,6 +520,28 @@ def test_py37orlater_list_of_dataclasses_headers(): skip("test_py37orlater_list_of_dataclasses_headers is skipped") +def test_py37orlater_list_of_dataclasses_with_separating_line(): + "Input: a list of dataclasses with a separating line" + try: + from dataclasses import make_dataclass + + Person = make_dataclass("Person", ["name", "age", "height"]) + ld = [Person("Alice", 23, 169.5), SEPARATING_LINE, Person("Bob", 27, 175.0)] + result = tabulate(ld, headers="keys") + expected = "\n".join( + [ + "name age height", + "------ ----- --------", + "Alice 23 169.5", + "------ ----- --------", + "Bob 27 175", + ] + ) + assert_equal(expected, result) + except ImportError: + skip("test_py37orlater_list_of_dataclasses_keys is skipped") + + def test_list_bytes(): "Input: a list of bytes. (issue #192)" lb = [["你好".encode("utf-8")], ["你好"]] From b1ed1fda6f62b9069ef7d5871925399159d9dfc9 Mon Sep 17 00:00:00 2001 From: Perry Kundert Date: Thu, 20 Jul 2023 14:50:40 -0600 Subject: [PATCH 014/204] Fix support for separating lines --- tabulate/__init__.py | 13 ++++++------- test/test_output.py | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 7 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 11bb8655..7bdeabd4 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -2414,7 +2414,6 @@ def _format_table(fmt, headers, headersaligns, rows, colwidths, colaligns, is_mu append_row = _append_basic_row padded_headers = pad_row(headers, pad) - padded_rows = [pad_row(row, pad) for row in rows] if fmt.lineabove and "lineabove" not in hidden: _append_line(lines, padded_widths, colaligns, fmt.lineabove) @@ -2424,17 +2423,17 @@ def _format_table(fmt, headers, headersaligns, rows, colwidths, colaligns, is_mu if fmt.linebelowheader and "linebelowheader" not in hidden: _append_line(lines, padded_widths, colaligns, fmt.linebelowheader) - if padded_rows and fmt.linebetweenrows and "linebetweenrows" not in hidden: + if rows and fmt.linebetweenrows and "linebetweenrows" not in hidden: # initial rows with a line below - for row, ralign in zip(padded_rows[:-1], rowaligns): + for row, ralign in zip(rows[:-1], rowaligns): append_row( - lines, row, padded_widths, colaligns, fmt.datarow, rowalign=ralign + lines, pad_row(row, pad), padded_widths, colaligns, fmt.datarow, rowalign=ralign ) _append_line(lines, padded_widths, colaligns, fmt.linebetweenrows) # the last row without a line below append_row( lines, - padded_rows[-1], + pad_row(rows[-1], pad), padded_widths, colaligns, fmt.datarow, @@ -2448,13 +2447,13 @@ def _format_table(fmt, headers, headersaligns, rows, colwidths, colaligns, is_mu or fmt.lineabove or Line("", "", "", "") ) - for row in padded_rows: + for row in rows: # test to see if either the 1st column or the 2nd column (account for showindex) has # the SEPARATING_LINE flag if _is_separating_line(row): _append_line(lines, padded_widths, colaligns, separating_line) else: - append_row(lines, row, padded_widths, colaligns, fmt.datarow) + append_row(lines, pad_row(row, pad), padded_widths, colaligns, fmt.datarow) if fmt.linebelow and "linebelow" not in hidden: _append_line(lines, padded_widths, colaligns, fmt.linebelow) diff --git a/test/test_output.py b/test/test_output.py index d5724985..c6e0c4b5 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -257,6 +257,21 @@ def test_simple_with_sep_line(): assert_equal(expected, result) +def test_orgtbl_with_sep_line(): + "Output: orgtbl with headers and separating line" + expected = "\n".join( + [ + "| strings | numbers |", + "|-----------+-----------|", + "| spam | 41.9999 |", + "|-----------+-----------|", + "| eggs | 451 |", + ] + ) + result = tabulate(_test_table_with_sep_line, _test_table_headers, tablefmt="orgtbl") + assert_equal(expected, result) + + def test_readme_example_with_sep(): table = [["Earth", 6371], ["Mars", 3390], SEPARATING_LINE, ["Moon", 1737]] expected = "\n".join( @@ -311,6 +326,28 @@ def test_simple_multiline_2_with_sep_line(): assert_equal(expected, result) +def test_orgtbl_multiline_2_with_sep_line(): + "Output: simple with multiline cells" + expected = "\n".join( + [ + "| key | value |", + "|-------+-----------|", + "| foo | bar |", + "|-------+-----------|", + "| spam | multiline |", + "| | world |", + ] + ) + table = [ + ["key", "value"], + ["foo", "bar"], + SEPARATING_LINE, + ["spam", "multiline\nworld"], + ] + result = tabulate(table, headers="firstrow", stralign="center", tablefmt="orgtbl") + assert_equal(expected, result) + + def test_simple_headerless(): "Output: simple without headers" expected = "\n".join( From 392be0f2f02116baac48838b06970829b46c1cd7 Mon Sep 17 00:00:00 2001 From: Adam Lugowski Date: Sun, 27 Aug 2023 23:34:46 -0700 Subject: [PATCH 015/204] Fix separating line detection with ndarray values This code: ``` import numpy as np from tabulate import tabulate data = [[np.ones(1)]] print(tabulate(data)) ``` Throws a `FutureWarning` or a `ValueError` due to the comparison with `SEPARATING_LINE`. Fixes https://github.com/astanin/python-tabulate/issues/287 --- tabulate/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 11bb8655..22e12882 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -105,8 +105,8 @@ def _is_file(f): def _is_separating_line(row): row_type = type(row) is_sl = (row_type == list or row_type == str) and ( - (len(row) >= 1 and row[0] == SEPARATING_LINE) - or (len(row) >= 2 and row[1] == SEPARATING_LINE) + (len(row) >= 1 and row[0] is SEPARATING_LINE) + or (len(row) >= 2 and row[1] is SEPARATING_LINE) ) return is_sl From 6ea2a05552352ea78247ee791e1cf0d8574c13ef Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Wed, 11 Jan 2023 12:10:01 +0100 Subject: [PATCH 016/204] No need to import Unicode from future in Python 3 --- test/test_textwrapper.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/test/test_textwrapper.py b/test/test_textwrapper.py index f3070b18..88420be2 100644 --- a/test/test_textwrapper.py +++ b/test/test_textwrapper.py @@ -1,6 +1,4 @@ """Discretely test functionality of our custom TextWrapper""" -from __future__ import unicode_literals - import datetime from tabulate import _CustomTextWrap as CTW, tabulate From f078669f38e14a44ea85f725e226f7ec7f3093a8 Mon Sep 17 00:00:00 2001 From: Phill Zarfos Date: Sat, 21 Oct 2023 12:48:26 -0400 Subject: [PATCH 017/204] fix merge conflict in README.md file --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3996f7d3..0feb58a3 100644 --- a/README.md +++ b/README.md @@ -1123,5 +1123,5 @@ Bart Broere, Vilhelm Prytz, Alexander Gažo, Hugo van Kemenade, jamescooke, Matt Warner, Jérôme Provensal, Kevin Deldycke, Kian-Meng Ang, Kevin Patterson, Shodhan Save, cleoold, KOLANICH, Vijaya Krishna Kasula, Furcy Pin, Christian Fibich, Shaun Duncan, -Dimitri Papadopoulos, Racerroar. +Dimitri Papadopoulos, Élie Goudout, Racerroar, Phill Zarfos. From 4a8778008b984b93762f2b6f4cefb9443905a798 Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Thu, 21 Dec 2023 12:12:43 +0200 Subject: [PATCH 018/204] Add support for Python 3.12 --- appveyor.yml | 1 + tox.ini | 17 ++++++++++++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/appveyor.yml b/appveyor.yml index 4eb2dd8f..318a1d60 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -16,6 +16,7 @@ environment: - PYTHON: "C:\\Python39-x64" - PYTHON: "C:\\Python310-x64" - PYTHON: "C:\\Python311-x64" + - PYTHON: "C:\\Python312-x64" install: # Newer setuptools is needed for proper support of pyproject.toml diff --git a/tox.ini b/tox.ini index c6260d21..4c4fe066 100644 --- a/tox.ini +++ b/tox.ini @@ -8,7 +8,7 @@ # for testing and it is disabled by default. [tox] -envlist = lint, py{37, 38, 39, 310, 311} +envlist = lint, py{37, 38, 39, 310, 311, 312} isolated_build = True [testenv] @@ -105,6 +105,21 @@ deps = pandas wcwidth +[testenv:py312] +basepython = python3.12 +commands = pytest -v --doctest-modules --ignore benchmark.py {posargs} +deps = + pytest + +[testenv:py312-extra] +basepython = python3.12 +setenv = PYTHONDEVMODE = 1 +commands = pytest -v --doctest-modules --ignore benchmark.py {posargs} +deps = + pytest + numpy + pandas + wcwidth [flake8] max-complexity = 22 From 733be92058815b4295d8ed5858fa14d7b0aad890 Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Thu, 21 Dec 2023 12:18:54 +0200 Subject: [PATCH 019/204] Drop support for EOL Python 3.7 --- HOWTOPUBLISH | 2 +- README.md | 16 ++++++++-------- appveyor.yml | 9 +-------- pyproject.toml | 3 +-- tabulate/__init__.py | 6 +++--- tox.ini | 17 +---------------- 6 files changed, 15 insertions(+), 38 deletions(-) diff --git a/HOWTOPUBLISH b/HOWTOPUBLISH index 5be16ed2..795fc736 100644 --- a/HOWTOPUBLISH +++ b/HOWTOPUBLISH @@ -1,7 +1,7 @@ # update contributors and CHANGELOG in README # tag version release python3 benchmark.py # then update README -tox -e py37-extra,py38-extra,py39-extra,py310-extra +tox -e py38-extra,py39-extra,py310-extra,py311-extra,py312-extra python3 -m build -nswx . twine upload --repository-url https://test.pypi.org/legacy/ dist/* twine upload dist/* diff --git a/README.md b/README.md index 07ab28c7..944a2605 100644 --- a/README.md +++ b/README.md @@ -81,7 +81,7 @@ The following tabular data types are supported: - list of lists or another iterable of iterables - list or another iterable of dicts (keys as columns) - dict of iterables (keys as columns) -- list of dataclasses (Python 3.7+ only, field names as columns) +- list of dataclasses (field names as columns) - two-dimensional NumPy array - NumPy record arrays (names as columns) - pandas.DataFrame @@ -1074,14 +1074,14 @@ To run tests on all supported Python versions, make sure all Python interpreters, `pytest` and `tox` are installed, then run `tox` in the root of the project source tree. -On Linux `tox` expects to find executables like `python3.7`, `python3.8` etc. -On Windows it looks for `C:\Python37\python.exe`, `C:\Python38\python.exe` etc. respectively. +On Linux `tox` expects to find executables like `python3.11`, `python3.12` etc. +On Windows it looks for `C:\Python311\python.exe`, `C:\Python312\python.exe` etc. respectively. One way to install all the required versions of the Python interpreter is to use [pyenv](https://github.com/pyenv/pyenv). All versions can then be easily installed with something like: - pyenv install 3.7.12 - pyenv install 3.8.12 + pyenv install 3.11.7 + pyenv install 3.12.1 ... Don't forget to change your `PATH` so that `tox` knows how to find all the installed versions. Something like @@ -1089,10 +1089,10 @@ Don't forget to change your `PATH` so that `tox` knows how to find all the insta export PATH="${PATH}:${HOME}/.pyenv/shims" To test only some Python environments, use `-e` option. For example, to -test only against Python 3.7 and Python 3.10, run: +test only against Python 3.11 and Python 3.12, run: ```shell -tox -e py37,py310 +tox -e py311,py312 ``` in the root of the project source tree. @@ -1100,7 +1100,7 @@ in the root of the project source tree. To enable NumPy and Pandas tests, run: ```shell -tox -e py37-extra,py310-extra +tox -e py311-extra,py312-extra ``` (this may take a long time the first time, because NumPy and Pandas will diff --git a/appveyor.yml b/appveyor.yml index 318a1d60..d36b8c94 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -8,10 +8,8 @@ environment: # The list here is complete (excluding Python 2.6, which # isn't covered by this document) at the time of writing. - - PYTHON: "C:\\Python37" - PYTHON: "C:\\Python38" - PYTHON: "C:\\Python39" - - PYTHON: "C:\\Python37-x64" - PYTHON: "C:\\Python38-x64" - PYTHON: "C:\\Python39-x64" - PYTHON: "C:\\Python310-x64" @@ -30,9 +28,6 @@ build: off test_script: # Put your test command here. - # If you don't need to build C extensions on 64-bit Python 3.3 or 3.4, - # you can remove "build.cmd" from the front of the command, as it's - # only needed to support those cases. # Note that you must use the environment variable %PYTHON% to refer to # the interpreter you're using - Appveyor does not do anything special # to put the Python version you want to use on PATH. @@ -41,9 +36,7 @@ test_script: after_test: # This step builds your wheels. - # Again, you only need build.cmd if you're building C extensions for - # 64-bit Python 3.3/3.4. And you need to use %PYTHON% to get the correct - # interpreter + # Again, you need to use %PYTHON% to get the correct interpreter #- "build.cmd %PYTHON%\\python.exe setup.py bdist_wheel" - "%PYTHON%\\python.exe -m build -nswx ." diff --git a/pyproject.toml b/pyproject.toml index 5a8c1fd8..837747d7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -13,14 +13,13 @@ classifiers = [ "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Topic :: Software Development :: Libraries", ] -requires-python = ">=3.7" +requires-python = ">=3.8" dynamic = ["version"] [project.urls] diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 11bb8655..dbbe45dd 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1331,7 +1331,7 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"): * list of OrderedDicts (usually used with headers="keys") - * list of dataclasses (Python 3.7+ only, usually used with headers="keys") + * list of dataclasses (usually used with headers="keys") * 2D NumPy arrays @@ -1457,7 +1457,7 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"): and len(rows) > 0 and dataclasses.is_dataclass(rows[0]) ): - # Python 3.7+'s dataclass + # Python's dataclass field_names = [field.name for field in dataclasses.fields(rows[0])] if headers == "keys": headers = field_names @@ -1600,7 +1600,7 @@ def tabulate( The first required argument (`tabular_data`) can be a list-of-lists (or another iterable of iterables), a list of named tuples, a dictionary of iterables, an iterable of dictionaries, - an iterable of dataclasses (Python 3.7+), a two-dimensional NumPy array, + an iterable of dataclasses, a two-dimensional NumPy array, NumPy record array, or a Pandas' dataframe. diff --git a/tox.ini b/tox.ini index 4c4fe066..7fd65a7d 100644 --- a/tox.ini +++ b/tox.ini @@ -8,7 +8,7 @@ # for testing and it is disabled by default. [tox] -envlist = lint, py{37, 38, 39, 310, 311, 312} +envlist = lint, py{38, 39, 310, 311, 312} isolated_build = True [testenv] @@ -25,21 +25,6 @@ commands = python -m pre_commit run -a deps = pre-commit -[testenv:py37] -basepython = python3.7 -commands = pytest -v --doctest-modules --ignore benchmark.py {posargs} -deps = - pytest - -[testenv:py37-extra] -basepython = python3.7 -commands = pytest -v --doctest-modules --ignore benchmark.py {posargs} -deps = - pytest - numpy - pandas - wcwidth - [testenv:py38] basepython = python3.8 commands = pytest -v --doctest-modules --ignore benchmark.py {posargs} From 36fb3088a85c0855a0985a2f2206ed872e0c71e1 Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Thu, 21 Dec 2023 12:21:58 +0200 Subject: [PATCH 020/204] Fix Black and Flake8 --- tabulate/__init__.py | 41 +++++++++++++----- test/common.py | 3 +- test/test_output.py | 98 +++++++++++++++++++++++++------------------- 3 files changed, 87 insertions(+), 55 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index dbbe45dd..4b4cf2ce 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1271,7 +1271,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): @@ -1319,7 +1319,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: @@ -2202,15 +2203,19 @@ 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 @@ -2229,20 +2234,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 @@ -2267,7 +2277,14 @@ def tabulate( _reinsert_separating_lines(rows, separating_lines) return _format_table( - tablefmt, headers, aligns_headers, rows, minwidths, aligns, is_multiline, rowaligns=rowaligns + tablefmt, + headers, + aligns_headers, + rows, + minwidths, + aligns, + is_multiline, + rowaligns=rowaligns, ) @@ -2398,7 +2415,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 [] diff --git a/test/common.py b/test/common.py index 4cd37099..fe332595 100644 --- a/test/common.py +++ b/test/common.py @@ -2,6 +2,7 @@ from pytest import skip, raises # noqa import warnings + def assert_equal(expected, result): print("Expected:\n%s\n" % expected) print("Got:\n%s\n" % result) @@ -28,6 +29,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: @@ -41,4 +43,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]) - diff --git a/test/test_output.py b/test/test_output.py index d5724985..8a608095 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -2680,60 +2680,72 @@ def test_colalign_multi_with_sep_line(): expected = " one two\n\nthree four" assert_equal(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_equal(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_equal(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_equal(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" From a37d34af8ea72a6b3a5afb18862fe2dedb391690 Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade Date: Thu, 21 Dec 2023 12:22:26 +0200 Subject: [PATCH 021/204] Upgrade Python syntax with pyupgrade --py38-plus --- tabulate/__init__.py | 4 ++-- test/test_input.py | 2 +- test/test_textwrapper.py | 1 - 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 4b4cf2ce..6adacde3 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -224,7 +224,7 @@ def make_header_line(is_header, colwidths, colaligns): colwidths, [alignment[colalign] for colalign in colaligns] ) asciidoc_column_specifiers = [ - "{:d}{}".format(width, align) for width, align in asciidoc_alignments + f"{width:d}{align}" for width, align in asciidoc_alignments ] header_list = ['cols="' + (",".join(asciidoc_column_specifiers)) + '"'] @@ -1297,7 +1297,7 @@ def _prepend_row_index(rows, index): if isinstance(index, Sized) and len(index) != len(rows): raise ValueError( "index must be as long as the number of data rows: " - + "len(index)={} len(rows)={}".format(len(index), len(rows)) + + f"len(index)={len(index)} len(rows)={len(rows)}" ) sans_rows, separating_lines = _remove_separating_lines(rows) new_rows = [] diff --git a/test/test_input.py b/test/test_input.py index a178bd9d..721d03a1 100644 --- a/test/test_input.py +++ b/test/test_input.py @@ -522,7 +522,7 @@ def test_py37orlater_list_of_dataclasses_headers(): def test_list_bytes(): "Input: a list of bytes. (issue #192)" - lb = [["你好".encode("utf-8")], ["你好"]] + lb = [["你好".encode()], ["你好"]] expected = "\n".join( ["bytes", "---------------------------", r"b'\xe4\xbd\xa0\xe5\xa5\xbd'", "你好"] ) diff --git a/test/test_textwrapper.py b/test/test_textwrapper.py index f3070b18..c8feded5 100644 --- a/test/test_textwrapper.py +++ b/test/test_textwrapper.py @@ -1,5 +1,4 @@ """Discretely test functionality of our custom TextWrapper""" -from __future__ import unicode_literals import datetime From 4a5feba2346b294047222d8db3e7a483f4942cb9 Mon Sep 17 00:00:00 2001 From: Andrew Coffey Date: Tue, 2 Jan 2024 21:19:18 -0600 Subject: [PATCH 022/204] empty aligns no longer gives a KeyError --- tabulate/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 11bb8655..0b0d99b7 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -2207,7 +2207,7 @@ def tabulate( else: # default aligns = [numalign if ct in [int, float] else stralign for ct in coltypes] # then specific alignements - if colalign is not None: + if colalign is not None and aligns: 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) From 216a36ea30c37018641f54cc110579bc944c7574 Mon Sep 17 00:00:00 2001 From: Andrew Coffey Date: Tue, 2 Jan 2024 21:33:03 -0600 Subject: [PATCH 023/204] added regression test --- test/test_regression.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/test/test_regression.py b/test/test_regression.py index 8f60ce74..d2fc3a07 100644 --- a/test/test_regression.py +++ b/test/test_regression.py @@ -512,3 +512,14 @@ def test_numpy_int64_as_integer(): assert_equal(expected, result) except ImportError: raise skip("") + +def test_empty_table_with_colalign(): + "Regression: empty table with colalign kwarg" + table = tabulate([], ["a", "b", "c"], colalign=("center", "left", "left", "center")) + expected = "\n".join( + [ + "a b c", + "--- --- ---", + ] + ) + assert_equal(expected, table) From d19c2fbe1468bc5c4634e90e2823cfa970874930 Mon Sep 17 00:00:00 2001 From: devdanzin <74280297+devdanzin@users.noreply.github.com> Date: Fri, 12 Jan 2024 23:55:55 -0300 Subject: [PATCH 024/204] WIP: Try to fix tabulate._CustomTextWrap._handle_long_word breaking up ANSI escape codes. --- tabulate/__init__.py | 14 +++++++++++--- test/test_textwrapper.py | 38 +++++++++++++++++++++++++++++++++++++- 2 files changed, 48 insertions(+), 4 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 11bb8655..8dca8d6e 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -2540,10 +2540,18 @@ def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width): # take each charcter's width into account chunk = reversed_chunks[-1] i = 1 - while self._len(chunk[:i]) <= space_left: + while len(_strip_ansi(chunk)[:i]) <= space_left: i = i + 1 - cur_line.append(chunk[: i - 1]) - reversed_chunks[-1] = chunk[i - 1 :] + # Consider escape codes when breaking words up + total_escape_len = 0 + if _ansi_codes.search(chunk) is not None: + for group, _, _, _ in _ansi_codes.findall(chunk): + escape_len = len(group) + # FIXME: Needs to keep track of found groups and search from there + if group in chunk[: i + total_escape_len + escape_len - 1]: + total_escape_len += escape_len + cur_line.append(chunk[: i + total_escape_len - 1]) + reversed_chunks[-1] = chunk[i + total_escape_len - 1 :] # Otherwise, we have to preserve the long word intact. Only add # it to the current line if there's nothing already there -- diff --git a/test/test_textwrapper.py b/test/test_textwrapper.py index f3070b18..b02f5d15 100644 --- a/test/test_textwrapper.py +++ b/test/test_textwrapper.py @@ -3,7 +3,7 @@ import datetime -from tabulate import _CustomTextWrap as CTW, tabulate +from tabulate import _CustomTextWrap as CTW, tabulate, _strip_ansi from textwrap import TextWrapper as OTW from common import skip, assert_equal @@ -158,6 +158,42 @@ def test_wrap_color_line_splillover(): assert_equal(expected, result) +def test_wrap_color_line_longword(): + """TextWrapper: Wrap a line - preserve internal color tags and wrap them to + other lines when required, requires adding the colors tags to other lines as appropriate + and avoiding splitting escape codes.""" + data = "This_is_a_\033[31mtest_string_for_testing_TextWrap\033[0m_with_colors" + + expected = [ + "This_is_a_\033[31mte\033[0m", + "\033[31mst_string_fo\033[0m", + "\033[31mr_testing_Te\033[0m", + "\033[31mxtWrap\033[0m_with_", + "colors", + ] + wrapper = CTW(width=12) + result = wrapper.wrap(data) + assert_equal(expected, result) + + +def test_wrap_color_line_multiple_escapes(): + data = '012345(\x1b[32ma\x1b[0mbc\x1b[32mdefghij\x1b[0m)' + expected = [ + "012345(\x1b[32ma\x1b[0mbc\x1b[32mdefg\x1b[0m", + "\x1b[32mhij\x1b[0m)", + ] + wrapper = CTW(width=10) + result = wrapper.wrap(data) + assert_equal(expected, result) + clean_data = _strip_ansi(data) + for width in range(2, len(clean_data)): + # Currently fails with 14, 15 and 16, because a escape code gets split at the end + wrapper = CTW(width=width) + result = wrapper.wrap(data) + # print(width, result) + # Comparing after stripping ANSI should be enough to catch broken escape codes + assert_equal(clean_data, _strip_ansi("".join(result))) + def test_wrap_datetime(): """TextWrapper: Show that datetimes can be wrapped without crashing""" data = [ From d27d3668f5c06c7bfd85e0c51f88a65d63fbed34 Mon Sep 17 00:00:00 2001 From: devdanzin <74280297+devdanzin@users.noreply.github.com> Date: Sun, 14 Jan 2024 14:58:05 -0300 Subject: [PATCH 025/204] Fix breaking up of long words so it doesn't mess up ANSI escape codes. --- tabulate/__init__.py | 7 +++++-- test/test_textwrapper.py | 10 +++++----- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 8dca8d6e..f1561779 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -2540,16 +2540,19 @@ def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width): # take each charcter's width into account chunk = reversed_chunks[-1] i = 1 + # Only count printable characters, so strip_ansi first, index later. while len(_strip_ansi(chunk)[:i]) <= space_left: i = i + 1 # Consider escape codes when breaking words up total_escape_len = 0 + last_group = 0 if _ansi_codes.search(chunk) is not None: for group, _, _, _ in _ansi_codes.findall(chunk): escape_len = len(group) - # FIXME: Needs to keep track of found groups and search from there - if group in chunk[: i + total_escape_len + escape_len - 1]: + if group in chunk[last_group: i + total_escape_len + escape_len - 1]: total_escape_len += escape_len + found = _ansi_codes.search(chunk[last_group:]) + last_group += found.end() cur_line.append(chunk[: i + total_escape_len - 1]) reversed_chunks[-1] = chunk[i + total_escape_len - 1 :] diff --git a/test/test_textwrapper.py b/test/test_textwrapper.py index b02f5d15..bdae8c8b 100644 --- a/test/test_textwrapper.py +++ b/test/test_textwrapper.py @@ -177,23 +177,23 @@ def test_wrap_color_line_longword(): def test_wrap_color_line_multiple_escapes(): - data = '012345(\x1b[32ma\x1b[0mbc\x1b[32mdefghij\x1b[0m)' + data = "012345(\x1b[32ma\x1b[0mbc\x1b[32mdefghij\x1b[0m)" expected = [ - "012345(\x1b[32ma\x1b[0mbc\x1b[32mdefg\x1b[0m", - "\x1b[32mhij\x1b[0m)", + "012345(\x1b[32ma\x1b[0mbc\x1b[32m\x1b[0m", + "\x1b[32mdefghij\x1b[0m)", ] wrapper = CTW(width=10) result = wrapper.wrap(data) assert_equal(expected, result) + clean_data = _strip_ansi(data) for width in range(2, len(clean_data)): - # Currently fails with 14, 15 and 16, because a escape code gets split at the end wrapper = CTW(width=width) result = wrapper.wrap(data) - # print(width, result) # Comparing after stripping ANSI should be enough to catch broken escape codes assert_equal(clean_data, _strip_ansi("".join(result))) + def test_wrap_datetime(): """TextWrapper: Show that datetimes can be wrapped without crashing""" data = [ From e1c59c325081e10f4ef9db86a357eb9cb5be448e Mon Sep 17 00:00:00 2001 From: devdanzin <74280297+devdanzin@users.noreply.github.com> Date: Mon, 15 Jan 2024 08:08:05 -0300 Subject: [PATCH 026/204] Make assert_equal() print repr() instead of str(). --- test/common.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/common.py b/test/common.py index 4cd37099..75524ecf 100644 --- a/test/common.py +++ b/test/common.py @@ -3,8 +3,8 @@ import warnings def assert_equal(expected, result): - print("Expected:\n%s\n" % expected) - print("Got:\n%s\n" % result) + print("Expected:\n%r\n" % expected) + print("Got:\n%r\n" % result) assert expected == result From 3c6e4185f7f0d033074d1ed53f598c9cfc8abff1 Mon Sep 17 00:00:00 2001 From: George Schizas Date: Tue, 27 Feb 2024 13:28:48 +0200 Subject: [PATCH 027/204] Allow columns to wrap even if they have None values within them. --- tabulate/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 11bb8655..f4bb2de5 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1529,7 +1529,7 @@ def _wrap_text_to_colwidths(list_of_lists, colwidths, numparses=True): # Any future custom formatting of types (such as datetimes) # may need to be more explicit than just `str` of the object casted_cell = ( - str(cell) if _isnumber(cell) else _type(cell, numparse)(cell) + '' if cell is None else str(cell) if _isnumber(cell) else _type(cell, numparse)(cell) ) wrapped = [ "\n".join(wrapper.wrap(line)) From 3b2b69505b3962ace99ac69ee96da1224b477f1a Mon Sep 17 00:00:00 2001 From: George Schizas Date: Tue, 27 Feb 2024 13:42:58 +0200 Subject: [PATCH 028/204] Added a simple test for wrapping None values in cells --- test/test_textwrapper.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/test/test_textwrapper.py b/test/test_textwrapper.py index f3070b18..9fd26603 100644 --- a/test/test_textwrapper.py +++ b/test/test_textwrapper.py @@ -184,3 +184,27 @@ def test_wrap_datetime(): ] expected = "\n".join(expected) assert_equal(expected, result) + + +def test_wrap_none_value(): + """TextWrapper: Show that None can be wrapped without crashing""" + data = [ + ["First Entry", None], + ["Second Entry", None] + ] + headers = ["Title", "Value"] + result = tabulate(data, headers=headers, tablefmt="grid", maxcolwidths=[7, 5]) + + expected = [ + "+---------+---------+", + "| Title | Value |", + "+=========+=========+", + "| First | |", + "| Entry | |", + "+---------+---------+", + "| Second | |", + "| Entry | |", + "+---------+---------+", + ] + expected = "\n".join(expected) + assert_equal(expected, result) From 92cb7096adaf162de9cbf7da6b432bc72cf68819 Mon Sep 17 00:00:00 2001 From: Israel Roldan Date: Sat, 13 Apr 2024 00:24:13 -0600 Subject: [PATCH 029/204] Fixed the problem with the intfmt argument. --- tabulate/__init__.py | 2 ++ test/test_output.py | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 11bb8655..03880ee1 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1229,6 +1229,8 @@ def _format(val, valtype, floatfmt, intfmt, missingval="", has_invisible=True): if valtype is str: return f"{val}" elif valtype is int: + if isinstance(val, str): + intfmt = "" return format(val, intfmt) elif valtype is bytes: try: diff --git a/test/test_output.py b/test/test_output.py index d5724985..872e2741 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -1,4 +1,5 @@ """Test output of the various forms of tabular data.""" +import pytest import tabulate as tabulate_module from common import assert_equal, raises, skip, check_warnings @@ -2638,6 +2639,44 @@ def test_intfmt(): assert_equal(expected, result) +def test_intfmt_with_string_as_integer(): + "Output: integer format" + result = tabulate([[82642], ["1500"], [2463]], intfmt=",", tablefmt="plain") + expected = "82,642\n 1500\n 2,463" + assert_equal(expected, result) + + +@pytest.mark.skip(reason="It detects all values as floats but there are strings and integers.") +def test_intfmt_with_string_with_floats(): + "Output: integer format" + result = tabulate([[82000.38], ["1500.47"], ["2463"], [92165]], intfmt=",", tablefmt="plain") + expected = "82000.4\n 1500.47\n 2463\n92,165" + assert_equal(expected, result) + + +def test_intfmt_with_colors(): + "Regression: Align ANSI-colored values as if they were colorless." + colortable = [ + ("abcd", 42, "\x1b[31m42\x1b[0m"), + ("elfy", 1010, "\x1b[32m1010\x1b[0m"), + ] + colorheaders = ("test", "\x1b[34mtest\x1b[0m", "test") + formatted = tabulate(colortable, colorheaders, "grid", intfmt=",") + expected = "\n".join( + [ + "+--------+--------+--------+", + "| test | \x1b[34mtest\x1b[0m | test |", + "+========+========+========+", + "| abcd | 42 | \x1b[31m42\x1b[0m |", + "+--------+--------+--------+", + "| elfy | 1,010 | \x1b[32m1010\x1b[0m |", + "+--------+--------+--------+", + ] + ) + print(f"expected: {expected!r}\n\ngot: {formatted!r}\n") + assert_equal(expected, formatted) + + def test_empty_data_with_headers(): "Output: table with empty data and headers as firstrow" expected = "" From e45cac16676f0955b2fd05389d97b3e6f71fd66c Mon Sep 17 00:00:00 2001 From: Israel Roldan Date: Sat, 13 Apr 2024 16:09:47 -0600 Subject: [PATCH 030/204] Added validation for integer numbers format when the number is colored. --- tabulate/__init__.py | 9 +++++++++ test/test_output.py | 18 +++++++++--------- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 03880ee1..9e96606e 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1230,6 +1230,15 @@ def _format(val, valtype, floatfmt, intfmt, missingval="", has_invisible=True): return f"{val}" elif valtype is int: if isinstance(val, str): + val_striped = val.encode('unicode_escape').decode('utf-8') + colored = re.search(r'(\\[xX]+[0-9a-fA-F]+\[\d+[mM]+)([0-9.]+)(\\.*)$', val_striped) + if colored: + total_groups = len(colored.groups()) + if total_groups == 3: + digits = colored.group(2) + if digits.isdigit(): + val_new = colored.group(1) + format(int(digits), intfmt) + colored.group(3) + val = val_new.encode('utf-8').decode('unicode_escape') intfmt = "" return format(val, intfmt) elif valtype is bytes: diff --git a/test/test_output.py b/test/test_output.py index 872e2741..8d80d95f 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -2657,20 +2657,20 @@ def test_intfmt_with_string_with_floats(): def test_intfmt_with_colors(): "Regression: Align ANSI-colored values as if they were colorless." colortable = [ - ("abcd", 42, "\x1b[31m42\x1b[0m"), - ("elfy", 1010, "\x1b[32m1010\x1b[0m"), + ("\x1b[33mabc\x1b[0m", 42, "\x1b[31m42\x1b[0m"), + ("\x1b[35mdef\x1b[0m", 987654321, "\x1b[32m987654321\x1b[0m"), ] colorheaders = ("test", "\x1b[34mtest\x1b[0m", "test") formatted = tabulate(colortable, colorheaders, "grid", intfmt=",") expected = "\n".join( [ - "+--------+--------+--------+", - "| test | \x1b[34mtest\x1b[0m | test |", - "+========+========+========+", - "| abcd | 42 | \x1b[31m42\x1b[0m |", - "+--------+--------+--------+", - "| elfy | 1,010 | \x1b[32m1010\x1b[0m |", - "+--------+--------+--------+", + "+--------+-------------+-------------+", + "| test | \x1b[34mtest\x1b[0m | test |", + "+========+=============+=============+", + "| \x1b[33mabc\x1b[0m | 42 | \x1b[31m42\x1b[0m |", + "+--------+-------------+-------------+", + "| \x1b[35mdef\x1b[0m | 987,654,321 | \x1b[32m987,654,321\x1b[0m |", + "+--------+-------------+-------------+", ] ) print(f"expected: {expected!r}\n\ngot: {formatted!r}\n") From 23b3cc6537d2ca5cabad662a6ebf9dc371873d6c Mon Sep 17 00:00:00 2001 From: Israel Roldan Date: Sun, 14 Apr 2024 09:54:46 -0600 Subject: [PATCH 031/204] Updated the import of the PyTest jump decorator. --- test/test_output.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/test_output.py b/test/test_output.py index 8d80d95f..8d0207c5 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -1,5 +1,5 @@ """Test output of the various forms of tabular data.""" -import pytest +from pytest import mark import tabulate as tabulate_module from common import assert_equal, raises, skip, check_warnings @@ -2646,7 +2646,7 @@ def test_intfmt_with_string_as_integer(): assert_equal(expected, result) -@pytest.mark.skip(reason="It detects all values as floats but there are strings and integers.") +@mark.skip(reason="It detects all values as floats but there are strings and integers.") def test_intfmt_with_string_with_floats(): "Output: integer format" result = tabulate([[82000.38], ["1500.47"], ["2463"], [92165]], intfmt=",", tablefmt="plain") From 0655054b4115f59607bbbd37e60f0897dd267261 Mon Sep 17 00:00:00 2001 From: cdar Date: Tue, 25 Jun 2024 23:23:16 +0200 Subject: [PATCH 032/204] Fix support for separating lines --- tabulate/__init__.py | 9 ++++++--- test/test_output.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 11bb8655..ff8591cf 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -2304,6 +2304,8 @@ def _expand_iterable(original, num_desired, default): def _pad_row(cells, padding): if cells: + if cells == SEPARATING_LINE: + return SEPARATING_LINE pad = " " * padding padded_cells = [pad + cell + pad for cell in cells] return padded_cells @@ -2427,9 +2429,10 @@ def _format_table(fmt, headers, headersaligns, rows, colwidths, colaligns, is_mu if padded_rows and fmt.linebetweenrows and "linebetweenrows" not in hidden: # initial rows with a line below for row, ralign in zip(padded_rows[:-1], rowaligns): - append_row( - lines, row, padded_widths, colaligns, fmt.datarow, rowalign=ralign - ) + if row != SEPARATING_LINE: + append_row( + lines, row, padded_widths, colaligns, fmt.datarow, rowalign=ralign + ) _append_line(lines, padded_widths, colaligns, fmt.linebetweenrows) # the last row without a line below append_row( diff --git a/test/test_output.py b/test/test_output.py index d5724985..1768720f 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -335,6 +335,36 @@ def test_simple_headerless_with_sep_line(): assert_equal(expected, result) +def test_simple_headerless_with_sep_line_with_padding_in_tablefmt(): + "Output: simple without headers with sep line with padding in tablefmt" + expected = "\n".join( + [ + "|------|----------|", + "| spam | 41.9999 |", + "|------|----------|", + "| eggs | 451 |", + ] + ) + result = tabulate(_test_table_with_sep_line, tablefmt="github") + assert_equal(expected, result) + + +def test_simple_headerless_with_sep_line_with_linebetweenrows_in_tablefmt(): + "Output: simple without headers with sep line with linebetweenrows in tablefmt" + expected = "\n".join( + [ + "+------+----------+", + "| spam | 41.9999 |", + "+------+----------+", + "+------+----------+", + "| eggs | 451 |", + "+------+----------+", + ] + ) + result = tabulate(_test_table_with_sep_line, tablefmt="grid") + assert_equal(expected, result) + + def test_simple_multiline_headerless(): "Output: simple with multiline cells without headers" table = [["foo bar\nbaz\nbau", "hello"], ["", "multiline\nworld"]] From ef4a407058db61dd5b8320d55adbeaba6809841f Mon Sep 17 00:00:00 2001 From: Frederik Scheerer <35305292+frsche@users.noreply.github.com> Date: Tue, 9 Jul 2024 09:15:40 +0200 Subject: [PATCH 033/204] fix command line argument parser --- tabulate/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 11bb8655..4a114677 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -2701,8 +2701,8 @@ def _main(): try: opts, args = getopt.getopt( sys.argv[1:], - "h1o:s:F:A:f:", - ["help", "header", "output", "sep=", "float=", "int=", "align=", "format="], + "h1o:s:F:I:f:", + ["help", "header", "output=", "sep=", "float=", "int=", "colalign=", "format="], ) except getopt.GetoptError as e: print(e) From b49b98eaa1aaecf44ab2842c30d826e4b17ef184 Mon Sep 17 00:00:00 2001 From: Dan Nicholson Date: Wed, 25 Sep 2024 14:59:28 +0100 Subject: [PATCH 034/204] Add colon_grid table format --- tabulate/__init__.py | 74 ++++++++++++++++++++++++++++++++++++++++++-- test/test_output.py | 13 ++++++++ 2 files changed, 84 insertions(+), 3 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 11bb8655..bfc6fa08 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -134,6 +134,30 @@ def _pipe_line_with_colons(colwidths, colaligns): return "|" + "|".join(segments) + "|" +def _grid_segment_with_colons(colwidth, align): + """Return a segment of a horizontal line with optional colons which indicate + column's alignment in a grid table.""" + width = colwidth + if align == "right": + return ("=" * (width - 1)) + ":" + elif align == "center": + return ":" + ("=" * (width - 2)) + ":" + elif align == "left": + return ":" + ("=" * (width - 1)) + else: + return "=" * width + + +def _grid_line_with_colons(colwidths, colaligns): + """Return a horizontal line with optional colons to indicate column's alignment + in a grid table.""" + if not colaligns: + colaligns = [""] * len(colwidths) + segments = [_grid_segment_with_colons(w, a) for a, w in zip(colaligns, colwidths)] + return "+" + "+".join(segments) + "+" + + + def _mediawiki_row_with_attrs(separator, cell_values, colwidths, colaligns): alignment = { "left": "", @@ -400,6 +424,16 @@ def escape_empty(val): padding=1, with_header_hide=None, ), + "colon_grid": TableFormat( + lineabove=Line("+", "-", "+", "+"), + linebelowheader=_grid_line_with_colons, + linebetweenrows=Line("+", "-", "+", "+"), + linebelow=Line("+", "-", "+", "+"), + headerrow=DataRow("|", "|", "|"), + datarow=DataRow("|", "|", "|"), + padding=1, + with_header_hide=None, + ), "outline": TableFormat( lineabove=Line("+", "-", "+", "+"), linebelowheader=Line("+", "=", "+", "+"), @@ -693,6 +727,7 @@ def escape_empty(val): "mixed_grid": "mixed_grid", "double_grid": "double_grid", "fancy_grid": "fancy_grid", + "colon_grid": "colon_grid", "pipe": "pipe", "orgtbl": "orgtbl", "jira": "jira", @@ -1822,6 +1857,32 @@ def tabulate( │ eggs │ 451 │ ╘═══════════╧═══════════╛ + "colon_grid" is similar to "grid" but uses colons only to define + columnwise content alignment, with no whitespace padding: + + >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], + ... ["strings", "numbers"], "colon_grid")) + + +-----------+-----------+ + | strings | numbers | + +:==========+:==========+ + | spam | 41.9999 | + +-----------+-----------+ + | eggs | 451 | + +-----------+-----------+ + + >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], + ... ["strings", "numbers"], "colon_grid", + ... colalign=["right, left"])) + + +-----------+-----------+ + | strings | numbers | + +==========:+:==========+ + | spam | 41.9999 | + +-----------+-----------+ + | eggs | 451 | + +-----------+-----------+ + "outline" is the same as the "grid" format but doesn't draw lines between rows: >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], @@ -2138,6 +2199,10 @@ def tabulate( numalign = "decimal" if numalign == _DEFAULT_ALIGN else numalign stralign = "left" if stralign == _DEFAULT_ALIGN else stralign + if tablefmt == "colon_grid": + colglobalalign = "left" + headersglobalalign = "left" + # optimization: look for ANSI control codes once, # enable smart width functions only if a control code is found # @@ -2206,7 +2271,7 @@ def tabulate( aligns = [colglobalalign] * len(cols) else: # default aligns = [numalign if ct in [int, float] else stralign for ct in coltypes] - # then specific alignements + # then specific alignments if colalign is not None: assert isinstance(colalign, Iterable) if isinstance(colalign, str): @@ -2219,9 +2284,12 @@ def tabulate( minwidths = ( [width_fn(h) + min_padding for h in headers] if headers else [0] * len(cols) ) + aligns_copy = aligns.copy() + if tablefmt == "colon_grid": + aligns_copy = ["left"] * len(cols) cols = [ _align_column(c, a, minw, has_invisible, enable_widechars, is_multiline) - for c, a, minw in zip(cols, aligns, minwidths) + for c, a, minw in zip(cols, aligns_copy, minwidths) ] aligns_headers = None @@ -2233,7 +2301,7 @@ def tabulate( aligns_headers = [headersglobalalign] * len(t_cols) else: # default aligns_headers = aligns or [stralign] * len(headers) - # then specific header alignements + # then specific header alignments if headersalign is not None: assert isinstance(headersalign, Iterable) if isinstance(headersalign, str): diff --git a/test/test_output.py b/test/test_output.py index d5724985..491d2604 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -1413,6 +1413,19 @@ def test_fancy_grid_multiline_row_align(): result = tabulate(table, tablefmt="fancy_grid", rowalign=[None, "center", "bottom"]) assert_equal(expected, result) +def test_colon_grid(): + expected = "\n".join( + [ + "+------+------+", + "| H1 | H2 |", + "+=====:+:====:+", + "| 3 | 4 |", + "+------+------+", + ] + ) + result = tabulate([[3, 4]], headers=("H1", "H2"), tablefmt="colon_grid", colalign=["right", "center"]) + assert_equal(expected, result) + def test_outline(): "Output: outline with headers" From 277a900e710aa30864e32b5d91fa4c8d3a42f243 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 26 Sep 2024 10:16:29 +0200 Subject: [PATCH 035/204] Remove Python 3.8 from appveyor.yml, add x86 configurations for Python 3.10, 3.11, 3.12 --- appveyor.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index d36b8c94..eb255edd 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -8,9 +8,10 @@ environment: # The list here is complete (excluding Python 2.6, which # isn't covered by this document) at the time of writing. - - PYTHON: "C:\\Python38" - PYTHON: "C:\\Python39" - - PYTHON: "C:\\Python38-x64" + - PYTHON: "C:\\Python310" + - PYTHON: "C:\\Python311" + - PYTHON: "C:\\Python312" - PYTHON: "C:\\Python39-x64" - PYTHON: "C:\\Python310-x64" - PYTHON: "C:\\Python311-x64" From 275ff0f8aa11aca6ae419675e2101807ff5c4551 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 26 Sep 2024 10:20:15 +0200 Subject: [PATCH 036/204] Remove Python 3.8 support from pyproject.toml Python 3.8 EOL is a month from now (31 Oct 2024). --- pyproject.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 837747d7..8cb6216f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -13,13 +13,13 @@ classifiers = [ "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", "Topic :: Software Development :: Libraries", ] -requires-python = ">=3.8" +requires-python = ">=3.9" dynamic = ["version"] [project.urls] From dffb4679d8956eac6c78938e5293a008eee3160e Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 26 Sep 2024 10:25:27 +0200 Subject: [PATCH 037/204] Update circleci config to use Python 3.12 image --- .circleci/config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index ac9c5259..cd8bbc1f 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -8,7 +8,7 @@ jobs: docker: # specify the version you desire here # use `-browsers` prefix for selenium tests, e.g. `3.6.1-browsers` - - image: circleci/python:3.8 + - image: circleci/python:3.12 # Specify service dependencies here if necessary # CircleCI maintains a library of pre-built images From fc3f4e8eec4b8989465f737c8d29a60f0900d581 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 26 Sep 2024 10:35:36 +0200 Subject: [PATCH 038/204] appveyor.yml - comment x86 Python 3.9 configuration because it is missing prebuilt Pandas dependencies --- appveyor.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/appveyor.yml b/appveyor.yml index eb255edd..e92d9e41 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -8,7 +8,7 @@ environment: # The list here is complete (excluding Python 2.6, which # isn't covered by this document) at the time of writing. - - PYTHON: "C:\\Python39" + #- PYTHON: "C:\\Python39" - PYTHON: "C:\\Python310" - PYTHON: "C:\\Python311" - PYTHON: "C:\\Python312" From b35a36267f27b715758406a1bd38f66c965bb032 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 26 Sep 2024 11:31:09 +0200 Subject: [PATCH 039/204] add .circleci github key fingerprint --- .circleci/config.yml | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index cd8bbc1f..d5d36476 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -1,9 +1,16 @@ -# Python CircleCI 2.0 configuration file +# Python CircleCI 2.1 configuration file # -# Check https://circleci.com/docs/2.0/language-python/ for more details +# Check https://circleci.com/docs/language-python/ for more details # -version: 2 +version: 2.1 jobs: + # https://circleci.com/docs/github-integration/#create-additional-github-ssh-keys + deploy-job: + steps: + - add_ssh_keys: + fingerprints: + - "SHA256:f54rX6EuLbjtby+J672u/YhJ4iyTgAqOejxdcvVQf64" + build: docker: # specify the version you desire here From 6dff98017aedca304676436294219a0bd496e81b Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 26 Sep 2024 11:36:25 +0200 Subject: [PATCH 040/204] remove Circle-CI integration At this point it's easier to migrate to GitHub Actions than to rewrite .cicleci/config.yml according to Circle CI 2.1 syntax --- .circleci/config.yml | 67 -------------------------------------- .circleci/requirements.txt | 10 ------ README.md | 2 +- 3 files changed, 1 insertion(+), 78 deletions(-) delete mode 100644 .circleci/config.yml delete mode 100644 .circleci/requirements.txt diff --git a/.circleci/config.yml b/.circleci/config.yml deleted file mode 100644 index d5d36476..00000000 --- a/.circleci/config.yml +++ /dev/null @@ -1,67 +0,0 @@ -# Python CircleCI 2.1 configuration file -# -# Check https://circleci.com/docs/language-python/ for more details -# -version: 2.1 -jobs: - # https://circleci.com/docs/github-integration/#create-additional-github-ssh-keys - deploy-job: - steps: - - add_ssh_keys: - fingerprints: - - "SHA256:f54rX6EuLbjtby+J672u/YhJ4iyTgAqOejxdcvVQf64" - - build: - docker: - # specify the version you desire here - # use `-browsers` prefix for selenium tests, e.g. `3.6.1-browsers` - - image: circleci/python:3.12 - - # Specify service dependencies here if necessary - # CircleCI maintains a library of pre-built images - # documented at https://circleci.com/docs/2.0/circleci-images/ - # - image: circleci/postgres:9.4 - - working_directory: ~/repo - - steps: - - checkout - - # Download and cache dependencies - - restore_cache: - keys: - - v1-dependencies-{{ checksum ".circleci/requirements.txt" }} - # fallback to using the latest cache if no exact match is found - - v1-dependencies- - - - run: - name: install dependencies - command: | - python3 -m venv venv - . venv/bin/activate - pip install -r .circleci/requirements.txt - - - save_cache: - paths: - - ./venv - key: v1-dependencies-{{ checksum ".circleci/requirements.txt" }} - - - run: - name: build wheel - command: | - . venv/bin/activate - python -m build -nwx . - - - store_artifacts: - path: dist - destination: dist - - - run: - name: run tests - command: | - . venv/bin/activate - tox -e py38-extra - - - store_artifacts: - path: test-reports - destination: test-reports diff --git a/.circleci/requirements.txt b/.circleci/requirements.txt deleted file mode 100644 index ea5e80c9..00000000 --- a/.circleci/requirements.txt +++ /dev/null @@ -1,10 +0,0 @@ -pytest -tox -numpy -pandas -wcwidth -setuptools -pip -build -wheel -setuptools_scm diff --git a/README.md b/README.md index 944a2605..12309db1 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ pip install tabulate Build status ------------ -[![Build status](https://circleci.com/gh/astanin/python-tabulate.svg?style=svg)](https://circleci.com/gh/astanin/python-tabulate/tree/master) [![Build status](https://ci.appveyor.com/api/projects/status/8745yksvvol7h3d7/branch/master?svg=true)](https://ci.appveyor.com/project/astanin/python-tabulate/branch/master) +[![Build status](https://ci.appveyor.com/api/projects/status/8745yksvvol7h3d7/branch/master?svg=true)](https://ci.appveyor.com/project/astanin/python-tabulate/branch/master) Library usage ------------- From 277e649579842878059464bc32f0e97aff287d29 Mon Sep 17 00:00:00 2001 From: Dan Nicholson Date: Thu, 26 Sep 2024 14:11:24 +0100 Subject: [PATCH 041/204] Correct alignment of text in docstring examples --- tabulate/__init__.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index bfc6fa08..e61e57cb 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1864,11 +1864,11 @@ def tabulate( ... ["strings", "numbers"], "colon_grid")) +-----------+-----------+ - | strings | numbers | + | strings | numbers | +:==========+:==========+ - | spam | 41.9999 | + | spam | 41.9999 | +-----------+-----------+ - | eggs | 451 | + | eggs | 451 | +-----------+-----------+ >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], @@ -1876,11 +1876,11 @@ def tabulate( ... colalign=["right, left"])) +-----------+-----------+ - | strings | numbers | + | strings | numbers | +==========:+:==========+ - | spam | 41.9999 | + | spam | 41.9999 | +-----------+-----------+ - | eggs | 451 | + | eggs | 451 | +-----------+-----------+ "outline" is the same as the "grid" format but doesn't draw lines between rows: From 4a17bc776fbc911e2d54f800e1d66bb545fdb314 Mon Sep 17 00:00:00 2001 From: Dan Nicholson Date: Thu, 26 Sep 2024 14:17:10 +0100 Subject: [PATCH 042/204] Document changes required for colon_grid format --- tabulate/__init__.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index e61e57cb..5acc98f8 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -2199,6 +2199,9 @@ def tabulate( numalign = "decimal" if numalign == _DEFAULT_ALIGN else numalign stralign = "left" if stralign == _DEFAULT_ALIGN else stralign + # 'colon_grid' uses colons in the line beneath the header to represent a column's + # alignment instead of literally aligning the text differently. Hence, + # left alignment of the data in the text output is enforced. if tablefmt == "colon_grid": colglobalalign = "left" headersglobalalign = "left" @@ -2285,6 +2288,8 @@ def tabulate( [width_fn(h) + min_padding for h in headers] if headers else [0] * len(cols) ) aligns_copy = aligns.copy() + # Reset alignments in copy of alignments list to "left" for 'colon_grid' format, + # which enforces left alignment in the text output of the data. if tablefmt == "colon_grid": aligns_copy = ["left"] * len(cols) cols = [ From 4440c1ed7842fd3c652b884361dbbead905cca4a Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 26 Sep 2024 15:31:05 +0200 Subject: [PATCH 043/204] add GitHub Actions workflow based on tox-gh-actions, create a map of tox environments --- .github/workflows/github-actions-tox.yml | 25 ++++++++++++++++++++++++ README.md | 2 +- tox.ini | 7 +++++++ 3 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/github-actions-tox.yml diff --git a/.github/workflows/github-actions-tox.yml b/.github/workflows/github-actions-tox.yml new file mode 100644 index 00000000..35be5cd2 --- /dev/null +++ b/.github/workflows/github-actions-tox.yml @@ -0,0 +1,25 @@ +name: python-tabulate + +on: + - push + - pull_request + +jobs: + build: + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ['3.9', '3.10', '3.11', '3.12'] + + steps: + - uses: actions/checkout@v3 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + - name: Install dependencies + run: | + python -m pip install --upgrade pip + python -m pip install tox tox-gh-actions + - name: Test with tox + run: tox diff --git a/README.md b/README.md index 12309db1..0023806f 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ pip install tabulate Build status ------------ -[![Build status](https://ci.appveyor.com/api/projects/status/8745yksvvol7h3d7/branch/master?svg=true)](https://ci.appveyor.com/project/astanin/python-tabulate/branch/master) +[![python-tabulate](https://github.com/astanin/python-tabulate/actions/workflows/github-actions-tox.yml/badge.svg)](https://github.com/astanin/python-tabulate/actions/workflows/github-actions-tox.yml) [![Build status](https://ci.appveyor.com/api/projects/status/8745yksvvol7h3d7/branch/master?svg=true)](https://ci.appveyor.com/project/astanin/python-tabulate/branch/master) Library usage ------------- diff --git a/tox.ini b/tox.ini index 7fd65a7d..92939c24 100644 --- a/tox.ini +++ b/tox.ini @@ -11,6 +11,13 @@ envlist = lint, py{38, 39, 310, 311, 312} isolated_build = True +[gh-actions] +python = + 3.9: py39 + 3.10: py310 + 3.11: py311 + 3.12: py312 + [testenv] commands = pytest -v --doctest-modules --ignore benchmark.py {posargs} deps = From 34310479571d2a1d067883bc9b90e4358c1040fe Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 26 Sep 2024 15:39:47 +0200 Subject: [PATCH 044/204] skip all x86 builds on appveyor because they lack dependencies --- appveyor.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index e92d9e41..12bd7726 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -9,9 +9,9 @@ environment: # isn't covered by this document) at the time of writing. #- PYTHON: "C:\\Python39" - - PYTHON: "C:\\Python310" - - PYTHON: "C:\\Python311" - - PYTHON: "C:\\Python312" + #- PYTHON: "C:\\Python310" + #- PYTHON: "C:\\Python311" + #- PYTHON: "C:\\Python312" - PYTHON: "C:\\Python39-x64" - PYTHON: "C:\\Python310-x64" - PYTHON: "C:\\Python311-x64" From 5a7ab7fb482f990bc7bb2061b0d8c7d579c01188 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 26 Sep 2024 16:05:43 +0200 Subject: [PATCH 045/204] enable extra tests in GitHub Actions --- tox.ini | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tox.ini b/tox.ini index 92939c24..b37e0aab 100644 --- a/tox.ini +++ b/tox.ini @@ -13,10 +13,10 @@ isolated_build = True [gh-actions] python = - 3.9: py39 - 3.10: py310 - 3.11: py311 - 3.12: py312 + 3.9: py39-extra + 3.10: py310-extra + 3.11: py311-extra + 3.12: py312-extra [testenv] commands = pytest -v --doctest-modules --ignore benchmark.py {posargs} From 18d7b50edd4e6d05d8ee77ab5a043717fe1ef966 Mon Sep 17 00:00:00 2001 From: Dan Nicholson Date: Thu, 26 Sep 2024 15:07:50 +0100 Subject: [PATCH 046/204] Expand tests for colon_grid --- test/test_output.py | 78 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/test/test_output.py b/test/test_output.py index 491d2604..25b99a9a 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -1413,7 +1413,9 @@ def test_fancy_grid_multiline_row_align(): result = tabulate(table, tablefmt="fancy_grid", rowalign=[None, "center", "bottom"]) assert_equal(expected, result) + def test_colon_grid(): + "Output: colon_grid with two columns aligned left and center" expected = "\n".join( [ "+------+------+", @@ -1427,6 +1429,82 @@ def test_colon_grid(): assert_equal(expected, result) +def test_colon_grid_wide_characters(): + "Output: colon_grid with wide chars in header" + try: + import wcwidth # noqa + except ImportError: + skip("test_colon_grid_wide_characters is skipped") + headers = list(_test_table_headers) + headers[1] = "配列" + expected = "\n".join( + [ + "+-----------+---------+", + "| strings | 配列 |", + "+:==========+========:+", + "| spam | 41.9999 |", + "+-----------+---------+", + "| eggs | 451 |", + "+-----------+---------+", + ] + ) + result = tabulate(_test_table, headers, tablefmt="colon_grid", colalign=["left", "right"]) + assert_equal(expected, result) + + +def test_colon_grid_headerless(): + "Output: colon_grid without headers" + expected = "\n".join( + [ + "+------+---------+", + "| spam | 41.9999 |", + "+------+---------+", + "| eggs | 451 |", + "+------+---------+", + ] + ) + result = tabulate(_test_table, tablefmt="colon_grid") + assert_equal(expected, result) + + +def test_colon_grid_multiline(): + "Output: colon_grid with multiline cells" + table = [["Data\n5", "33\n3"]] + headers = ["H1\n1", "H2\n2"] + expected = "\n".join( + [ + "+------+------+", + "| H1 | H2 |", + "| 1 | 2 |", + "+:=====+:=====+", + "| Data | 33 |", + "| 5 | 3 |", + "+------+------+", + ] + ) + result = tabulate(table, headers, tablefmt="colon_grid") + assert_equal(expected, result) + + +def test_colon_grid_with_empty_cells(): + table = [["A", ""], ["", "B"]] + headers = ["H1", "H2"] + alignments = ["center", "right"] + expected = "\n".join( + [ + "+------+------+", + "| H1 | H2 |", + "+:====:+=====:+", + "| A | |", + "+------+------+", + "| | B |", + "+------+------+", + ] + ) + result = tabulate(table, headers, tablefmt="colon_grid", colalign=alignments) + assert_equal(expected, result) + + def test_outline(): "Output: outline with headers" expected = "\n".join( From db5cdd0cc88f2e1a4b29dfa4ea08df07bf24388c Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 26 Sep 2024 16:09:31 +0200 Subject: [PATCH 047/204] install pytest, numpy and pandas in Github Actions workflow --- .github/workflows/github-actions-tox.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/github-actions-tox.yml b/.github/workflows/github-actions-tox.yml index 35be5cd2..98c814ab 100644 --- a/.github/workflows/github-actions-tox.yml +++ b/.github/workflows/github-actions-tox.yml @@ -20,6 +20,7 @@ jobs: - name: Install dependencies run: | python -m pip install --upgrade pip + python -m pip install pytest numpy pandas python -m pip install tox tox-gh-actions - name: Test with tox run: tox From bdb639e650d9033a07d17e8eded9a908f08e101d Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 26 Sep 2024 16:21:55 +0200 Subject: [PATCH 048/204] rewrite GitHub Action using explicit reference to tox environment with -extra suffix --- .github/workflows/github-actions-tox.yml | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/.github/workflows/github-actions-tox.yml b/.github/workflows/github-actions-tox.yml index 98c814ab..178b2124 100644 --- a/.github/workflows/github-actions-tox.yml +++ b/.github/workflows/github-actions-tox.yml @@ -12,15 +12,13 @@ jobs: python-version: ['3.9', '3.10', '3.11', '3.12'] steps: - - uses: actions/checkout@v3 - - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v4 - with: - python-version: ${{ matrix.python-version }} - - name: Install dependencies - run: | - python -m pip install --upgrade pip - python -m pip install pytest numpy pandas - python -m pip install tox tox-gh-actions - - name: Test with tox - run: tox + - uses: actions/checkout@v4 + - name: Setup Python + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python }} + - name: Install tox and any other packages + run: pip install tox pytest numpy pandas + - name: Run tox + # Run tox using the version of Python in `PATH` + run: tox -e py${{ matrix.python}}-extra From ec79fe0381d6d89afd0d4d4075282ecb26349f19 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 26 Sep 2024 16:32:00 +0200 Subject: [PATCH 049/204] configure GitHub Action using tox-gh instead of tox-gh-actions --- .github/workflows/github-actions-tox.yml | 22 ++++++++++++---------- tox.ini | 2 +- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/.github/workflows/github-actions-tox.yml b/.github/workflows/github-actions-tox.yml index 178b2124..0b890581 100644 --- a/.github/workflows/github-actions-tox.yml +++ b/.github/workflows/github-actions-tox.yml @@ -12,13 +12,15 @@ jobs: python-version: ['3.9', '3.10', '3.11', '3.12'] steps: - - uses: actions/checkout@v4 - - name: Setup Python - uses: actions/setup-python@v5 - with: - python-version: ${{ matrix.python }} - - name: Install tox and any other packages - run: pip install tox pytest numpy pandas - - name: Run tox - # Run tox using the version of Python in `PATH` - run: tox -e py${{ matrix.python}}-extra + - uses: actions/checkout@v34 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + - name: Install dependencies + run: | + python -m pip install --upgrade pip + python -m pip install pytest numpy pandas + python -m pip install tox tox-gh + - name: Test with tox + run: tox diff --git a/tox.ini b/tox.ini index b37e0aab..a7fe513f 100644 --- a/tox.ini +++ b/tox.ini @@ -11,7 +11,7 @@ envlist = lint, py{38, 39, 310, 311, 312} isolated_build = True -[gh-actions] +[gh] python = 3.9: py39-extra 3.10: py310-extra From 4bd335c585b9d9445ca3bdc3efb7a41e6defc1c7 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 26 Sep 2024 16:33:16 +0200 Subject: [PATCH 050/204] fix typo in github-actions-tox.yml --- .github/workflows/github-actions-tox.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/github-actions-tox.yml b/.github/workflows/github-actions-tox.yml index 0b890581..e39e44f2 100644 --- a/.github/workflows/github-actions-tox.yml +++ b/.github/workflows/github-actions-tox.yml @@ -12,7 +12,7 @@ jobs: python-version: ['3.9', '3.10', '3.11', '3.12'] steps: - - uses: actions/checkout@v34 + - uses: actions/checkout@v4 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v4 with: From 8cd28a3a36bae2daacbc3333b19fdbb344a39177 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 26 Sep 2024 16:36:58 +0200 Subject: [PATCH 051/204] rewrite GitHub Action using pytest --- .github/workflows/github-actions-tox.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/github-actions-tox.yml b/.github/workflows/github-actions-tox.yml index e39e44f2..9adabb7c 100644 --- a/.github/workflows/github-actions-tox.yml +++ b/.github/workflows/github-actions-tox.yml @@ -21,6 +21,6 @@ jobs: run: | python -m pip install --upgrade pip python -m pip install pytest numpy pandas - python -m pip install tox tox-gh - - name: Test with tox - run: tox + - name: Run tests + run: | + pytest -v --doctest-modules --ignore benchmark.py From 968f25851eea82bff2c4f10d46035164ff54418e Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 26 Sep 2024 16:40:59 +0200 Subject: [PATCH 052/204] apply black --- tabulate/__init__.py | 2 +- test/test_cli.py | 1 - test/test_internal.py | 20 +++++++++++++++++--- test/test_output.py | 5 ++++- test/test_textwrapper.py | 3 ++- 5 files changed, 24 insertions(+), 7 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 874ad90f..704bc5bb 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -2762,7 +2762,7 @@ def _main(): print(usage) sys.exit(0) files = [sys.stdin] if not args else args - with (sys.stdout if outfile == "-" else open(outfile, "w")) as out: + with sys.stdout if outfile == "-" else open(outfile, "w") as out: for f in files: if f == "-": f = sys.stdin diff --git a/test/test_cli.py b/test/test_cli.py index ce85f198..e71572d3 100644 --- a/test/test_cli.py +++ b/test/test_cli.py @@ -2,7 +2,6 @@ """ - import os import sys diff --git a/test/test_internal.py b/test/test_internal.py index 64e1d12c..17107c6d 100644 --- a/test/test_internal.py +++ b/test/test_internal.py @@ -180,9 +180,16 @@ def test_wrap_text_wide_chars(): except ImportError: skip("test_wrap_text_wide_chars is skipped") - rows = [["청자청자청자청자청자", "약간 감싸면 더 잘 보일 수있는 다소 긴 설명입니다"]] + rows = [ + ["청자청자청자청자청자", "약간 감싸면 더 잘 보일 수있는 다소 긴 설명입니다"] + ] widths = [5, 20] - expected = [["청자\n청자\n청자\n청자\n청자", "약간 감싸면 더 잘\n보일 수있는 다소 긴\n설명입니다"]] + expected = [ + [ + "청자\n청자\n청자\n청자\n청자", + "약간 감싸면 더 잘\n보일 수있는 다소 긴\n설명입니다", + ] + ] result = T._wrap_text_to_colwidths(rows, widths) assert_equal(expected, result) @@ -239,7 +246,14 @@ def test_wrap_text_to_colwidths_colors_wide_char(): except ImportError: skip("test_wrap_text_to_colwidths_colors_wide_char is skipped") - data = [[("\033[31m약간 감싸면 더 잘 보일 수있는 다소 긴" " 설명입니다 설명입니다 설명입니다 설명입니다 설명\033[0m")]] + data = [ + [ + ( + "\033[31m약간 감싸면 더 잘 보일 수있는 다소 긴" + " 설명입니다 설명입니다 설명입니다 설명입니다 설명\033[0m" + ) + ] + ] result = T._wrap_text_to_colwidths(data, [30]) expected = [ diff --git a/test/test_output.py b/test/test_output.py index 260ed315..fe9e486a 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -136,7 +136,10 @@ def test_plain_maxcolwidth_autowraps_wide_chars(): table = [ ["hdr", "fold"], - ["1", "약간 감싸면 더 잘 보일 수있는 다소 긴 설명입니다 설명입니다 설명입니다 설명입니다 설명"], + [ + "1", + "약간 감싸면 더 잘 보일 수있는 다소 긴 설명입니다 설명입니다 설명입니다 설명입니다 설명", + ], ] expected = "\n".join( [ diff --git a/test/test_textwrapper.py b/test/test_textwrapper.py index c8feded5..1f134fd3 100644 --- a/test/test_textwrapper.py +++ b/test/test_textwrapper.py @@ -143,7 +143,8 @@ def test_wrap_color_in_single_line(): def test_wrap_color_line_splillover(): """TextWrapper: Wrap a line - preserve internal color tags and wrap them to - other lines when required, requires adding the colors tags to other lines as appropriate""" + other lines when required, requires adding the colors tags to other lines as appropriate + """ # This has both a text color and a background color data = "This is a \033[31mtest string for testing TextWrap\033[0m with colors" From 4e97640cbc53d7dfa7f5a1e635f104852debb2bf Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 26 Sep 2024 16:42:10 +0200 Subject: [PATCH 053/204] fix E721 warning in tabulate/__init__.py --- tabulate/__init__.py | 2 +- test/test_internal.py | 13 ++----------- 2 files changed, 3 insertions(+), 12 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 704bc5bb..06600724 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -103,7 +103,7 @@ def _is_file(f): def _is_separating_line_value(value): - return type(value) == str and value.strip() == SEPARATING_LINE + return type(value) is str and value.strip() == SEPARATING_LINE def _is_separating_line(row): diff --git a/test/test_internal.py b/test/test_internal.py index 17107c6d..e7564d37 100644 --- a/test/test_internal.py +++ b/test/test_internal.py @@ -180,9 +180,7 @@ def test_wrap_text_wide_chars(): except ImportError: skip("test_wrap_text_wide_chars is skipped") - rows = [ - ["청자청자청자청자청자", "약간 감싸면 더 잘 보일 수있는 다소 긴 설명입니다"] - ] + rows = [["청자청자청자청자청자", "약간 감싸면 더 잘 보일 수있는 다소 긴 설명입니다"]] widths = [5, 20] expected = [ [ @@ -246,14 +244,7 @@ def test_wrap_text_to_colwidths_colors_wide_char(): except ImportError: skip("test_wrap_text_to_colwidths_colors_wide_char is skipped") - data = [ - [ - ( - "\033[31m약간 감싸면 더 잘 보일 수있는 다소 긴" - " 설명입니다 설명입니다 설명입니다 설명입니다 설명\033[0m" - ) - ] - ] + data = [[("\033[31m약간 감싸면 더 잘 보일 수있는 다소 긴" " 설명입니다 설명입니다 설명입니다 설명입니다 설명\033[0m")]] result = T._wrap_text_to_colwidths(data, [30]) expected = [ From 10f7b758fdcace9bcce3d14225ddadbe0f17e40e Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 26 Sep 2024 16:43:16 +0200 Subject: [PATCH 054/204] rename GitHub Action workflow --- .github/workflows/{github-actions-tox.yml => tabulate.yml} | 0 README.md | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) rename .github/workflows/{github-actions-tox.yml => tabulate.yml} (100%) diff --git a/.github/workflows/github-actions-tox.yml b/.github/workflows/tabulate.yml similarity index 100% rename from .github/workflows/github-actions-tox.yml rename to .github/workflows/tabulate.yml diff --git a/README.md b/README.md index 0023806f..543576d0 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ pip install tabulate Build status ------------ -[![python-tabulate](https://github.com/astanin/python-tabulate/actions/workflows/github-actions-tox.yml/badge.svg)](https://github.com/astanin/python-tabulate/actions/workflows/github-actions-tox.yml) [![Build status](https://ci.appveyor.com/api/projects/status/8745yksvvol7h3d7/branch/master?svg=true)](https://ci.appveyor.com/project/astanin/python-tabulate/branch/master) +[![python-tabulate](https://github.com/astanin/python-tabulate/actions/workflows/tabulate.yml/badge.svg)](https://github.com/astanin/python-tabulate/actions/workflows/tabulate.yml) [![Build status](https://ci.appveyor.com/api/projects/status/8745yksvvol7h3d7/branch/master?svg=true)](https://ci.appveyor.com/project/astanin/python-tabulate/branch/master) Library usage ------------- From 97b67f374871c5d1dc706072573f08f3acad7295 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 26 Sep 2024 16:54:23 +0200 Subject: [PATCH 055/204] add GitHub Action workflow lint which runs pre_commit actions --- .github/workflows/lint.yml | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 .github/workflows/lint.yml diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 00000000..7e7c906b --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,26 @@ +name: lint + +on: + - push + - pull_request + +jobs: + build: + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ['3.12'] + + steps: + - uses: actions/checkout@v4 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + - name: Install dependencies + run: | + python -m pip install --upgrade pip + python -m pip install tox tox-gh + - name: Run linters + run: | + tox -e lint From 2855363cf7d8ad088b55a45bd16116f1edef24e8 Mon Sep 17 00:00:00 2001 From: Dan Nicholson Date: Thu, 26 Sep 2024 16:49:11 +0100 Subject: [PATCH 056/204] Fix doctests for colon_grid --- tabulate/__init__.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 5acc98f8..b0d9612f 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1862,7 +1862,6 @@ def tabulate( >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], ... ["strings", "numbers"], "colon_grid")) - +-----------+-----------+ | strings | numbers | +:==========+:==========+ @@ -1873,8 +1872,7 @@ def tabulate( >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], ... ["strings", "numbers"], "colon_grid", - ... colalign=["right, left"])) - + ... colalign=["right", "left"])) +-----------+-----------+ | strings | numbers | +==========:+:==========+ From 049d7d9701d70a0b05c405b574f0b69925ac51fa Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 26 Sep 2024 18:31:44 +0200 Subject: [PATCH 057/204] apply black to the PR branch and fix lint errors --- README.md | 2 +- tabulate/__init__.py | 42 ++++++++++++++++++++++++++++++++--------- test/common.py | 2 ++ test/test_output.py | 16 ++++++++++++---- test/test_regression.py | 1 + 5 files changed, 49 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index b596cf5b..52c76440 100644 --- a/README.md +++ b/README.md @@ -131,7 +131,7 @@ When data is a list of dictionaries, a dictionary can be passed as `headers` to replace the keys with other column labels: ```pycon ->>> print(tabulate([{1: "Alice", 2: 24}, {1: "Bob", 2: 19}], +>>> print(tabulate([{1: "Alice", 2: 24}, {1: "Bob", 2: 19}], ... headers={1: "Name", 2: "Age"})) Name Age ------ ----- diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 63d8d328..598cb4ea 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -160,7 +160,6 @@ def _grid_line_with_colons(colwidths, colaligns): return "+" + "+".join(segments) + "+" - def _mediawiki_row_with_attrs(separator, cell_values, colwidths, colaligns): alignment = { "left": "", @@ -1160,10 +1159,12 @@ def _align_column( has_invisible=True, enable_widechars=False, is_multiline=False, - preserve_whitespace=False + preserve_whitespace=False, ): """[string] -> [padded_string]""" - strings, padfn = _align_column_choose_padfn(strings, alignment, has_invisible, preserve_whitespace) + strings, padfn = _align_column_choose_padfn( + strings, alignment, has_invisible, preserve_whitespace + ) width_fn = _align_column_choose_width_fn( has_invisible, enable_widechars, is_multiline ) @@ -1269,15 +1270,21 @@ def _format(val, valtype, floatfmt, intfmt, missingval="", has_invisible=True): return f"{val}" elif valtype is int: if isinstance(val, str): - val_striped = val.encode('unicode_escape').decode('utf-8') - colored = re.search(r'(\\[xX]+[0-9a-fA-F]+\[\d+[mM]+)([0-9.]+)(\\.*)$', val_striped) + val_striped = val.encode("unicode_escape").decode("utf-8") + colored = re.search( + r"(\\[xX]+[0-9a-fA-F]+\[\d+[mM]+)([0-9.]+)(\\.*)$", val_striped + ) if colored: total_groups = len(colored.groups()) if total_groups == 3: digits = colored.group(2) if digits.isdigit(): - val_new = colored.group(1) + format(int(digits), intfmt) + colored.group(3) - val = val_new.encode('utf-8').decode('unicode_escape') + val_new = ( + colored.group(1) + + format(int(digits), intfmt) + + colored.group(3) + ) + val = val_new.encode("utf-8").decode("unicode_escape") intfmt = "" return format(val, intfmt) elif valtype is bytes: @@ -2322,7 +2329,15 @@ def tabulate( if tablefmt == "colon_grid": aligns_copy = ["left"] * len(cols) cols = [ - _align_column(c, a, minw, has_invisible, enable_widechars, is_multiline, preserve_whitespace) + _align_column( + c, + a, + minw, + has_invisible, + enable_widechars, + is_multiline, + preserve_whitespace, + ) for c, a, minw in zip(cols, aligns_copy, minwidths) ] @@ -2819,7 +2834,16 @@ def _main(): opts, args = getopt.getopt( sys.argv[1:], "h1o:s:F:I:f:", - ["help", "header", "output=", "sep=", "float=", "int=", "colalign=", "format="], + [ + "help", + "header", + "output=", + "sep=", + "float=", + "int=", + "colalign=", + "format=", + ], ) except getopt.GetoptError as e: print(e) diff --git a/test/common.py b/test/common.py index ca5a0697..fe332595 100644 --- a/test/common.py +++ b/test/common.py @@ -2,11 +2,13 @@ from pytest import skip, raises # noqa import warnings + def assert_equal(expected, result): print("Expected:\n%s\n" % expected) print("Got:\n%s\n" % result) assert expected == result + def assert_in(result, expected_set): nums = range(1, len(expected_set) + 1) for i, expected in zip(nums, expected_set): diff --git a/test/test_output.py b/test/test_output.py index c90f90cd..059742c1 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -1,7 +1,6 @@ """Test output of the various forms of tabular data.""" from pytest import mark -import tabulate as tabulate_module from common import assert_equal, raises, skip, check_warnings from tabulate import tabulate, simple_separated_format, SEPARATING_LINE @@ -1459,7 +1458,12 @@ def test_colon_grid(): "+------+------+", ] ) - result = tabulate([[3, 4]], headers=("H1", "H2"), tablefmt="colon_grid", colalign=["right", "center"]) + result = tabulate( + [[3, 4]], + headers=("H1", "H2"), + tablefmt="colon_grid", + colalign=["right", "center"], + ) assert_equal(expected, result) @@ -1482,7 +1486,9 @@ def test_colon_grid_wide_characters(): "+-----------+---------+", ] ) - result = tabulate(_test_table, headers, tablefmt="colon_grid", colalign=["left", "right"]) + result = tabulate( + _test_table, headers, tablefmt="colon_grid", colalign=["left", "right"] + ) assert_equal(expected, result) @@ -2773,7 +2779,9 @@ def test_intfmt_with_string_as_integer(): @mark.skip(reason="It detects all values as floats but there are strings and integers.") def test_intfmt_with_string_with_floats(): "Output: integer format" - result = tabulate([[82000.38], ["1500.47"], ["2463"], [92165]], intfmt=",", tablefmt="plain") + result = tabulate( + [[82000.38], ["1500.47"], ["2463"], [92165]], intfmt=",", tablefmt="plain" + ) expected = "82000.4\n 1500.47\n 2463\n92,165" assert_equal(expected, result) diff --git a/test/test_regression.py b/test/test_regression.py index d2fc3a07..5289db0d 100644 --- a/test/test_regression.py +++ b/test/test_regression.py @@ -513,6 +513,7 @@ def test_numpy_int64_as_integer(): except ImportError: raise skip("") + def test_empty_table_with_colalign(): "Regression: empty table with colalign kwarg" table = tabulate([], ["a", "b", "c"], colalign=("center", "left", "left", "center")) From 54ac10757ac23a5b9bd4f483f35730a5d9dea437 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 26 Sep 2024 18:33:50 +0200 Subject: [PATCH 058/204] add preserve_whitespace to test_tabulate_signature --- test/test_api.py | 1 + 1 file changed, 1 insertion(+) diff --git a/test/test_api.py b/test/test_api.py index e658e826..062573c7 100644 --- a/test/test_api.py +++ b/test/test_api.py @@ -50,6 +50,7 @@ def test_tabulate_signature(): ("disable_numparse", False), ("colglobalalign", None), ("colalign", None), + ("preserve_whitespace", False), ("maxcolwidths", None), ("headersglobalalign", None), ("headersalign", None), From 0d5d30e81a98caed4fc867e76ec5ca10cb5ff20f Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 26 Sep 2024 18:38:36 +0200 Subject: [PATCH 059/204] update README according to the new preserve_whitespace usage --- README.md | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 52c76440..089f20e1 100644 --- a/README.md +++ b/README.md @@ -739,13 +739,8 @@ column, in which case every column may have different number formatting: ### Text formatting By default, `tabulate` removes leading and trailing whitespace from text -columns. To disable whitespace removal, set the global module-level flag -`PRESERVE_WHITESPACE`: - -```python -import tabulate -tabulate.PRESERVE_WHITESPACE = True -``` +columns. To disable whitespace removal, pass `preserve_whitespace=True`. +Older versions of the library used a global module-level flag PRESERVE_WHITESPACE. ### Wide (fullwidth CJK) symbols From 09550a7b2eeaf7de723c10bbffe4c941a2d860db Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 26 Sep 2024 18:44:25 +0200 Subject: [PATCH 060/204] Apply ruff/Perflint rule PERF402 https://docs.astral.sh/ruff/rules/manual-list-copy/ --- tabulate/__init__.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 11bb8655..9e76a529 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1108,8 +1108,7 @@ def _flat_list(nested_list): ret = [] for item in nested_list: if isinstance(item, list): - for subitem in item: - ret.append(subitem) + ret.extend(item) else: ret.append(item) return ret From e8b511d7bcd547deb8b9d623394a44b8c3960ea7 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 26 Sep 2024 18:47:33 +0200 Subject: [PATCH 061/204] rename unitest workflow --- .github/workflows/tabulate.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/tabulate.yml b/.github/workflows/tabulate.yml index 9adabb7c..eeb96b74 100644 --- a/.github/workflows/tabulate.yml +++ b/.github/workflows/tabulate.yml @@ -1,4 +1,4 @@ -name: python-tabulate +name: pytest on: - push From 1f49977cce900e9414600ae11a25750bec8e5801 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Fri, 29 Sep 2023 10:07:58 +0200 Subject: [PATCH 062/204] Fix typos found by codespell --- tabulate/__init__.py | 2 +- test/test_input.py | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index b7510b22..2ff8f8f5 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -2647,7 +2647,7 @@ def _update_lines(self, lines, new_line): else: # A single reset code resets everything self._active_codes = [] - # Always ensure each line is color terminted if any colors are + # Always ensure each line is color terminated if any colors are # still active, otherwise colors will bleed into other cells on the console if len(self._active_codes) > 0: new_line = new_line + _ansi_color_reset_code diff --git a/test/test_input.py b/test/test_input.py index 721d03a1..b910a346 100644 --- a/test/test_input.py +++ b/test/test_input.py @@ -11,7 +11,7 @@ def test_iterable_of_iterables(): - "Input: an interable of iterables." + "Input: an iterable of iterables." ii = iter(map(lambda x: iter(x), [range(5), range(5, 0, -1)])) expected = "\n".join( ["- - - - -", "0 1 2 3 4", "5 4 3 2 1", "- - - - -"] @@ -21,7 +21,7 @@ def test_iterable_of_iterables(): def test_iterable_of_iterables_headers(): - "Input: an interable of iterables with headers." + "Input: an iterable of iterables with headers." ii = iter(map(lambda x: iter(x), [range(5), range(5, 0, -1)])) expected = "\n".join( [ @@ -36,7 +36,7 @@ def test_iterable_of_iterables_headers(): def test_iterable_of_iterables_firstrow(): - "Input: an interable of iterables with the first row as headers" + "Input: an iterable of iterables with the first row as headers" ii = iter(map(lambda x: iter(x), ["abcde", range(5), range(5, 0, -1)])) expected = "\n".join( [ From ca385d2ed23a405ea18bc0fb9ce1fe5327867e8a Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 26 Sep 2024 18:46:29 +0200 Subject: [PATCH 063/204] A round of black to pass CI tests --- test/test_internal.py | 13 +++++++++++-- test/test_output.py | 1 + test/test_regression.py | 2 +- test/test_textwrapper.py | 1 + 4 files changed, 14 insertions(+), 3 deletions(-) diff --git a/test/test_internal.py b/test/test_internal.py index e7564d37..17107c6d 100644 --- a/test/test_internal.py +++ b/test/test_internal.py @@ -180,7 +180,9 @@ def test_wrap_text_wide_chars(): except ImportError: skip("test_wrap_text_wide_chars is skipped") - rows = [["청자청자청자청자청자", "약간 감싸면 더 잘 보일 수있는 다소 긴 설명입니다"]] + rows = [ + ["청자청자청자청자청자", "약간 감싸면 더 잘 보일 수있는 다소 긴 설명입니다"] + ] widths = [5, 20] expected = [ [ @@ -244,7 +246,14 @@ def test_wrap_text_to_colwidths_colors_wide_char(): except ImportError: skip("test_wrap_text_to_colwidths_colors_wide_char is skipped") - data = [[("\033[31m약간 감싸면 더 잘 보일 수있는 다소 긴" " 설명입니다 설명입니다 설명입니다 설명입니다 설명\033[0m")]] + data = [ + [ + ( + "\033[31m약간 감싸면 더 잘 보일 수있는 다소 긴" + " 설명입니다 설명입니다 설명입니다 설명입니다 설명\033[0m" + ) + ] + ] result = T._wrap_text_to_colwidths(data, [30]) expected = [ diff --git a/test/test_output.py b/test/test_output.py index 059742c1..68b5e55f 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -1,4 +1,5 @@ """Test output of the various forms of tabular data.""" + from pytest import mark from common import assert_equal, raises, skip, check_warnings diff --git a/test/test_regression.py b/test/test_regression.py index 584ea396..bf262470 100644 --- a/test/test_regression.py +++ b/test/test_regression.py @@ -490,7 +490,7 @@ def test_preserve_line_breaks_with_maxcolwidths(): def test_maxcolwidths_accepts_list_or_tuple(): "Regression: maxcolwidths can accept a list or a tuple (github issue #214)" - table = [["lorem ipsum dolor sit amet"]*3] + table = [["lorem ipsum dolor sit amet"] * 3] expected = "\n".join( [ "+-------------+----------+----------------------------+", diff --git a/test/test_textwrapper.py b/test/test_textwrapper.py index b315a5cc..1f134fd3 100644 --- a/test/test_textwrapper.py +++ b/test/test_textwrapper.py @@ -1,4 +1,5 @@ """Discretely test functionality of our custom TextWrapper""" + import datetime from tabulate import _CustomTextWrap as CTW, tabulate From de466cb48fc2eaeb033b283d0081093dc51b5dd2 Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com> Date: Thu, 26 Sep 2024 12:20:35 -0700 Subject: [PATCH 064/204] Add support for Python 3.13 --- .github/workflows/tabulate.yml | 3 ++- pyproject.toml | 1 + tox.ini | 19 ++++++++++++++++++- 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/.github/workflows/tabulate.yml b/.github/workflows/tabulate.yml index eeb96b74..e75466b5 100644 --- a/.github/workflows/tabulate.yml +++ b/.github/workflows/tabulate.yml @@ -9,7 +9,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - python-version: ['3.9', '3.10', '3.11', '3.12'] + python-version: ['3.9', '3.10', '3.11', '3.12', '3.13'] steps: - uses: actions/checkout@v4 @@ -17,6 +17,7 @@ jobs: uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }} + allow-prereleases: true - name: Install dependencies run: | python -m pip install --upgrade pip diff --git a/pyproject.toml b/pyproject.toml index 8cb6216f..4144f9b9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -17,6 +17,7 @@ classifiers = [ "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", "Topic :: Software Development :: Libraries", ] requires-python = ">=3.9" diff --git a/tox.ini b/tox.ini index a7fe513f..4ab82446 100644 --- a/tox.ini +++ b/tox.ini @@ -8,7 +8,7 @@ # for testing and it is disabled by default. [tox] -envlist = lint, py{38, 39, 310, 311, 312} +envlist = lint, py{38, 39, 310, 311, 312, 313} isolated_build = True [gh] @@ -17,6 +17,7 @@ python = 3.10: py310-extra 3.11: py311-extra 3.12: py312-extra + 3.13: py313-extra [testenv] commands = pytest -v --doctest-modules --ignore benchmark.py {posargs} @@ -113,6 +114,22 @@ deps = pandas wcwidth +[testenv:py313] +basepython = python3.13 +commands = pytest -v --doctest-modules --ignore benchmark.py {posargs} +deps = + pytest + +[testenv:py313-extra] +basepython = python3.13 +setenv = PYTHONDEVMODE = 1 +commands = pytest -v --doctest-modules --ignore benchmark.py {posargs} +deps = + pytest + numpy + pandas + wcwidth + [flake8] max-complexity = 22 max-line-length = 99 From 571bc370aa22729440194e6fb7dc149cd169d5fa Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com> Date: Thu, 26 Sep 2024 12:21:41 -0700 Subject: [PATCH 065/204] Bump GitHub Actions --- .github/workflows/lint.yml | 2 +- .github/workflows/tabulate.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 7e7c906b..0093303c 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -14,7 +14,7 @@ jobs: steps: - uses: actions/checkout@v4 - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} - name: Install dependencies diff --git a/.github/workflows/tabulate.yml b/.github/workflows/tabulate.yml index e75466b5..fd6004b0 100644 --- a/.github/workflows/tabulate.yml +++ b/.github/workflows/tabulate.yml @@ -14,7 +14,7 @@ jobs: steps: - uses: actions/checkout@v4 - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v4 + uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} allow-prereleases: true From 29e0b1f97f012cdc97390b714ebc9c2e2c399774 Mon Sep 17 00:00:00 2001 From: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com> Date: Thu, 26 Sep 2024 12:22:19 -0700 Subject: [PATCH 066/204] Fix lint --- test/test_regression.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_regression.py b/test/test_regression.py index 584ea396..bf262470 100644 --- a/test/test_regression.py +++ b/test/test_regression.py @@ -490,7 +490,7 @@ def test_preserve_line_breaks_with_maxcolwidths(): def test_maxcolwidths_accepts_list_or_tuple(): "Regression: maxcolwidths can accept a list or a tuple (github issue #214)" - table = [["lorem ipsum dolor sit amet"]*3] + table = [["lorem ipsum dolor sit amet"] * 3] expected = "\n".join( [ "+-------------+----------+----------------------------+", From 813edee611c0b007940c3287a888408f33949ddd Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Fri, 27 Sep 2024 09:55:46 +0200 Subject: [PATCH 067/204] update README and doctest descriptions of colon_grid introduced in pr #341 --- README.md | 16 ++++++++++++++++ tabulate/__init__.py | 3 ++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 666537ac..cab553eb 100644 --- a/README.md +++ b/README.md @@ -335,6 +335,22 @@ corresponds to the `pipe` format without alignment colons: ╘════════╧═══════╛ ``` +`colon_grid` is similar to `grid` but uses colons only to define +columnwise content alignment , without whitespace padding, +similar the alignment specification of Pandoc `grid_tables`: + + >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], + ... ["strings", "numbers"], "colon_grid", + ... colalign=["right", "left"])) + +-----------+-----------+ + | strings | numbers | + +==========:+:==========+ + | spam | 41.9999 | + +-----------+-----------+ + | eggs | 451 | + +-----------+-----------+ + + `outline` is the same as the `grid` format but doesn't draw lines between rows: >>> print(tabulate(table, headers, tablefmt="outline")) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index b7510b22..125c4776 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1891,7 +1891,8 @@ def tabulate( ╘═══════════╧═══════════╛ "colon_grid" is similar to "grid" but uses colons only to define - columnwise content alignment, with no whitespace padding: + columnwise content alignment, without whitespace padding, + similar to the alignment specification of Pandoc `grid_tables`: >>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]], ... ["strings", "numbers"], "colon_grid")) From 3cee6568c7a2e8dd6379f11bba2c532f6acc5e3d Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Fri, 27 Sep 2024 10:58:47 +0200 Subject: [PATCH 068/204] update the list of contributors in README.md --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index cab553eb..3af3caad 100644 --- a/README.md +++ b/README.md @@ -1156,7 +1156,9 @@ endolith, Dominic Davis-Foster, pavlocat, Daniel Aslau, paulc, Felix Yan, Shane Loretz, Frank Busse, Harsh Singh, Derek Weitzel, Vladimir Vrzić, 서승우 (chrd5273), Georgy Frolov, Christian Cwienk, Bart Broere, Vilhelm Prytz, Alexander Gažo, Hugo van Kemenade, -jamescooke, Matt Warner, Jérôme Provensal, Kevin Deldycke, +jamescooke, Matt Warner, Jérôme Provensal, Michał Górny, Kevin Deldycke, Kian-Meng Ang, Kevin Patterson, Shodhan Save, cleoold, KOLANICH, Vijaya Krishna Kasula, Furcy Pin, Christian Fibich, Shaun Duncan, -Dimitri Papadopoulos, Élie Goudout, Racerroar888, Phill Zarfos. +Dimitri Papadopoulos, Élie Goudout, Racerroar888, Phill Zarfos, +Keyacom, Andrew Coffey, Arpit Jain, Israel Roldan, ilya112358, +Dan Nicholson, Frederik Scheerer, cdar07 (cdar), Racerroar888. \ No newline at end of file From 68292bd4c85557551c4f664f42705baa9d70243f Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Fri, 27 Sep 2024 09:57:12 +0200 Subject: [PATCH 069/204] update CHANGELOG for 0.10.0 version --- CHANGELOG | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/CHANGELOG b/CHANGELOG index a18a5a19..27374413 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,4 +1,10 @@ -- 0.9.1: Future version. +- 0.10.0: Add support for Python 3.11, 3.12, 3.13. + Drop support for Python 3.7, 3.8. + PRESERVE_STERILITY global is replaced with preserve_sterility function argument. + New formatting options: headersglobalalign, headersalign, colglobalalign. + New output format: ``colon_grid`` (Pandoc grid_tables with alignment) + Various bug fixes. + Improved error messages. - 0.9.0: Drop support for Python 2.7, 3.5, 3.6. Migrate to pyproject.toml project layout (PEP 621). New output formats: `asciidoc`, various `*grid` and `*outline` formats. From 22683f924c2afe28533863e70dd9e8c8611b7e49 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Fri, 27 Sep 2024 10:14:02 +0200 Subject: [PATCH 070/204] remove asciitable from benchmark.py (not installable on Python 3.11), add benchmark_requirements.txt --- benchmark.py | 9 --------- benchmark_requirements.txt | 2 ++ 2 files changed, 2 insertions(+), 9 deletions(-) create mode 100644 benchmark_requirements.txt diff --git a/benchmark.py b/benchmark.py index 8422f5c3..a89b709e 100644 --- a/benchmark.py +++ b/benchmark.py @@ -1,6 +1,5 @@ from timeit import timeit import tabulate -import asciitable import prettytable import texttable import sys @@ -9,7 +8,6 @@ from csv import writer from io import StringIO import tabulate -import asciitable import prettytable import texttable @@ -34,12 +32,6 @@ def run_prettytable(table): return str(pp) -def run_asciitable(table): - buf = StringIO() - asciitable.write(table, output=buf, Writer=asciitable.FixedWidth) - return buf.getvalue() - - def run_texttable(table): pp = texttable.Texttable() pp.set_cols_align(["l"] + ["r"]*9) @@ -61,7 +53,6 @@ def run_tabulate(table, widechars=False): methods = [ ("join with tabs and newlines", "join_table(table)"), ("csv to StringIO", "csv_table(table)"), - ("asciitable (%s)" % asciitable.__version__, "run_asciitable(table)"), ("tabulate (%s)" % tabulate.__version__, "run_tabulate(table)"), ( "tabulate (%s, WIDE_CHARS_MODE)" % tabulate.__version__, diff --git a/benchmark_requirements.txt b/benchmark_requirements.txt new file mode 100644 index 00000000..81086efe --- /dev/null +++ b/benchmark_requirements.txt @@ -0,0 +1,2 @@ +prettytable +texttable \ No newline at end of file From da896a81031fcb558e3e330503d979b57e3a3dd1 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Fri, 27 Sep 2024 10:16:12 +0200 Subject: [PATCH 071/204] move benchmark files to benchmark/ directory --- benchmark.py => benchmark/benchmark.py | 0 benchmark_requirements.txt => benchmark/requirements.txt | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename benchmark.py => benchmark/benchmark.py (100%) rename benchmark_requirements.txt => benchmark/requirements.txt (100%) diff --git a/benchmark.py b/benchmark/benchmark.py similarity index 100% rename from benchmark.py rename to benchmark/benchmark.py diff --git a/benchmark_requirements.txt b/benchmark/requirements.txt similarity index 100% rename from benchmark_requirements.txt rename to benchmark/requirements.txt From dbfd4219da5bb7fccd50014c8afca4e42bab889a Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Fri, 27 Sep 2024 10:16:26 +0200 Subject: [PATCH 072/204] update HOWTOPUBLISH instructions --- HOWTOPUBLISH | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/HOWTOPUBLISH b/HOWTOPUBLISH index 795fc736..ea0bdcaa 100644 --- a/HOWTOPUBLISH +++ b/HOWTOPUBLISH @@ -1,7 +1,14 @@ # update contributors and CHANGELOG in README +python -m pre_commit run -a # and then commit changes +tox -e py39-extra,py310-extra,py311-extra,py312-extra,py313-extra # tag version release -python3 benchmark.py # then update README -tox -e py38-extra,py39-extra,py310-extra,py311-extra,py312-extra -python3 -m build -nswx . +python -m build -s # this will update tabulate/version.py +python -m pip install . # install tabulate in the current venv +python -m pip install -r benchmark/requirements.txt +python benchmark/benchmark.py # then update README +# move tag to the last commit +python -m build -s # update tabulate/version.py +python -m build -nswx . +git push # wait for all CI builds to succeed twine upload --repository-url https://test.pypi.org/legacy/ dist/* twine upload dist/* From c3fd38802e463686c58534233e7014df9fe684fe Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Fri, 27 Sep 2024 10:24:04 +0200 Subject: [PATCH 073/204] update benchmark table in the README.md for 0.10.0 --- README.md | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 3af3caad..3a75f263 100644 --- a/README.md +++ b/README.md @@ -1059,21 +1059,19 @@ simply joining lists of values with a tab, comma, or other separator. At the same time, `tabulate` is comparable to other table pretty-printers. Given a 10x10 table (a list of lists) of mixed text and -numeric data, `tabulate` appears to be slower than `asciitable`, and -faster than `PrettyTable` and `texttable` The following mini-benchmark -was run in Python 3.9.13 on Windows 10: - - ================================= ========== =========== - Table formatter time, μs rel. time - ================================= ========== =========== - csv to StringIO 12.5 1.0 - join with tabs and newlines 14.6 1.2 - asciitable (0.8.0) 192.0 15.4 - tabulate (0.9.0) 483.5 38.7 - tabulate (0.9.0, WIDE_CHARS_MODE) 637.6 51.1 - PrettyTable (3.4.1) 1080.6 86.6 - texttable (1.6.4) 1390.3 111.4 - ================================= ========== =========== +numeric data, `tabulate` appears to be faster than `PrettyTable` and `texttable`. +The following mini-benchmark was run in Python 3.11.9 on Windows 11 (x64): + + ================================== ========== =========== + Table formatter time, μs rel. time + ================================== ========== =========== + join with tabs and newlines 6.3 1.0 + csv to StringIO 6.6 1.0 + tabulate (0.10.0) 249.2 39.3 + tabulate (0.10.0, WIDE_CHARS_MODE) 325.6 51.4 + texttable (1.7.0) 579.3 91.5 + PrettyTable (3.11.0) 605.5 95.6 + ================================== ========== =========== Version history From 174a16326951fcf0111ab23352c811ac42214e59 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Fri, 27 Sep 2024 11:07:45 +0200 Subject: [PATCH 074/204] update HOWTOPUBLISH (remember to push tags) --- HOWTOPUBLISH | 1 + 1 file changed, 1 insertion(+) diff --git a/HOWTOPUBLISH b/HOWTOPUBLISH index ea0bdcaa..ce7dcc7d 100644 --- a/HOWTOPUBLISH +++ b/HOWTOPUBLISH @@ -10,5 +10,6 @@ python benchmark/benchmark.py # then update README python -m build -s # update tabulate/version.py python -m build -nswx . git push # wait for all CI builds to succeed +git push --tags # if CI builds succeed twine upload --repository-url https://test.pypi.org/legacy/ dist/* twine upload dist/* From 9ef6b8bf9e4176a36d255c34dee25cc8defb6142 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Fri, 27 Sep 2024 11:18:14 +0200 Subject: [PATCH 075/204] ignore benchmark/benchmark.py in all CI tests --- .github/workflows/tabulate.yml | 2 +- appveyor.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/tabulate.yml b/.github/workflows/tabulate.yml index fd6004b0..64cfbd80 100644 --- a/.github/workflows/tabulate.yml +++ b/.github/workflows/tabulate.yml @@ -24,4 +24,4 @@ jobs: python -m pip install pytest numpy pandas - name: Run tests run: | - pytest -v --doctest-modules --ignore benchmark.py + pytest -v --doctest-modules --ignore benchmark/benchmark.py diff --git a/appveyor.yml b/appveyor.yml index 12bd7726..64463bd8 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -33,7 +33,7 @@ test_script: # the interpreter you're using - Appveyor does not do anything special # to put the Python version you want to use on PATH. #- "build.cmd %PYTHON%\\python.exe setup.py test" - - "%PYTHON%\\python.exe -m pytest -v --doctest-modules --ignore benchmark.py" + - "%PYTHON%\\python.exe -m pytest -v --doctest-modules --ignore benchmark\benchmark.py" after_test: # This step builds your wheels. From 46b35b44a206bc2e84208fe7159fba632a301ca8 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Fri, 27 Sep 2024 11:25:09 +0200 Subject: [PATCH 076/204] ignore benchmark folder in all tox environments --- tox.ini | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/tox.ini b/tox.ini index 4ab82446..9605e79b 100644 --- a/tox.ini +++ b/tox.ini @@ -20,7 +20,7 @@ python = 3.13: py313-extra [testenv] -commands = pytest -v --doctest-modules --ignore benchmark.py {posargs} +commands = pytest -v --doctest-modules --ignore benchmark {posargs} deps = pytest passenv = @@ -35,13 +35,13 @@ deps = [testenv:py38] basepython = python3.8 -commands = pytest -v --doctest-modules --ignore benchmark.py {posargs} +commands = pytest -v --doctest-modules --ignore benchmark {posargs} deps = pytest [testenv:py38-extra] basepython = python3.8 -commands = pytest -v --doctest-modules --ignore benchmark.py {posargs} +commands = pytest -v --doctest-modules --ignore benchmark {posargs} deps = pytest numpy @@ -51,13 +51,13 @@ deps = [testenv:py39] basepython = python3.9 -commands = pytest -v --doctest-modules --ignore benchmark.py {posargs} +commands = pytest -v --doctest-modules --ignore benchmark {posargs} deps = pytest [testenv:py39-extra] basepython = python3.9 -commands = pytest -v --doctest-modules --ignore benchmark.py {posargs} +commands = pytest -v --doctest-modules --ignore benchmark {posargs} deps = pytest numpy @@ -67,14 +67,14 @@ deps = [testenv:py310] basepython = python3.10 -commands = pytest -v --doctest-modules --ignore benchmark.py {posargs} +commands = pytest -v --doctest-modules --ignore benchmark {posargs} deps = pytest [testenv:py310-extra] basepython = python3.10 setenv = PYTHONDEVMODE = 1 -commands = pytest -v --doctest-modules --ignore benchmark.py {posargs} +commands = pytest -v --doctest-modules --ignore benchmark {posargs} deps = pytest numpy @@ -84,14 +84,14 @@ deps = [testenv:py311] basepython = python3.11 -commands = pytest -v --doctest-modules --ignore benchmark.py {posargs} +commands = pytest -v --doctest-modules --ignore benchmark {posargs} deps = pytest [testenv:py311-extra] basepython = python3.11 setenv = PYTHONDEVMODE = 1 -commands = pytest -v --doctest-modules --ignore benchmark.py {posargs} +commands = pytest -v --doctest-modules --ignore benchmark {posargs} deps = pytest numpy @@ -100,14 +100,14 @@ deps = [testenv:py312] basepython = python3.12 -commands = pytest -v --doctest-modules --ignore benchmark.py {posargs} +commands = pytest -v --doctest-modules --ignore benchmark {posargs} deps = pytest [testenv:py312-extra] basepython = python3.12 setenv = PYTHONDEVMODE = 1 -commands = pytest -v --doctest-modules --ignore benchmark.py {posargs} +commands = pytest -v --doctest-modules --ignore benchmark {posargs} deps = pytest numpy @@ -116,14 +116,14 @@ deps = [testenv:py313] basepython = python3.13 -commands = pytest -v --doctest-modules --ignore benchmark.py {posargs} +commands = pytest -v --doctest-modules --ignore benchmark {posargs} deps = pytest [testenv:py313-extra] basepython = python3.13 setenv = PYTHONDEVMODE = 1 -commands = pytest -v --doctest-modules --ignore benchmark.py {posargs} +commands = pytest -v --doctest-modules --ignore benchmark {posargs} deps = pytest numpy From 8c9c9e75c9a7da858e8ecf72236ee021c69e2d36 Mon Sep 17 00:00:00 2001 From: Perry Kundert Date: Thu, 20 Jul 2023 14:16:55 -0600 Subject: [PATCH 077/204] Support better type deduction o Empty/None values are ignored for deducing the type of a column o Comma-separated numbers are allowed in for int and float types --- tabulate/__init__.py | 35 ++++++++++++++++++++++++++++------- test/test_output.py | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 7 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index c349a791..8642c8d3 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -933,8 +933,13 @@ def _isbool(string): def _type(string, has_invisible=True, numparse=True): """The least generic type (type(None), int, float, str, unicode). + Treats empty string as missing for the purposes of type deduction, so as to not influence + the type of an otherwise complete column; does *not* result in missingval replacement! + >>> _type(None) is type(None) True + >>> _type("") is type(None) + True >>> _type("foo") is type("") True >>> _type("1") is type(1) @@ -949,15 +954,26 @@ def _type(string, has_invisible=True, numparse=True): if has_invisible and isinstance(string, (str, bytes)): string = _strip_ansi(string) - if string is None: + if string is None or (isinstance(string, (bytes, str)) and not string): return type(None) elif hasattr(string, "isoformat"): # datetime.datetime, date, and time return str elif _isbool(string): return bool - elif _isint(string) and numparse: + elif numparse and ( + _isint(string) or ( + isinstance(string, str) + and _isnumber_with_thousands_separator(string) + and '.' not in string + ) + ): return int - elif _isnumber(string) and numparse: + elif numparse and ( + _isnumber(string) or ( + isinstance(string, str) + and _isnumber_with_thousands_separator(string) + ) + ): return float elif isinstance(string, bytes): return bytes @@ -1251,7 +1267,7 @@ def _column_type(strings, has_invisible=True, numparse=True): def _format(val, valtype, floatfmt, intfmt, missingval="", has_invisible=True): - """Format a value according to its type. + """Format a value according to its deduced type. Empty values are deemed valid for any type. Unicode is supported: @@ -1264,6 +1280,8 @@ def _format(val, valtype, floatfmt, intfmt, missingval="", has_invisible=True): """ # noqa if val is None: return missingval + if isinstance(val, (bytes, str)) and not val: + return "" if valtype is str: return f"{val}" @@ -1298,6 +1316,8 @@ def _format(val, valtype, floatfmt, intfmt, missingval="", has_invisible=True): formatted_val = format(float(raw_val), floatfmt) return val.replace(raw_val, formatted_val) else: + if isinstance(val,str) and ',' in val: + val = val.replace(',', '') # handle thousands-separators return format(float(val), floatfmt) else: return f"{val}" @@ -1592,9 +1612,10 @@ def _wrap_text_to_colwidths(list_of_lists, colwidths, numparses=True): if width is not None: wrapper = _CustomTextWrap(width=width) - # Cast based on our internal type handling - # Any future custom formatting of types (such as datetimes) - # may need to be more explicit than just `str` of the object + # Cast based on our internal type handling. Any future custom + # formatting of types (such as datetimes) may need to be more + # explicit than just `str` of the object. Also doesn't work for + # custom floatfmt/intfmt, nor with any missing/blank cells. casted_cell = ( str(cell) if _isnumber(cell) else _type(cell, numparse)(cell) ) diff --git a/test/test_output.py b/test/test_output.py index 68b5e55f..5b94e829 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -2824,6 +2824,13 @@ def test_floatfmt(): assert_equal(expected, result) +def test_floatfmt_thousands(): + "Output: floating point format" + result = tabulate([["1.23456789"], [1.0], ["1,234.56"]], floatfmt=".3f", tablefmt="plain") + expected = " 1.235\n 1.000\n1234.560" + assert_equal(expected, result) + + def test_floatfmt_multi(): "Output: floating point format different for each column" result = tabulate( @@ -2964,6 +2971,32 @@ def test_missingval_multi(): assert_equal(expected, result) +def test_column_emptymissing_deduction(): + "Missing or empty/blank values shouldn't change type deduction of rest of column" + from fractions import Fraction + + test_table = [ + [None, "1.23423515351", Fraction(1, 3)], + [Fraction(56789, 1000000), 12345.1, b"abc"], + ["", b"", None], + [Fraction(10000, 3), None, ""], + ] + result = tabulate( + test_table, + floatfmt=",.5g", + missingval="?", + ) + print(f"\n{result}") + expected = """\ +------------ ----------- --- + ? 1.2342 1/3 + 0.056789 12,345 abc + ? +3,333.3 ? +------------ ----------- ---""" + assert_equal(expected, result) + + def test_column_alignment(): "Output: custom alignment for text and numbers" expected = "\n".join(["----- ---", "Alice 1", " Bob 333", "----- ---"]) From b39a162ecbb2e9898c2f759e01ddd21f4af7f316 Mon Sep 17 00:00:00 2001 From: Perry Kundert Date: Mon, 7 Oct 2024 18:01:46 -0600 Subject: [PATCH 078/204] Add back in check for SEPARATING_LINE --- tabulate/__init__.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 6cf6ea31..296974d0 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -2561,9 +2561,10 @@ def _format_table( if rows and fmt.linebetweenrows and "linebetweenrows" not in hidden: # initial rows with a line below for row, ralign in zip(rows[:-1], rowaligns): - append_row( - lines, pad_row(row, pad), padded_widths, colaligns, fmt.datarow, rowalign=ralign - ) + if row != SEPARATING_LINE: + append_row( + lines, pad_row(row, pad), padded_widths, colaligns, fmt.datarow, rowalign=ralign + ) _append_line(lines, padded_widths, colaligns, fmt.linebetweenrows) # the last row without a line below append_row( From 588f4121f669d3cde4a5eae741f40bd014eac331 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Tue, 8 Oct 2024 11:36:19 +0200 Subject: [PATCH 079/204] fix backslash escaping in appveyor.yml --- appveyor.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/appveyor.yml b/appveyor.yml index 64463bd8..85881d42 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -33,7 +33,7 @@ test_script: # the interpreter you're using - Appveyor does not do anything special # to put the Python version you want to use on PATH. #- "build.cmd %PYTHON%\\python.exe setup.py test" - - "%PYTHON%\\python.exe -m pytest -v --doctest-modules --ignore benchmark\benchmark.py" + - "%PYTHON%\\python.exe -m pytest -v --doctest-modules --ignore benchmark\\benchmark.py" after_test: # This step builds your wheels. From ae3d485c734e732d9ace6eefc4fb433ef8ae1005 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Tue, 8 Oct 2024 11:53:07 +0200 Subject: [PATCH 080/204] add windows build to github actions job matrix --- .github/workflows/tabulate.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/tabulate.yml b/.github/workflows/tabulate.yml index 64cfbd80..9b113c96 100644 --- a/.github/workflows/tabulate.yml +++ b/.github/workflows/tabulate.yml @@ -6,10 +6,11 @@ on: jobs: build: - runs-on: ubuntu-latest strategy: matrix: python-version: ['3.9', '3.10', '3.11', '3.12', '3.13'] + os: ["ubuntu-latest", "windows-latest"] + runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 From cf45298f3f01ad05264b9ab9a2ad4cbd2c32d9aa Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Tue, 8 Oct 2024 11:56:26 +0200 Subject: [PATCH 081/204] apply black to fix linting errors --- HOWTOPUBLISH | 4 ++-- tabulate/__init__.py | 33 +++++++++++++++++++++------------ test/test_internal.py | 13 ++----------- test/test_output.py | 4 +++- 4 files changed, 28 insertions(+), 26 deletions(-) diff --git a/HOWTOPUBLISH b/HOWTOPUBLISH index ce7dcc7d..29c4545c 100644 --- a/HOWTOPUBLISH +++ b/HOWTOPUBLISH @@ -4,12 +4,12 @@ tox -e py39-extra,py310-extra,py311-extra,py312-extra,py313-extra # tag version release python -m build -s # this will update tabulate/version.py python -m pip install . # install tabulate in the current venv -python -m pip install -r benchmark/requirements.txt +python -m pip install -r benchmark/requirements.txt python benchmark/benchmark.py # then update README # move tag to the last commit python -m build -s # update tabulate/version.py python -m build -nswx . -git push # wait for all CI builds to succeed +git push # wait for all CI builds to succeed git push --tags # if CI builds succeed twine upload --repository-url https://test.pypi.org/legacy/ dist/* twine upload dist/* diff --git a/tabulate/__init__.py b/tabulate/__init__.py index d6a977af..0d249ac5 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -961,18 +961,17 @@ def _type(string, has_invisible=True, numparse=True): elif _isbool(string): return bool elif numparse and ( - _isint(string) or ( + _isint(string) + or ( isinstance(string, str) and _isnumber_with_thousands_separator(string) - and '.' not in string + and "." not in string ) ): return int elif numparse and ( - _isnumber(string) or ( - isinstance(string, str) - and _isnumber_with_thousands_separator(string) - ) + _isnumber(string) + or (isinstance(string, str) and _isnumber_with_thousands_separator(string)) ): return float elif isinstance(string, bytes): @@ -1316,8 +1315,8 @@ def _format(val, valtype, floatfmt, intfmt, missingval="", has_invisible=True): formatted_val = format(float(raw_val), floatfmt) return val.replace(raw_val, formatted_val) else: - if isinstance(val,str) and ',' in val: - val = val.replace(',', '') # handle thousands-separators + if isinstance(val, str) and "," in val: + val = val.replace(",", "") # handle thousands-separators return format(float(val), floatfmt) else: return f"{val}" @@ -2584,7 +2583,12 @@ def _format_table( for row, ralign in zip(rows[:-1], rowaligns): if row != SEPARATING_LINE: append_row( - lines, pad_row(row, pad), padded_widths, colaligns, fmt.datarow, rowalign=ralign + lines, + pad_row(row, pad), + padded_widths, + colaligns, + fmt.datarow, + rowalign=ralign, ) _append_line(lines, padded_widths, colaligns, fmt.linebetweenrows) # the last row without a line below @@ -2610,7 +2614,9 @@ def _format_table( if _is_separating_line(row): _append_line(lines, padded_widths, colaligns, separating_line) else: - append_row(lines, pad_row(row, pad), padded_widths, colaligns, fmt.datarow) + append_row( + lines, pad_row(row, pad), padded_widths, colaligns, fmt.datarow + ) if fmt.linebelow and "linebelow" not in hidden: _append_line(lines, padded_widths, colaligns, fmt.linebelow) @@ -2705,11 +2711,14 @@ def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width): if _ansi_codes.search(chunk) is not None: for group, _, _, _ in _ansi_codes.findall(chunk): escape_len = len(group) - if group in chunk[last_group: i + total_escape_len + escape_len - 1]: + if ( + group + in chunk[last_group : i + total_escape_len + escape_len - 1] + ): total_escape_len += escape_len found = _ansi_codes.search(chunk[last_group:]) last_group += found.end() - cur_line.append(chunk[: i + total_escape_len - 1]) + cur_line.append(chunk[: i + total_escape_len - 1]) reversed_chunks[-1] = chunk[i + total_escape_len - 1 :] # Otherwise, we have to preserve the long word intact. Only add diff --git a/test/test_internal.py b/test/test_internal.py index 17107c6d..e7564d37 100644 --- a/test/test_internal.py +++ b/test/test_internal.py @@ -180,9 +180,7 @@ def test_wrap_text_wide_chars(): except ImportError: skip("test_wrap_text_wide_chars is skipped") - rows = [ - ["청자청자청자청자청자", "약간 감싸면 더 잘 보일 수있는 다소 긴 설명입니다"] - ] + rows = [["청자청자청자청자청자", "약간 감싸면 더 잘 보일 수있는 다소 긴 설명입니다"]] widths = [5, 20] expected = [ [ @@ -246,14 +244,7 @@ def test_wrap_text_to_colwidths_colors_wide_char(): except ImportError: skip("test_wrap_text_to_colwidths_colors_wide_char is skipped") - data = [ - [ - ( - "\033[31m약간 감싸면 더 잘 보일 수있는 다소 긴" - " 설명입니다 설명입니다 설명입니다 설명입니다 설명\033[0m" - ) - ] - ] + data = [[("\033[31m약간 감싸면 더 잘 보일 수있는 다소 긴" " 설명입니다 설명입니다 설명입니다 설명입니다 설명\033[0m")]] result = T._wrap_text_to_colwidths(data, [30]) expected = [ diff --git a/test/test_output.py b/test/test_output.py index bba7622b..e3d369ae 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -2863,7 +2863,9 @@ def test_floatfmt(): def test_floatfmt_thousands(): "Output: floating point format" - result = tabulate([["1.23456789"], [1.0], ["1,234.56"]], floatfmt=".3f", tablefmt="plain") + result = tabulate( + [["1.23456789"], [1.0], ["1,234.56"]], floatfmt=".3f", tablefmt="plain" + ) expected = " 1.235\n 1.000\n1234.560" assert_equal(expected, result) From a81f6b0a032f84f9225bdfdf375d255ab8e847d3 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Tue, 8 Oct 2024 11:59:15 +0200 Subject: [PATCH 082/204] update the list of contributors --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3a75f263..28ef166e 100644 --- a/README.md +++ b/README.md @@ -1159,4 +1159,5 @@ Kian-Meng Ang, Kevin Patterson, Shodhan Save, cleoold, KOLANICH, Vijaya Krishna Kasula, Furcy Pin, Christian Fibich, Shaun Duncan, Dimitri Papadopoulos, Élie Goudout, Racerroar888, Phill Zarfos, Keyacom, Andrew Coffey, Arpit Jain, Israel Roldan, ilya112358, -Dan Nicholson, Frederik Scheerer, cdar07 (cdar), Racerroar888. \ No newline at end of file +Dan Nicholson, Frederik Scheerer, cdar07 (cdar), Racerroar888, +Perry Kundert. From 3c43178313bc80dc45337e3931c4c0cfdfc032f4 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Tue, 8 Oct 2024 12:00:07 +0200 Subject: [PATCH 083/204] add macos build to github actions job matrix --- .github/workflows/tabulate.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/tabulate.yml b/.github/workflows/tabulate.yml index 9b113c96..c4594846 100644 --- a/.github/workflows/tabulate.yml +++ b/.github/workflows/tabulate.yml @@ -9,7 +9,7 @@ jobs: strategy: matrix: python-version: ['3.9', '3.10', '3.11', '3.12', '3.13'] - os: ["ubuntu-latest", "windows-latest"] + os: ["ubuntu-latest", "windows-latest", "macos-latest"] runs-on: ${{ matrix.os }} steps: From 1de098247fb374521448893765f0a4962cdf3147 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Tue, 8 Oct 2024 12:08:25 +0200 Subject: [PATCH 084/204] remove appveyor.yml and appveyor badge --- README.md | 2 +- appveyor.yml | 51 --------------------------------------------------- 2 files changed, 1 insertion(+), 52 deletions(-) delete mode 100644 appveyor.yml diff --git a/README.md b/README.md index 28ef166e..b1b56d55 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ pip install tabulate Build status ------------ -[![python-tabulate](https://github.com/astanin/python-tabulate/actions/workflows/tabulate.yml/badge.svg)](https://github.com/astanin/python-tabulate/actions/workflows/tabulate.yml) [![Build status](https://ci.appveyor.com/api/projects/status/8745yksvvol7h3d7/branch/master?svg=true)](https://ci.appveyor.com/project/astanin/python-tabulate/branch/master) +[![python-tabulate](https://github.com/astanin/python-tabulate/actions/workflows/tabulate.yml/badge.svg)](https://github.com/astanin/python-tabulate/actions/workflows/tabulate.yml) Library usage ------------- diff --git a/appveyor.yml b/appveyor.yml deleted file mode 100644 index 85881d42..00000000 --- a/appveyor.yml +++ /dev/null @@ -1,51 +0,0 @@ -image: Visual Studio 2022 -environment: - - matrix: - - # For Python versions available on Appveyor, see - # https://www.appveyor.com/docs/windows-images-software/#python - # The list here is complete (excluding Python 2.6, which - # isn't covered by this document) at the time of writing. - - #- PYTHON: "C:\\Python39" - #- PYTHON: "C:\\Python310" - #- PYTHON: "C:\\Python311" - #- PYTHON: "C:\\Python312" - - PYTHON: "C:\\Python39-x64" - - PYTHON: "C:\\Python310-x64" - - PYTHON: "C:\\Python311-x64" - - PYTHON: "C:\\Python312-x64" - -install: - # Newer setuptools is needed for proper support of pyproject.toml - - "%PYTHON%\\python.exe -m pip install setuptools --upgrade" - # We need wheel installed to build wheels - - "%PYTHON%\\python.exe -m pip install wheel --upgrade" - - "%PYTHON%\\python.exe -m pip install build setuptools_scm" - - "%PYTHON%\\python.exe -m pip install pytest numpy pandas" - -build: off - -test_script: - # Put your test command here. - # Note that you must use the environment variable %PYTHON% to refer to - # the interpreter you're using - Appveyor does not do anything special - # to put the Python version you want to use on PATH. - #- "build.cmd %PYTHON%\\python.exe setup.py test" - - "%PYTHON%\\python.exe -m pytest -v --doctest-modules --ignore benchmark\\benchmark.py" - -after_test: - # This step builds your wheels. - # Again, you need to use %PYTHON% to get the correct interpreter - #- "build.cmd %PYTHON%\\python.exe setup.py bdist_wheel" - - "%PYTHON%\\python.exe -m build -nswx ." - -artifacts: - # bdist_wheel puts your built wheel in the dist directory - - path: dist\* - -#on_success: -# You can use this step to upload your artifacts to a public website. -# See Appveyor's documentation for more details. Or you can simply -# access your wheels from the Appveyor "artifacts" tab for your build. From c37de756a0ccfa9f23dae5aa2281e813f42fef02 Mon Sep 17 00:00:00 2001 From: Perry Kundert Date: Tue, 8 Oct 2024 09:21:09 -0600 Subject: [PATCH 085/204] Correct README.md examples and outputs using doctest --- README.md | 128 ++++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 104 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index b1b56d55..70b68395 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,7 @@ Earth 6371 5973.6 Moon 1737 73.5 Mars 3390 641.85 ----- ------ ------------- + ``` The following tabular data types are supported: @@ -101,6 +102,7 @@ Sun 696000 1.9891e+09 Earth 6371 5973.6 Moon 1737 73.5 Mars 3390 641.85 + ``` If `headers="firstrow"`, then the first row of data is used: @@ -112,6 +114,7 @@ Name Age ------ ----- Alice 24 Bob 19 + ``` If `headers="keys"`, then the keys of a dictionary/dataframe, or column @@ -125,6 +128,7 @@ Name Age ------ ----- Alice 24 Bob 19 + ``` When data is a list of dictionaries, a dictionary can be passed as `headers` @@ -137,6 +141,7 @@ Name Age ------ ----- Alice 24 Bob 19 + ``` ### Row Indices @@ -154,6 +159,7 @@ or `showindex=False`. To add a custom row index column, pass 0 F 24 1 M 19 - - -- + ``` ### Table format @@ -210,6 +216,7 @@ item qty spam 42 eggs 451 bacon 0 + ``` `simple` is the default format (the default may change in future @@ -223,6 +230,7 @@ item qty spam 42 eggs 451 bacon 0 + ``` `github` follows the conventions of GitHub flavored Markdown. It @@ -230,11 +238,12 @@ corresponds to the `pipe` format without alignment colons: ```pycon >>> print(tabulate(table, headers, tablefmt="github")) -| item | qty | +| item | qty | |--------|-------| -| spam | 42 | -| eggs | 451 | -| bacon | 0 | +| spam | 42 | +| eggs | 451 | +| bacon | 0 | + ``` `grid` is like tables formatted by Emacs' @@ -252,6 +261,7 @@ corresponds to the `pipe` format without alignment colons: +--------+-------+ | bacon | 0 | +--------+-------+ + ``` `simple_grid` draws a grid using single-line box-drawing characters: @@ -333,6 +343,7 @@ corresponds to the `pipe` format without alignment colons: ├────────┼───────┤ │ bacon │ 0 │ ╘════════╧═══════╛ + ``` `colon_grid` is similar to `grid` but uses colons only to define @@ -437,6 +448,7 @@ similar the alignment specification of Pandoc `grid_tables`: spam | 42 eggs | 451 bacon | 0 + ``` `pretty` attempts to be close to the format emitted by the PrettyTables @@ -451,6 +463,7 @@ library: | eggs | 451 | | bacon | 0 | +-------+-----+ + ``` `psql` is like tables formatted by Postgres' psql cli: @@ -464,6 +477,7 @@ library: | eggs | 451 | | bacon | 0 | +--------+-------+ + ``` `pipe` follows the conventions of [PHP Markdown @@ -478,6 +492,7 @@ indicate column alignment: | spam | 42 | | eggs | 451 | | bacon | 0 | + ``` `asciidoc` formats data like a simple table of the @@ -488,11 +503,12 @@ format: >>> print(tabulate(table, headers, tablefmt="asciidoc")) [cols="8<,7>",options="header"] |==== -| item | qty -| spam | 42 -| eggs | 451 -| bacon | 0 +| item | qty +| spam | 42 +| eggs | 451 +| bacon | 0 |==== + ``` `orgtbl` follows the conventions of Emacs @@ -506,6 +522,7 @@ in the minor orgtbl-mode. Hence its name: | spam | 42 | | eggs | 451 | | bacon | 0 | + ``` `jira` follows the conventions of Atlassian Jira markup language: @@ -516,6 +533,7 @@ in the minor orgtbl-mode. Hence its name: | spam | 42 | | eggs | 451 | | bacon | 0 | + ``` `rst` formats data like a simple table of the @@ -531,6 +549,7 @@ spam 42 eggs 451 bacon 0 ====== ===== + ``` `mediawiki` format produces a table markup used in @@ -550,6 +569,7 @@ MediaWiki-based sites: |- | bacon || style="text-align: right;"| 0 |} + ``` `moinmoin` format produces a table markup used in @@ -557,20 +577,22 @@ MediaWiki-based sites: ```pycon >>> print(tabulate(table, headers, tablefmt="moinmoin")) -|| ''' item ''' || ''' quantity ''' || -|| spam || 41.999 || -|| eggs || 451 || -|| bacon || || +|| ''' item ''' || ''' qty ''' || +|| spam || 42 || +|| eggs || 451 || +|| bacon || 0 || + ``` `youtrack` format produces a table markup used in Youtrack tickets: ```pycon >>> print(tabulate(table, headers, tablefmt="youtrack")) -|| item || quantity || -| spam | 41.999 | -| eggs | 451 | -| bacon | | +|| item || qty || +| spam | 42 | +| eggs | 451 | +| bacon | 0 | + ``` `textile` format produces a table markup used in @@ -582,6 +604,7 @@ MediaWiki-based sites: |<. spam |>. 42 | |<. eggs |>. 451 | |<. bacon |>. 0 | + ``` `html` produces standard HTML markup as an html.escape'd str @@ -592,13 +615,16 @@ and a .str property so that the raw HTML remains accessible. ```pycon >>> print(tabulate(table, headers, tablefmt="html")) - + + +
item qty
spam 42
eggs 451
bacon 0
+ ``` `latex` format creates a `tabular` environment for LaTeX markup, @@ -616,6 +642,7 @@ correspondents: bacon & 0 \\ \hline \end{tabular} + ``` `latex_raw` behaves like `latex` but does not escape LaTeX commands and @@ -650,6 +677,7 @@ at a glance: 12345 1234.5 ---------- + ``` Compare this with a more common right alignment: @@ -663,6 +691,7 @@ Compare this with a more common right alignment: 12345 1234.5 ------ + ``` For `tabulate`, anything which can be parsed as a number is a number. @@ -671,7 +700,7 @@ comes in handy when reading a mixed table of text and numbers from a file: ```pycon ->>> import csv ; from StringIO import StringIO +>>> import csv; from io import StringIO >>> table = list(csv.reader(StringIO("spam, 42\neggs, 451\n"))) >>> table [['spam', ' 42'], ['eggs', ' 451']] @@ -680,16 +709,18 @@ file: spam 42 eggs 451 ---- ---- + ``` To disable this feature use `disable_numparse=True`. ```pycon ->>> print(tabulate.tabulate([["Ver1", "18.0"], ["Ver2","19.2"]], tablefmt="simple", disable_numparse=True)) +>>> print(tabulate([["Ver1", "18.0"], ["Ver2","19.2"]], tablefmt="simple", disable_numparse=True)) ---- ---- Ver1 18.0 Ver2 19.2 ---- ---- + ``` ### Custom column alignment @@ -704,6 +735,7 @@ Furthermore, you can define `colalign` for column-specific alignment as a list o 1 2 3 4 111 222 333 444 --- --- --- --- + ``` ### Custom header alignment @@ -714,11 +746,11 @@ Headers' alignment can be defined separately from columns'. Like for columns, yo ```pycon >>> print(tabulate([[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'))) - h e a d e r --- --- --- --- --- --- 1 2 3 4 5 6 111 222 333 444 555 666 + ``` ### Number formatting @@ -732,6 +764,7 @@ columns of decimal numbers. Use `floatfmt` named argument: pi 3.1416 e 2.7183 -- ------ + ``` `floatfmt` argument can be a list or a tuple of format strings, one per @@ -742,6 +775,7 @@ column, in which case every column may have different number formatting: --- ----- ------- 0.1 0.123 0.12345 --- ----- ------- + ``` `intfmt` works similarly for integers @@ -752,6 +786,33 @@ column, in which case every column may have different number formatting: b 90,000 - ------ + +### Type Deduction and Missing Values + +When `tabulate` sees numerical data (with our without comma separators), it +attempts to align the column on the decimal point. However, if it observes +non-numerical data in the column, it aligns it to the left by default. If +data is missing in a column (either None or empty values), the remaining +data in the column is used to infer the type: + +```pycon +>>> from fractions import Fraction +>>> test_table = [ +... [None, "1.23423515351", Fraction(1, 3)], +... [Fraction(56789, 1000000), 12345.1, b"abc"], +... ["", b"", None], +... [Fraction(10000, 3), None, ""], +... ] +>>> print(tabulate(test_table, floatfmt=",.5g", missingval="?")) +------------ ----------- --- + ? 1.2342 1/3 + 0.056789 12,345 abc + ? +3,333.3 ? +------------ ----------- --- + +``` + ### Text formatting By default, `tabulate` removes leading and trailing whitespace from text @@ -802,6 +863,7 @@ a multiline cell, and headers with a multiline cell: ```pycon >>> table = [["eggs",451],["more\nspam",42]] >>> headers = ["item\nname", "qty"] + ``` `plain` tables: @@ -813,6 +875,7 @@ name eggs 451 more 42 spam + ``` `simple` tables: @@ -825,6 +888,7 @@ name eggs 451 more 42 spam + ``` `grid` tables: @@ -840,6 +904,7 @@ spam | more | 42 | | spam | | +--------+-------+ + ``` `fancy_grid` tables: @@ -855,6 +920,7 @@ spam │ more │ 42 │ │ spam │ │ ╘════════╧═══════╛ + ``` `pipe` tables: @@ -867,6 +933,7 @@ spam | eggs | 451 | | more | 42 | | spam | | + ``` `orgtbl` tables: @@ -879,18 +946,19 @@ spam | eggs | 451 | | more | 42 | | spam | | + ``` `jira` tables: ```pycon >>> print(tabulate(table, headers, tablefmt="jira")) -| item | qty | -| name | | -|:-------|------:| +|| item || qty || +|| name || || | eggs | 451 | | more | 42 | | spam | | + ``` `presto` tables: @@ -903,6 +971,7 @@ spam eggs | 451 more | 42 spam | + ``` `pretty` tables: @@ -917,6 +986,7 @@ spam | more | 42 | | spam | | +------+-----+ + ``` `psql` tables: @@ -931,6 +1001,7 @@ spam | more | 42 | | spam | | +--------+-------+ + ``` `rst` tables: @@ -945,6 +1016,7 @@ eggs 451 more 42 spam ====== ===== + ``` Multiline cells are not well-supported for the other table formats. @@ -974,6 +1046,7 @@ the lines being wrapped would probably be significantly longer than this. | John Smith | Middle | | | Manager | +------------+---------+ + ``` ### Adding Separating lines @@ -1016,7 +1089,7 @@ hyperlinks is that column width will be based on the length of the URL _text_ ra itself (terminals would show this text). For example: >>> len('\x1b]8;;https://example.com\x1b\\example\x1b]8;;\x1b\\') # display length is 7, showing 'example' - 45 + 40 Usage of the command line utility @@ -1136,6 +1209,13 @@ tox -e lint See `tox.ini` file to learn how to use to test individual Python versions. +To test the "doctest" examples and their outputs in `README.md`: + +```shell +python3 -m pip install pytest-doctestplus[md] +python3 -m doctest README.md +``` + Contributors ------------ From 232ed74a4be2806bda886739a20a703b9c1043ea Mon Sep 17 00:00:00 2001 From: Perry Kundert Date: Tue, 8 Oct 2024 12:49:37 -0600 Subject: [PATCH 086/204] Begin trying to simplify _isnumber --- README.md | 14 +++++++++++++ tabulate/__init__.py | 48 +++++++++++++++++++++++++++++++++++--------- 2 files changed, 53 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 70b68395..f3d0fa92 100644 --- a/README.md +++ b/README.md @@ -813,6 +813,20 @@ data in the column is used to infer the type: ``` +The deduced type (eg. str, float) influences the rendering of any types +that have alternative representations. For example, since `Fraction` has +methods `__str__` and `__float__` defined (and hence is convertible to a +`float` and also has a `str` representation), the appropriate +representation is selected for the column's deduced type. In order to not +lose precision accidentally, types having both an `__int__` and +`__float__` represention will be considered a `float`. + +Therefore, if your table contains types convertible to int/float but you'd +*prefer* they be represented as strings, or your strings *might* all look +like numbers such as "1e23": either convert them to the desired +representation before you `tabulate`, or ensure that the column always +contains at least one other `str`. + ### Text formatting By default, `tabulate` removes leading and trailing whitespace from text diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 0d249ac5..b15d7f02 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -876,25 +876,55 @@ def _isconvertible(conv, string): def _isnumber(string): - """ + """Detects if something *could* be considered a numeric value, vs. just a string. + + This promotes types convertible to both int and float to be considered + a float. Note that, iff *all* values appear to be some form of numeric + value such as eg. "1e2", they would be considered numbers! + + The exception is things that appear to be numbers but overflow to + +/-inf, eg. "1e23456"; we'll have to exclude them explicitly. + + >>> _isnumber(123) + True + >>> _isnumber(123.45) + True >>> _isnumber("123.45") True >>> _isnumber("123") True >>> _isnumber("spam") False - >>> _isnumber("123e45678") + >>> _isnumber("123e45") + True + >>> _isnumber("123e45678") # evaluates equal to 'inf', but ... isn't False >>> _isnumber("inf") True + >>> from fractions import Fraction + >>> _isnumber(Fraction(1,3)) + True + """ - if not _isconvertible(float, string): - return False - elif isinstance(string, (str, bytes)) and ( - math.isinf(float(string)) or math.isnan(float(string)) - ): - return string.lower() in ["inf", "-inf", "nan"] - return True + return ( + # fast path + type(string) in (float, int) + # covers 'NaN', +/- 'inf', and eg. '1e2', as well as any type + # convertible to int/float. + or ( + _isconvertible(float, string) + and ( + # some other type convertible to float + not isinstance(string, (str, bytes)) + # or, a numeric string eg. "1e1...", "NaN", ..., but isn't + # just an over/underflow + or ( + not (math.isinf(float(string)) or math.isnan(float(string))) + or string.lower() in ["inf", "-inf", "nan"] + ) + ) + ) + ) def _isint(string, inttype=int): From 787851ffe4350a779ba8ecd1e58c570f20d28c34 Mon Sep 17 00:00:00 2001 From: George Schizas Date: Tue, 22 Oct 2024 23:31:51 +0300 Subject: [PATCH 087/204] Use missingval instead of empty string for None values --- tabulate/__init__.py | 8 ++++---- test/test_textwrapper.py | 28 ++++++++++++++++++++++++---- 2 files changed, 28 insertions(+), 8 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 520b60ea..a7826832 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1623,7 +1623,7 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"): return rows, headers, headers_pad -def _wrap_text_to_colwidths(list_of_lists, colwidths, numparses=True): +def _wrap_text_to_colwidths(list_of_lists, colwidths, numparses=True, missingval=_DEFAULT_MISSINGVAL): if len(list_of_lists): num_cols = len(list_of_lists[0]) else: @@ -1646,7 +1646,7 @@ def _wrap_text_to_colwidths(list_of_lists, colwidths, numparses=True): # explicit than just `str` of the object. Also doesn't work for # custom floatfmt/intfmt, nor with any missing/blank cells. casted_cell = ( - '' if cell is None else str(cell) if _isnumber(cell) else _type(cell, numparse)(cell) + missingval if cell is None else str(cell) if _isnumber(cell) else _type(cell, numparse)(cell) ) wrapped = [ "\n".join(wrapper.wrap(line)) @@ -2247,7 +2247,7 @@ def tabulate( numparses = _expand_numparse(disable_numparse, num_cols) list_of_lists = _wrap_text_to_colwidths( - list_of_lists, maxcolwidths, numparses=numparses + list_of_lists, maxcolwidths, numparses=numparses, missingval=missingval ) if maxheadercolwidths is not None: @@ -2261,7 +2261,7 @@ def tabulate( numparses = _expand_numparse(disable_numparse, num_cols) headers = _wrap_text_to_colwidths( - [headers], maxheadercolwidths, numparses=numparses + [headers], maxheadercolwidths, numparses=numparses, missingval=missingval )[0] # empty values in the first column of RST tables should be escaped (issue #82) diff --git a/test/test_textwrapper.py b/test/test_textwrapper.py index b47ea3ec..02dcc415 100644 --- a/test/test_textwrapper.py +++ b/test/test_textwrapper.py @@ -224,10 +224,7 @@ def test_wrap_datetime(): def test_wrap_none_value(): """TextWrapper: Show that None can be wrapped without crashing""" - data = [ - ["First Entry", None], - ["Second Entry", None] - ] + data = [["First Entry", None], ["Second Entry", None]] headers = ["Title", "Value"] result = tabulate(data, headers=headers, tablefmt="grid", maxcolwidths=[7, 5]) @@ -244,3 +241,26 @@ def test_wrap_none_value(): ] expected = "\n".join(expected) assert_equal(expected, result) + + +def test_wrap_none_value_with_missingval(): + """TextWrapper: Show that None can be wrapped without crashing and with a missing value""" + data = [["First Entry", None], ["Second Entry", None]] + headers = ["Title", "Value"] + result = tabulate( + data, headers=headers, tablefmt="grid", maxcolwidths=[7, 5], missingval="???" + ) + + expected = [ + "+---------+---------+", + "| Title | Value |", + "+=========+=========+", + "| First | ??? |", + "| Entry | |", + "+---------+---------+", + "| Second | ??? |", + "| Entry | |", + "+---------+---------+", + ] + expected = "\n".join(expected) + assert_equal(expected, result) From d29909b4fb17e2bbf62dde8bc730e9f29240155f Mon Sep 17 00:00:00 2001 From: Hashem Nasarat Date: Mon, 17 Mar 2025 16:47:49 -0400 Subject: [PATCH 088/204] Fix handling "True"/"False" bool str and None calling _type is incorrect here; the subsequent lines need a `str`. Also you can't reconstruct `None` with `type(None)(None)` anyway. This regressed in e8e3091d46966f462735f227d5ef4effdfaa0582 Fixes #305 --- tabulate/__init__.py | 8 +------- test/test_textwrapper.py | 24 ++++++++++++++++++++++++ 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index b15d7f02..b937d6cb 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1641,13 +1641,7 @@ def _wrap_text_to_colwidths(list_of_lists, colwidths, numparses=True): if width is not None: wrapper = _CustomTextWrap(width=width) - # Cast based on our internal type handling. Any future custom - # formatting of types (such as datetimes) may need to be more - # explicit than just `str` of the object. Also doesn't work for - # custom floatfmt/intfmt, nor with any missing/blank cells. - casted_cell = ( - str(cell) if _isnumber(cell) else _type(cell, numparse)(cell) - ) + casted_cell = str(cell) wrapped = [ "\n".join(wrapper.wrap(line)) for line in casted_cell.splitlines() diff --git a/test/test_textwrapper.py b/test/test_textwrapper.py index 8c0a6cc7..46dd818d 100644 --- a/test/test_textwrapper.py +++ b/test/test_textwrapper.py @@ -220,3 +220,27 @@ def test_wrap_datetime(): ] expected = "\n".join(expected) assert_equal(expected, result) + + +def test_wrap_optional_bool_strs(): + """TextWrapper: Show that str bools and None can be wrapped without crashing""" + data = [ + ["First Entry", "True"], + ["Second Entry", None], + ] + headers = ["Title", "When"] + result = tabulate(data, headers=headers, tablefmt="grid", maxcolwidths=[7, 5]) + + expected = [ + "+---------+--------+", + "| Title | When |", + "+=========+========+", + "| First | True |", + "| Entry | |", + "+---------+--------+", + "| Second | None |", + "| Entry | |", + "+---------+--------+", + ] + expected = "\n".join(expected) + assert_equal(expected, result) From 5efffde6bbf1a72e526c2dc35b24a31bd0480562 Mon Sep 17 00:00:00 2001 From: George Schizas Date: Wed, 2 Apr 2025 21:23:06 +0300 Subject: [PATCH 089/204] Remove setuptools dependency --- pyproject.toml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 4144f9b9..944106ba 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ -[build-system] -requires = ["setuptools>=61.2.0", "setuptools_scm[toml]>=3.4.3"] -build-backend = "setuptools.build_meta" +#[build-system] +#requires = ["setuptools>=61.2.0", "setuptools_scm[toml]>=3.4.3"] +#build-backend = "setuptools.build_meta" [project] name = "tabulate" From 5efa7e253326d011f04034b7309edd7d1f44dd9e Mon Sep 17 00:00:00 2001 From: George Schizas Date: Wed, 2 Apr 2025 21:24:11 +0300 Subject: [PATCH 090/204] Remove setuptools dependency --- pyproject.toml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 944106ba..6e5b6929 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ -#[build-system] -#requires = ["setuptools>=61.2.0", "setuptools_scm[toml]>=3.4.3"] -#build-backend = "setuptools.build_meta" +# [build-system] +# requires = ["setuptools>=61.2.0", "setuptools_scm[toml]>=3.4.3"] +# build-backend = "setuptools.build_meta" [project] name = "tabulate" @@ -32,8 +32,8 @@ widechars = ["wcwidth"] [project.scripts] tabulate = "tabulate:_main" -[tool.setuptools] -packages = ["tabulate"] +# [tool.setuptools] +# packages = ["tabulate"] [tool.setuptools_scm] write_to = "tabulate/version.py" From 3ef6249547368357e631f85fda22aedfd37f551b Mon Sep 17 00:00:00 2001 From: George Schizas Date: Wed, 2 Apr 2025 21:25:38 +0300 Subject: [PATCH 091/204] Remove setuptools dependency --- pyproject.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 6e5b6929..cdd62d56 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -35,5 +35,5 @@ tabulate = "tabulate:_main" # [tool.setuptools] # packages = ["tabulate"] -[tool.setuptools_scm] -write_to = "tabulate/version.py" +# [tool.setuptools_scm] +# write_to = "tabulate/version.py" From 9dedd450439610e326b79b15cb1ece36ee968766 Mon Sep 17 00:00:00 2001 From: Mikhail Korobkin Date: Tue, 6 May 2025 15:05:05 +0300 Subject: [PATCH 092/204] Add missed multiline support for github --- tabulate/__init__.py | 1 + test/test_output.py | 17 +++++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index b15d7f02..d418e96f 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -737,6 +737,7 @@ def escape_empty(val): "pretty": "pretty", "psql": "psql", "rst": "rst", + "github": "github", "outline": "outline", "simple_outline": "simple_outline", "rounded_outline": "rounded_outline", diff --git a/test/test_output.py b/test/test_output.py index e3d369ae..2a1415b2 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -509,6 +509,23 @@ def test_github(): assert_equal(expected, result) +def test_github_multiline(): + "Output: github with multiline cells with headers" + table = [[2, "foo\nbar"]] + headers = ("more\nspam eggs", "more spam\n& eggs") + expected = "\n".join( + [ + "| more | more spam |", + "| spam eggs | & eggs |", + "|-------------|-------------|", + "| 2 | foo |", + "| | bar |", + ] + ) + result = tabulate(table, headers, tablefmt="github") + assert_equal(expected, result) + + def test_grid(): "Output: grid with headers" expected = "\n".join( From 3c9d404c0189f4cdaf1a58e3413cd88675d5ae35 Mon Sep 17 00:00:00 2001 From: "Jun, Koo" Date: Mon, 26 May 2025 04:00:34 +0900 Subject: [PATCH 093/204] fix(docs): Correct typo in ANSI support section --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f3d0fa92..dedbf729 100644 --- a/README.md +++ b/README.md @@ -1098,7 +1098,7 @@ table, however, ANSI escape sequences are not removed so the original styling is Some terminals support a special grouping of ANSI escape sequences that are intended to display hyperlinks much in the same way they are shown in browsers. These are handled just as mentioned before: non-printable -ANSI escape sequences are removed prior to string length calculation. The only diifference with escaped +ANSI escape sequences are removed prior to string length calculation. The only difference with escaped hyperlinks is that column width will be based on the length of the URL _text_ rather than the URL itself (terminals would show this text). For example: From 7a19c30763c8f6f52161ac77bb233353d7b2d1a9 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Wed, 23 Jul 2025 18:58:33 +0200 Subject: [PATCH 094/204] PEP 639 compliance MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Declare licenses using only these two fields, as per PEP 639: * license: SPDX license expression consisting of one or more license identifiers * license-files: list of license file glob patterns Supported by setuptools ≥ 77.0, or perhaps setuptools ≥ 77.0.3 which irons out some bugs: https://packaging.python.org/en/latest/guides/writing-pyproject-toml/#license-and-license-files --- pyproject.toml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 4144f9b9..d13e92d4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,16 +1,16 @@ [build-system] -requires = ["setuptools>=61.2.0", "setuptools_scm[toml]>=3.4.3"] +requires = ["setuptools>=77.0.3", "setuptools_scm[toml]>=3.4.3"] build-backend = "setuptools.build_meta" [project] name = "tabulate" authors = [{name = "Sergey Astanin", email = "s.astanin@gmail.com"}] -license = {text = "MIT"} +license = "MIT" +license-files = ["LICENSE"] description = "Pretty-print tabular data" readme = "README.md" classifiers = [ "Development Status :: 4 - Beta", - "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.9", From 34bd63aaca3e6b68a11f508f82e47cc4d35ee54b Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Wed, 23 Jul 2025 19:07:10 +0200 Subject: [PATCH 095/204] Fix typo found by codespell --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6c09f0ec..223a85a2 100644 --- a/README.md +++ b/README.md @@ -819,7 +819,7 @@ methods `__str__` and `__float__` defined (and hence is convertible to a `float` and also has a `str` representation), the appropriate representation is selected for the column's deduced type. In order to not lose precision accidentally, types having both an `__int__` and -`__float__` represention will be considered a `float`. +`__float__` representation will be considered a `float`. Therefore, if your table contains types convertible to int/float but you'd *prefer* they be represented as strings, or your strings *might* all look From f967017d7d09d8aa7e91150946131543aeaf5db4 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Sat, 13 Sep 2025 16:08:16 +0200 Subject: [PATCH 096/204] Robust test for callable objects - If the object implements a custom `__getattr__`, or if its `__call__` is itself not callable, you may get misleading results. - Instead use the built-in `callable` function. Not only is it more robust, but it makes the intent clear and the code more readable. --- tabulate/__init__.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index e100c097..e1756f84 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1480,7 +1480,7 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"): index = None if hasattr(tabular_data, "keys") and hasattr(tabular_data, "values"): # dict-like and pandas.DataFrame? - if hasattr(tabular_data.values, "__call__"): + if callable(tabular_data.values): # likely a conventional dict keys = tabular_data.keys() try: @@ -2515,7 +2515,7 @@ def _build_row(padded_cells, colwidths, colaligns, rowfmt): "Return a string which represents a row of data cells." if not rowfmt: return None - if hasattr(rowfmt, "__call__"): + if callable(rowfmt): return rowfmt(padded_cells, colwidths, colaligns) else: return _build_simple_row(padded_cells, rowfmt) @@ -2566,7 +2566,7 @@ def _build_line(colwidths, colaligns, linefmt): "Return a string which represents a horizontal line." if not linefmt: return None - if hasattr(linefmt, "__call__"): + if callable(linefmt): return linefmt(colwidths, colaligns) else: begin, fill, sep, end = linefmt From 3fdc1302ecbb5d28458ddef389f5ff839c474ff8 Mon Sep 17 00:00:00 2001 From: J08nY Date: Thu, 19 Oct 2023 13:10:57 +0200 Subject: [PATCH 097/204] Fix asciidoc alignment Fixes #256. --- tabulate/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index e100c097..5816e058 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -259,7 +259,7 @@ def make_header_line(is_header, colwidths, colaligns): colwidths, [alignment[colalign] for colalign in colaligns] ) asciidoc_column_specifiers = [ - f"{width:d}{align}" for width, align in asciidoc_alignments + f"{align}{width:d}" for width, align in asciidoc_alignments ] header_list = ['cols="' + (",".join(asciidoc_column_specifiers)) + '"'] From 7a2e5f3dc4b08a7ca85e0ca065daee216b0f0e34 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Sat, 13 Sep 2025 18:19:26 +0200 Subject: [PATCH 098/204] Fix asciidoc tests and docs accordingly --- README.md | 2 +- test/test_output.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 223a85a2..5bbe2521 100644 --- a/README.md +++ b/README.md @@ -501,7 +501,7 @@ format: ```pycon >>> print(tabulate(table, headers, tablefmt="asciidoc")) -[cols="8<,7>",options="header"] +[cols="<8,>7",options="header"] |==== | item | qty | spam | 42 diff --git a/test/test_output.py b/test/test_output.py index 12dfc3a3..58373795 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -2101,7 +2101,7 @@ def test_asciidoc(): "Output: asciidoc with headers" expected = "\n".join( [ - '[cols="11<,11>",options="header"]', + '[cols="<11,>11",options="header"]', "|====", "| strings | numbers ", "| spam | 41.9999 ", @@ -2117,7 +2117,7 @@ def test_asciidoc_headerless(): "Output: asciidoc without headers" expected = "\n".join( [ - '[cols="6<,10>"]', + '[cols="<6,>10"]', "|====", "| spam | 41.9999 ", "| eggs | 451 ", From bb1bf9f409788057f3355f034f90013858270a12 Mon Sep 17 00:00:00 2001 From: George Schizas Date: Wed, 5 Nov 2025 15:53:18 +0200 Subject: [PATCH 099/204] Fix crash when cell is empty --- tabulate/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index a7826832..0137f837 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1646,7 +1646,7 @@ def _wrap_text_to_colwidths(list_of_lists, colwidths, numparses=True, missingval # explicit than just `str` of the object. Also doesn't work for # custom floatfmt/intfmt, nor with any missing/blank cells. casted_cell = ( - missingval if cell is None else str(cell) if _isnumber(cell) else _type(cell, numparse)(cell) + missingval if cell is None else str(cell) if cell == '' or _isnumber(cell) else _type(cell, numparse)(cell) ) wrapped = [ "\n".join(wrapper.wrap(line)) From c59a5ff3ef898464df25f8bb97a611c9c4ff5013 Mon Sep 17 00:00:00 2001 From: Kadir Can Ozden <101993364+bysiber@users.noreply.github.com> Date: Sun, 22 Feb 2026 02:03:39 +0300 Subject: [PATCH 100/204] Handle ValueError in _format when float conversion fails When a column contains both bool-like strings ('True'/'False') and numeric strings, the column type is detected as float. Formatting then crashes with ValueError on float('False'). Catch ValueError and TypeError in the float branch of _format and fall back to string formatting. Fixes #209 --- tabulate/__init__.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index e100c097..7c180155 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1352,12 +1352,18 @@ def _format(val, valtype, floatfmt, intfmt, missingval="", has_invisible=True): is_a_colored_number = has_invisible and isinstance(val, (str, bytes)) if is_a_colored_number: raw_val = _strip_ansi(val) - formatted_val = format(float(raw_val), floatfmt) + try: + formatted_val = format(float(raw_val), floatfmt) + except (ValueError, TypeError): + return f"{val}" return val.replace(raw_val, formatted_val) else: if isinstance(val, str) and "," in val: val = val.replace(",", "") # handle thousands-separators - return format(float(val), floatfmt) + try: + return format(float(val), floatfmt) + except (ValueError, TypeError): + return f"{val}" else: return f"{val}" From 886e2ed87b499e8485882da0ea5f5b122ca1d55a Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Wed, 4 Mar 2026 17:26:37 +0100 Subject: [PATCH 101/204] fix conflicting wrapping behavior for missing (None) values --- tabulate/__init__.py | 2 +- test/test_textwrapper.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index a1bdfa21..7d63ac89 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1661,7 +1661,7 @@ def _wrap_text_to_colwidths(list_of_lists, colwidths, numparses=True, missingval # explicit than just `str` of the object. Also doesn't work for # custom floatfmt/intfmt, nor with any missing/blank cells. casted_cell = ( - missingval if cell is None else str(cell) if cell == '' or _isnumber(cell) else _type(cell, numparse)(cell) + missingval if cell is None else str(cell) if cell == '' or _isnumber(cell) else str(_type(cell, numparse)(cell)) ) wrapped = [ "\n".join(wrapper.wrap(line)) diff --git a/test/test_textwrapper.py b/test/test_textwrapper.py index ea07c8bf..8c43bb21 100644 --- a/test/test_textwrapper.py +++ b/test/test_textwrapper.py @@ -282,7 +282,7 @@ def test_wrap_optional_bool_strs(): "| First | True |", "| Entry | |", "+---------+--------+", - "| Second | None |", + "| Second | |", "| Entry | |", "+---------+--------+", ] From 5a579fc79bcb40f7ee6c655bd3a98af9df5a6558 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Wed, 4 Mar 2026 17:26:37 +0100 Subject: [PATCH 102/204] fix "DeprecationWarning: Data type alias 'a' was deprecated in NumPy 2.0. Use the 'S' alias instead." --- test/test_input.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/test_input.py b/test/test_input.py index 8368770e..49f44173 100644 --- a/test/test_input.py +++ b/test/test_input.py @@ -173,7 +173,7 @@ def test_numpy_record_array(): [("Alice", 23, 169.5), ("Bob", 27, 175.0)], dtype={ "names": ["name", "age", "height"], - "formats": ["a32", "uint8", "float32"], + "formats": ["S32", "uint8", "float32"], }, ) expected = "\n".join( @@ -199,7 +199,7 @@ def test_numpy_record_array_keys(): [("Alice", 23, 169.5), ("Bob", 27, 175.0)], dtype={ "names": ["name", "age", "height"], - "formats": ["a32", "uint8", "float32"], + "formats": ["S32", "uint8", "float32"], }, ) expected = "\n".join( @@ -225,7 +225,7 @@ def test_numpy_record_array_headers(): [("Alice", 23, 169.5), ("Bob", 27, 175.0)], dtype={ "names": ["name", "age", "height"], - "formats": ["a32", "uint8", "float32"], + "formats": ["S32", "uint8", "float32"], }, ) expected = "\n".join( From f0a5df6ee72fa1bb27596e43b64ff2746fee284b Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Wed, 4 Mar 2026 17:26:37 +0100 Subject: [PATCH 103/204] apply pre_commit hooks (black) --- README.md | 12 ++++++------ tabulate/__init__.py | 35 ++++++++++++++++++++++++++++++----- test/test_output.py | 2 ++ test/test_textwrapper.py | 4 ++-- 4 files changed, 40 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 223a85a2..5c69cd93 100644 --- a/README.md +++ b/README.md @@ -503,10 +503,10 @@ format: >>> print(tabulate(table, headers, tablefmt="asciidoc")) [cols="8<,7>",options="header"] |==== -| item | qty -| spam | 42 -| eggs | 451 -| bacon | 0 +| item | qty +| spam | 42 +| eggs | 451 +| bacon | 0 |==== ``` @@ -1065,11 +1065,11 @@ the lines being wrapped would probably be significantly longer than this. Text is preferably wrapped on whitespaces and right after the hyphens in hyphenated words. -break_long_words (default: True) If true, then words longer than width will be broken in order to ensure that no lines are longer than width. +break_long_words (default: True) If true, then words longer than width will be broken in order to ensure that no lines are longer than width. If it is false, long words will not be broken, and some lines may be longer than width. (Long words will be put on a line by themselves, in order to minimize the amount by which width is exceeded.) -break_on_hyphens (default: True) If true, wrapping will occur preferably on whitespaces and right after hyphens in compound words, as it is customary in English. +break_on_hyphens (default: True) If true, wrapping will occur preferably on whitespaces and right after hyphens in compound words, as it is customary in English. If false, only whitespaces will be considered as potentially good places for line breaks. ```pycon diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 7d63ac89..ee646ad7 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1638,7 +1638,14 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"): return rows, headers, headers_pad -def _wrap_text_to_colwidths(list_of_lists, colwidths, numparses=True, missingval=_DEFAULT_MISSINGVAL, break_long_words=_BREAK_LONG_WORDS, break_on_hyphens=_BREAK_ON_HYPHENS): +def _wrap_text_to_colwidths( + list_of_lists, + colwidths, + numparses=True, + missingval=_DEFAULT_MISSINGVAL, + break_long_words=_BREAK_LONG_WORDS, + break_on_hyphens=_BREAK_ON_HYPHENS, +): if len(list_of_lists): num_cols = len(list_of_lists[0]) else: @@ -1655,13 +1662,21 @@ def _wrap_text_to_colwidths(list_of_lists, colwidths, numparses=True, missingval continue if width is not None: - wrapper = _CustomTextWrap(width=width, break_long_words=break_long_words, break_on_hyphens=break_on_hyphens) + wrapper = _CustomTextWrap( + width=width, + break_long_words=break_long_words, + break_on_hyphens=break_on_hyphens, + ) # Cast based on our internal type handling. Any future custom # formatting of types (such as datetimes) may need to be more # explicit than just `str` of the object. Also doesn't work for # custom floatfmt/intfmt, nor with any missing/blank cells. casted_cell = ( - missingval if cell is None else str(cell) if cell == '' or _isnumber(cell) else str(_type(cell, numparse)(cell)) + missingval + if cell is None + else str(cell) + if cell == "" or _isnumber(cell) + else str(_type(cell, numparse)(cell)) ) wrapped = [ "\n".join(wrapper.wrap(line)) @@ -2264,7 +2279,12 @@ def tabulate( numparses = _expand_numparse(disable_numparse, num_cols) list_of_lists = _wrap_text_to_colwidths( - list_of_lists, maxcolwidths, numparses=numparses, missingval=missingval, break_long_words=break_long_words, break_on_hyphens=break_on_hyphens + list_of_lists, + maxcolwidths, + numparses=numparses, + missingval=missingval, + break_long_words=break_long_words, + break_on_hyphens=break_on_hyphens, ) if maxheadercolwidths is not None: @@ -2278,7 +2298,12 @@ def tabulate( numparses = _expand_numparse(disable_numparse, num_cols) headers = _wrap_text_to_colwidths( - [headers], maxheadercolwidths, numparses=numparses, missingval=missingval, break_long_words=break_long_words, break_on_hyphens=break_on_hyphens + [headers], + maxheadercolwidths, + numparses=numparses, + missingval=missingval, + break_long_words=break_long_words, + break_on_hyphens=break_on_hyphens, )[0] # empty values in the first column of RST tables should be escaped (issue #82) diff --git a/test/test_output.py b/test/test_output.py index 12dfc3a3..d7c225b4 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -3320,6 +3320,7 @@ def test_preserve_whitespace(): result = tabulate(test_table, table_headers, preserve_whitespace=False) assert_equal(expected, result) + def test_break_long_words(): "Output: Default table output, with breakwords true." table_headers = ["h1", "h2", "h3"] @@ -3335,6 +3336,7 @@ def test_break_long_words(): result = tabulate(test_table, table_headers, maxcolwidths=3, break_long_words=True) assert_equal(expected, result) + def test_break_on_hyphens(): "Output: Default table output, with break on hyphens true." table_headers = ["h1", "h2", "h3"] diff --git a/test/test_textwrapper.py b/test/test_textwrapper.py index 8c43bb21..fa6eb00e 100644 --- a/test/test_textwrapper.py +++ b/test/test_textwrapper.py @@ -263,9 +263,9 @@ def test_wrap_none_value_with_missingval(): "+---------+---------+", ] expected = "\n".join(expected) - assert_equal(expected, result) + assert_equal(expected, result) + - def test_wrap_optional_bool_strs(): """TextWrapper: Show that str bools and None can be wrapped without crashing""" data = [ From 38b7333b1f52bdc30960f351dc85823f4a766894 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Wed, 4 Mar 2026 17:26:38 +0100 Subject: [PATCH 104/204] uncomment [tool.setuptools_scm] to detect package version --- pyproject.toml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 0abfebe9..3962cb92 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -35,5 +35,4 @@ tabulate = "tabulate:_main" # [tool.setuptools] # packages = ["tabulate"] -# [tool.setuptools_scm] -# write_to = "tabulate/version.py" +[tool.setuptools_scm] From d42acbe85c0dba1d70cd02aa1f754480938c76bc Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Wed, 4 Mar 2026 17:26:38 +0100 Subject: [PATCH 105/204] fix test_internal being stuck on test_wrap_text_wide_chars (fix _handle_long_word) --- tabulate/__init__.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index ee646ad7..f6a7c833 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -2775,7 +2775,8 @@ def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width): chunk = reversed_chunks[-1] i = 1 # Only count printable characters, so strip_ansi first, index later. - while len(_strip_ansi(chunk)[:i]) <= space_left: + stripped_chunk = _strip_ansi(chunk) + while i <= len(stripped_chunk) and self._len(stripped_chunk[:i]) <= space_left: i = i + 1 # Consider escape codes when breaking words up total_escape_len = 0 From 95c815d3995febb489fe7b489ab15afa0dd9374c Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Wed, 4 Mar 2026 17:26:38 +0100 Subject: [PATCH 106/204] re-enable test_alignment_of_decimal_numbers_with_commas --- test/test_regression.py | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/test/test_regression.py b/test/test_regression.py index bf262470..573172de 100644 --- a/test/test_regression.py +++ b/test/test_regression.py @@ -258,15 +258,14 @@ def test_alignment_of_decimal_numbers_with_ansi_color(): def test_alignment_of_decimal_numbers_with_commas(): "Regression: alignment for decimal numbers with comma separators" - skip("test is temporarily disable until the feature is reimplemented") - # table = [["c1r1", "14502.05"], ["c1r2", 105]] - # result = tabulate(table, tablefmt="grid", floatfmt=',.2f') - # expected = "\n".join( - # ['+------+-----------+', '| c1r1 | 14,502.05 |', - # '+------+-----------+', '| c1r2 | 105.00 |', - # '+------+-----------+'] - # ) - # assert_equal(expected, result) + table = [["c1r1", "14502.05"], ["c1r2", 105]] + result = tabulate(table, tablefmt="grid", floatfmt=',.2f') + expected = "\n".join( + ['+------+-----------+', '| c1r1 | 14,502.05 |', + '+------+-----------+', '| c1r2 | 105.00 |', + '+------+-----------+'] + ) + assert_equal(expected, result) def test_long_integers(): From a3223ed1ca64b6f937aaa90c0f4efc6a0a800cb9 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Wed, 4 Mar 2026 17:26:38 +0100 Subject: [PATCH 107/204] run pre_commit hooks (black) --- tabulate/__init__.py | 4 +++- test/test_regression.py | 12 ++++++++---- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index f6a7c833..7cf521c7 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -2776,7 +2776,9 @@ def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width): i = 1 # Only count printable characters, so strip_ansi first, index later. stripped_chunk = _strip_ansi(chunk) - while i <= len(stripped_chunk) and self._len(stripped_chunk[:i]) <= space_left: + while ( + i <= len(stripped_chunk) and self._len(stripped_chunk[:i]) <= space_left + ): i = i + 1 # Consider escape codes when breaking words up total_escape_len = 0 diff --git a/test/test_regression.py b/test/test_regression.py index 573172de..f56f48e6 100644 --- a/test/test_regression.py +++ b/test/test_regression.py @@ -259,11 +259,15 @@ def test_alignment_of_decimal_numbers_with_ansi_color(): def test_alignment_of_decimal_numbers_with_commas(): "Regression: alignment for decimal numbers with comma separators" table = [["c1r1", "14502.05"], ["c1r2", 105]] - result = tabulate(table, tablefmt="grid", floatfmt=',.2f') + result = tabulate(table, tablefmt="grid", floatfmt=",.2f") expected = "\n".join( - ['+------+-----------+', '| c1r1 | 14,502.05 |', - '+------+-----------+', '| c1r2 | 105.00 |', - '+------+-----------+'] + [ + "+------+-----------+", + "| c1r1 | 14,502.05 |", + "+------+-----------+", + "| c1r2 | 105.00 |", + "+------+-----------+", + ] ) assert_equal(expected, result) From e0a4311bcf6b930e24180c784c08293566b72304 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Wed, 4 Mar 2026 17:26:38 +0100 Subject: [PATCH 108/204] add py314-extra (full Python 3.14 tests) to tox.ini --- HOWTOPUBLISH | 2 +- tox.ini | 19 ++++++++++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/HOWTOPUBLISH b/HOWTOPUBLISH index 29c4545c..148190e5 100644 --- a/HOWTOPUBLISH +++ b/HOWTOPUBLISH @@ -1,6 +1,6 @@ # update contributors and CHANGELOG in README python -m pre_commit run -a # and then commit changes -tox -e py39-extra,py310-extra,py311-extra,py312-extra,py313-extra +tox -e py39-extra,py310-extra,py311-extra,py312-extra,py313-extra,py314-extra # tag version release python -m build -s # this will update tabulate/version.py python -m pip install . # install tabulate in the current venv diff --git a/tox.ini b/tox.ini index 9605e79b..7df9f0bb 100644 --- a/tox.ini +++ b/tox.ini @@ -8,7 +8,7 @@ # for testing and it is disabled by default. [tox] -envlist = lint, py{38, 39, 310, 311, 312, 313} +envlist = lint, py{38, 39, 310, 311, 312, 313, 314} isolated_build = True [gh] @@ -18,6 +18,7 @@ python = 3.11: py311-extra 3.12: py312-extra 3.13: py313-extra + 3.14: py314-extra [testenv] commands = pytest -v --doctest-modules --ignore benchmark {posargs} @@ -130,6 +131,22 @@ deps = pandas wcwidth +[testenv:py314] +basepython = python3.14 +commands = pytest -v --doctest-modules --ignore benchmark {posargs} +deps = + pytest + +[testenv:py314-extra] +basepython = python3.14 +setenv = PYTHONDEVMODE = 1 +commands = pytest -v --doctest-modules --ignore benchmark {posargs} +deps = + pytest + numpy + pandas + wcwidth + [flake8] max-complexity = 22 max-line-length = 99 From 27727c2d2327c755e6e6e2cd379ca44eb8b64e3a Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Wed, 4 Mar 2026 17:26:38 +0100 Subject: [PATCH 109/204] fix warnings in test_sqlite3 and test_sqlite3_keys --- test/test_input.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/test_input.py b/test/test_input.py index 49f44173..073dead2 100644 --- a/test/test_input.py +++ b/test/test_input.py @@ -313,6 +313,7 @@ def test_sqlite3(): cursor.execute("INSERT INTO people VALUES (?, ?, ?)", values) cursor.execute("SELECT name, age, height FROM people ORDER BY name") result = tabulate(cursor, headers=["whom", "how old", "how tall"]) + conn.close() expected = """\ whom how old how tall ------ --------- ---------- @@ -337,6 +338,7 @@ def test_sqlite3_keys(): 'SELECT name "whom", age "how old", height "how tall" FROM people ORDER BY name' ) result = tabulate(cursor, headers="keys") + conn.close() expected = """\ whom how old how tall ------ --------- ---------- From e13a4d0dd292cade200e653eb9155a1ca0f1dbea Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Wed, 4 Mar 2026 17:26:38 +0100 Subject: [PATCH 110/204] update _CustomTextWrap to make it compatible with Python 3.14 add `and space_left > 0` to prevent appending an empty string to `cur_line` when the line is already full. --- tabulate/__init__.py | 2 +- test/test_textwrapper.py | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 7cf521c7..0a321848 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -2769,7 +2769,7 @@ def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width): # If we're allowed to break long words, then do so: put as much # of the next chunk onto the current line as will fit. - if self.break_long_words: + if self.break_long_words and space_left > 0: # Tabulate Custom: Build the string up piece-by-piece in order to # take each charcter's width into account chunk = reversed_chunks[-1] diff --git a/test/test_textwrapper.py b/test/test_textwrapper.py index fa6eb00e..485fa30e 100644 --- a/test/test_textwrapper.py +++ b/test/test_textwrapper.py @@ -15,9 +15,9 @@ def test_wrap_multiword_non_wide(): orig = OTW(width=width) cust = CTW(width=width) - assert orig.wrap(data) == cust.wrap( - data - ), "Failure on non-wide char multiword regression check for width " + str(width) + assert [line.rstrip() for line in orig.wrap(data)] == [ + line.rstrip() for line in cust.wrap(data) + ], "Failure on non-wide char multiword regression check for width " + str(width) def test_wrap_multiword_non_wide_with_hypens(): @@ -27,9 +27,9 @@ def test_wrap_multiword_non_wide_with_hypens(): orig = OTW(width=width) cust = CTW(width=width) - assert orig.wrap(data) == cust.wrap( - data - ), "Failure on non-wide char hyphen regression check for width " + str(width) + assert [line.rstrip() for line in orig.wrap(data)] == [ + line.rstrip() for line in cust.wrap(data) + ], "Failure on non-wide char hyphen regression check for width " + str(width) def test_wrap_longword_non_wide(): From 87a9a4e07a5efb39b81fdb6ac513b1d345bb21fb Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Wed, 4 Mar 2026 17:26:38 +0100 Subject: [PATCH 111/204] fix #365 - added a regression test and a fix based on pull request #393 --- tabulate/__init__.py | 2 +- test/test_regression.py | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 0a321848..fb6e6352 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -2288,7 +2288,7 @@ def tabulate( ) if maxheadercolwidths is not None: - num_cols = len(list_of_lists[0]) + num_cols = len(list_of_lists[0]) if list_of_lists else len(headers) if isinstance(maxheadercolwidths, int): # Expand scalar for all columns maxheadercolwidths = _expand_iterable( maxheadercolwidths, num_cols, maxheadercolwidths diff --git a/test/test_regression.py b/test/test_regression.py index f56f48e6..113e9105 100644 --- a/test/test_regression.py +++ b/test/test_regression.py @@ -548,3 +548,15 @@ def test_empty_table_with_colalign(): ] ) assert_equal(expected, table) + + +def test_empty_table_with_maxheadercolwidths(): + "Regression: empty table with maxheadercolwidths kwarg (issue #365)" + result = tabulate([], headers=["one", "two", "three"], maxheadercolwidths=5) + expected = "\n".join( + [ + "one two three", + "----- ----- -------", + ] + ) + assert_equal(expected, result) From 4582b63010eb60e777ab3433df4a422599ef0afa Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Wed, 4 Mar 2026 17:26:38 +0100 Subject: [PATCH 112/204] drop Python 3.9 support, add Python 3.14 support --- HOWTOPUBLISH | 2 +- pyproject.toml | 4 ++-- tox.ini | 1 - 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/HOWTOPUBLISH b/HOWTOPUBLISH index 148190e5..5a072d10 100644 --- a/HOWTOPUBLISH +++ b/HOWTOPUBLISH @@ -1,6 +1,6 @@ # update contributors and CHANGELOG in README python -m pre_commit run -a # and then commit changes -tox -e py39-extra,py310-extra,py311-extra,py312-extra,py313-extra,py314-extra +tox -e py310-extra,py311-extra,py312-extra,py313-extra,py314-extra # tag version release python -m build -s # this will update tabulate/version.py python -m pip install . # install tabulate in the current venv diff --git a/pyproject.toml b/pyproject.toml index 3962cb92..b602919e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -13,14 +13,14 @@ classifiers = [ "Development Status :: 4 - Beta", "Operating System :: OS Independent", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", "Topic :: Software Development :: Libraries", ] -requires-python = ">=3.9" +requires-python = ">=3.10" dynamic = ["version"] [project.urls] diff --git a/tox.ini b/tox.ini index 7df9f0bb..77b5f2e7 100644 --- a/tox.ini +++ b/tox.ini @@ -13,7 +13,6 @@ isolated_build = True [gh] python = - 3.9: py39-extra 3.10: py310-extra 3.11: py311-extra 3.12: py312-extra From 9d930e8847b6e10baacaf23ccb46aeedbb499e3c Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Wed, 4 Mar 2026 17:55:01 +0100 Subject: [PATCH 113/204] add Python 3.14 to github workflow, upgrade lint workflow to Python 3.13 --- .github/workflows/lint.yml | 2 +- .github/workflows/tabulate.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 0093303c..3bf20ee2 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -9,7 +9,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - python-version: ['3.12'] + python-version: ['3.13'] steps: - uses: actions/checkout@v4 diff --git a/.github/workflows/tabulate.yml b/.github/workflows/tabulate.yml index c4594846..141a686f 100644 --- a/.github/workflows/tabulate.yml +++ b/.github/workflows/tabulate.yml @@ -8,7 +8,7 @@ jobs: build: strategy: matrix: - python-version: ['3.9', '3.10', '3.11', '3.12', '3.13'] + python-version: ['3.9', '3.10', '3.11', '3.12', '3.13', '3.14'] os: ["ubuntu-latest", "windows-latest", "macos-latest"] runs-on: ${{ matrix.os }} From 197a8036dc01a0645fafa72dcce329d37e9369a4 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Wed, 4 Mar 2026 18:12:45 +0100 Subject: [PATCH 114/204] add regression test for issue #209 - test_mixed_bool_strings_and_numeric_strings --- test/test_regression.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/test/test_regression.py b/test/test_regression.py index 113e9105..c2e95838 100644 --- a/test/test_regression.py +++ b/test/test_regression.py @@ -560,3 +560,10 @@ def test_empty_table_with_maxheadercolwidths(): ] ) assert_equal(expected, result) + + +def test_mixed_bool_strings_and_numeric_strings(): + "Regression: column with bool-like strings and numeric strings should not crash (issue #209)" + result = tabulate([["False"], ["1."]]) + expected = "\n".join(["-----", "False", " 1", "-----"]) + assert_equal(expected, result) From 4fa86395681e8502e1ee8ea7fcc5402adf53773b Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Sat, 13 Sep 2025 18:06:01 +0200 Subject: [PATCH 115/204] Improve string concatenation Avoid temporary array. --- tabulate/__init__.py | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 43bcbc6f..ddcf5f9e 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -142,8 +142,10 @@ def _pipe_line_with_colons(colwidths, colaligns): alignment (as in `pipe` output format).""" if not colaligns: # e.g. printing an empty data frame (github issue #15) colaligns = [""] * len(colwidths) - segments = [_pipe_segment_with_colons(a, w) for a, w in zip(colaligns, colwidths)] - return "|" + "|".join(segments) + "|" + segments = "|".join( + _pipe_segment_with_colons(a, w) for a, w in zip(colaligns, colwidths) + ) + return f"|{segments}|" def _grid_segment_with_colons(colwidth, align): @@ -165,8 +167,10 @@ def _grid_line_with_colons(colwidths, colaligns): in a grid table.""" if not colaligns: colaligns = [""] * len(colwidths) - segments = [_grid_segment_with_colons(w, a) for a, w in zip(colaligns, colwidths)] - return "+" + "+".join(segments) + "+" + segments = "+".join( + _grid_segment_with_colons(w, a) for a, w in zip(colaligns, colwidths) + ) + return f"+{segments}+" def _mediawiki_row_with_attrs(separator, cell_values, colwidths, colaligns): @@ -188,8 +192,8 @@ def _mediawiki_row_with_attrs(separator, cell_values, colwidths, colaligns): def _textile_row_with_attrs(cell_values, colwidths, colaligns): cell_values[0] += " " alignment = {"left": "<.", "right": ">.", "center": "=.", "decimal": ">."} - values = (alignment.get(a, "") + v for a, v in zip(colaligns, cell_values)) - return "|" + "|".join(values) + "|" + values = "|".join(alignment.get(a, "") + v for a, v in zip(colaligns, cell_values)) + return f"|{values}|" def _html_begin_table_without_header(colwidths_ignore, colaligns_ignore): @@ -258,10 +262,10 @@ def make_header_line(is_header, colwidths, colaligns): asciidoc_alignments = zip( colwidths, [alignment[colalign] for colalign in colaligns] ) - asciidoc_column_specifiers = [ + asciidoc_column_specifiers = ",".join( f"{width:d}{align}" for width, align in asciidoc_alignments - ] - header_list = ['cols="' + (",".join(asciidoc_column_specifiers)) + '"'] + ) + header_list = [f'cols="{asciidoc_column_specifiers}"'] # generate the list of options (currently only "header") options_list = [] @@ -270,7 +274,8 @@ def make_header_line(is_header, colwidths, colaligns): options_list.append("header") if options_list: - header_list += ['options="' + ",".join(options_list) + '"'] + options_list = ",".join(options_list) + header_list.append(f'options="{options_list}"') # generate the list of entries in the table header field From 8ca340f59e079e3b513068c76be9654205350542 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Sat, 13 Sep 2025 17:44:29 +0200 Subject: [PATCH 116/204] Fix typo in docs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit maxcolwidth → maxcolwidths maxheadercolwidth → maxheadercolwidths --- tabulate/__init__.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index ddcf5f9e..7a9ae625 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -2246,8 +2246,8 @@ def tabulate( Tabulate will, by default, set the width of each column to the length of the longest element in that column. However, in situations where fields are expected to reasonably be too long to look good as a single line, tabulate can help automate - word wrapping long fields for you. Use the parameter `maxcolwidth` to provide a - list of maximal column widths + word wrapping long fields for you. Use the parameter `maxcolwidths` to provide a + list of maximal column widths: >>> print(tabulate( \ [('1', 'John Smith', \ @@ -2264,7 +2264,7 @@ def tabulate( | | | better if it is wrapped a bit | +------------+------------+-------------------------------+ - Header column width can be specified in a similar way using `maxheadercolwidth` + Header column width can be specified in a similar way using `maxheadercolwidths`. """ From 5c10c81b76a473c52fa1575cf43c5ade9da26da0 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Wed, 4 Mar 2026 18:38:51 +0100 Subject: [PATCH 117/204] update pre-commit hooks as suggested by pull request #373 --- .pre-commit-config.yaml | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 7349858e..28c2f8c8 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,15 +1,19 @@ repos: - repo: https://github.com/python/black - rev: 22.3.0 + rev: 25.1.0 hooks: - id: black args: [--safe] language_version: python3 - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v2.2.3 + rev: v6.0.0 hooks: - id: trailing-whitespace - id: check-yaml - id: debug-statements - - id: flake8 language_version: python3 +- repo: https://github.com/pycqa/flake8 + rev: 7.3.0 + hooks: + - id: flake8 + language_version: python3 \ No newline at end of file From b96c59a6168a654d8c99ffdcaaa22c96d63102bb Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Wed, 4 Mar 2026 18:39:13 +0100 Subject: [PATCH 118/204] run pre-commit hooks (black) --- tabulate/__init__.py | 16 ++++++++++------ test/test_api.py | 4 +--- test/test_cli.py | 4 +--- test/test_internal.py | 13 +++++++++++-- 4 files changed, 23 insertions(+), 14 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 00d6e55b..f4147ad5 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1599,9 +1599,11 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"): if headers == "keys": headers = field_names rows = [ - [getattr(row, f) for f in field_names] - if not _is_separating_line(row) - else row + ( + [getattr(row, f) for f in field_names] + if not _is_separating_line(row) + else row + ) for row in rows ] @@ -1685,9 +1687,11 @@ def _wrap_text_to_colwidths( casted_cell = ( missingval if cell is None - else str(cell) - if cell == "" or _isnumber(cell) - else str(_type(cell, numparse)(cell)) + else ( + str(cell) + if cell == "" or _isnumber(cell) + else str(_type(cell, numparse)(cell)) + ) ) wrapped = [ "\n".join(wrapper.wrap(line)) diff --git a/test/test_api.py b/test/test_api.py index f35d09ad..9401a303 100644 --- a/test/test_api.py +++ b/test/test_api.py @@ -1,6 +1,4 @@ -"""API properties. - -""" +"""API properties.""" from tabulate import tabulate, tabulate_formats, simple_separated_format from common import skip diff --git a/test/test_cli.py b/test/test_cli.py index e71572d3..573c99e7 100644 --- a/test/test_cli.py +++ b/test/test_cli.py @@ -1,6 +1,4 @@ -"""Command-line interface. - -""" +"""Command-line interface.""" import os import sys diff --git a/test/test_internal.py b/test/test_internal.py index e7564d37..17107c6d 100644 --- a/test/test_internal.py +++ b/test/test_internal.py @@ -180,7 +180,9 @@ def test_wrap_text_wide_chars(): except ImportError: skip("test_wrap_text_wide_chars is skipped") - rows = [["청자청자청자청자청자", "약간 감싸면 더 잘 보일 수있는 다소 긴 설명입니다"]] + rows = [ + ["청자청자청자청자청자", "약간 감싸면 더 잘 보일 수있는 다소 긴 설명입니다"] + ] widths = [5, 20] expected = [ [ @@ -244,7 +246,14 @@ def test_wrap_text_to_colwidths_colors_wide_char(): except ImportError: skip("test_wrap_text_to_colwidths_colors_wide_char is skipped") - data = [[("\033[31m약간 감싸면 더 잘 보일 수있는 다소 긴" " 설명입니다 설명입니다 설명입니다 설명입니다 설명\033[0m")]] + data = [ + [ + ( + "\033[31m약간 감싸면 더 잘 보일 수있는 다소 긴" + " 설명입니다 설명입니다 설명입니다 설명입니다 설명\033[0m" + ) + ] + ] result = T._wrap_text_to_colwidths(data, [30]) expected = [ From 69f67cd72de4c7990bc7a25200b89ab9b2bdd870 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Sat, 13 Sep 2025 15:49:24 +0200 Subject: [PATCH 119/204] Do not call `getattr` with a constant value It is not any safer than normal property access. It feels like the intent might have been `hasattr()` instead of `getattr()`, but the initial commit e2086c3 appears to : - assume any attribute `dtype` is of type `numpy.dtype`, - test whether `numpy.dtype.names` is a list of fields names or `None`. https://numpy.org/doc/stable/reference/generated/numpy.dtype.names.html --- tabulate/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index f4147ad5..df2e634c 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1534,7 +1534,7 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"): elif ( headers == "keys" and hasattr(tabular_data, "dtype") - and getattr(tabular_data.dtype, "names") + and tabular_data.dtype.names ): # numpy record array headers = tabular_data.dtype.names From 13508e7a75783af650a2b76065dac28e06d1fa34 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Sat, 13 Sep 2025 15:44:03 +0200 Subject: [PATCH 120/204] Unnecessary `list` call The `sorted()` function returns a list: https://docs.python.org/3/library/functions.html#sorted --- tabulate/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index df2e634c..a63f0837 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -728,7 +728,7 @@ def escape_empty(val): } -tabulate_formats = list(sorted(_table_formats.keys())) +tabulate_formats = sorted(_table_formats.keys()) # The table formats for which multiline cells will be folded into subsequent # table rows. The key is the original format specified at the API. The value is From 76c3d37a5f51546b2bfba8d3e0648ebcda05b436 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Sat, 13 Sep 2025 14:46:09 +0200 Subject: [PATCH 121/204] Remove spurious space from error message --- tabulate/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index a63f0837..41b53b30 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -300,7 +300,7 @@ def make_header_line(is_header, colwidths, colaligns): else: raise ValueError( - " _asciidoc_row() requires two (colwidths, colaligns) " + "_asciidoc_row() requires two (colwidths, colaligns) " + "or three (cell_values, colwidths, colaligns) arguments) " ) From 4d535af12d2de46ee5a87329d2bc5810a386ef89 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Sat, 13 Sep 2025 15:26:25 +0200 Subject: [PATCH 122/204] Use specific noqa directives --- tabulate/__init__.py | 8 ++++---- test/common.py | 4 ++-- test/test_internal.py | 4 ++-- test/test_output.py | 32 ++++++++++++++++---------------- test/test_regression.py | 4 ++-- test/test_textwrapper.py | 4 ++-- 6 files changed, 28 insertions(+), 28 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 41b53b30..db1f18ce 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1150,7 +1150,7 @@ def _choose_width_fn(has_invisible, enable_widechars, is_multiline): else: line_width_fn = len if is_multiline: - width_fn = lambda s: _multiline_width(s, line_width_fn) # noqa + width_fn = lambda s: _multiline_width(s, line_width_fn) # noqa: E731 else: width_fn = line_width_fn return width_fn @@ -1190,7 +1190,7 @@ def _align_column_choose_width_fn(has_invisible, enable_widechars, is_multiline) else: line_width_fn = len if is_multiline: - width_fn = lambda s: _align_column_multiline_width(s, line_width_fn) # noqa + width_fn = lambda s: _align_column_multiline_width(s, line_width_fn) # noqa: E731 else: width_fn = line_width_fn return width_fn @@ -1321,7 +1321,7 @@ def _format(val, valtype, floatfmt, intfmt, missingval="", has_invisible=True): tabulate(tbl, headers=hrow) == good_result True - """ # noqa + """ # noqa: E501 if val is None: return missingval if isinstance(val, (bytes, str)) and not val: @@ -2649,7 +2649,7 @@ def _format_table( padded_widths = [(w + 2 * pad) for w in colwidths] if is_multiline: - pad_row = lambda row, _: row # noqa do it later, in _append_multiline_row + pad_row = lambda row, _: row # noqa: E731 # do it later, in _append_multiline_row append_row = partial(_append_multiline_row, pad=pad) else: pad_row = _pad_row diff --git a/test/common.py b/test/common.py index ec2fb351..31d6b82c 100644 --- a/test/common.py +++ b/test/common.py @@ -1,5 +1,5 @@ -import pytest # noqa -from pytest import skip, raises # noqa +import pytest # noqa: F401 +from pytest import skip, raises # noqa: F401 import warnings diff --git a/test/test_internal.py b/test/test_internal.py index 17107c6d..fb2cec8b 100644 --- a/test/test_internal.py +++ b/test/test_internal.py @@ -176,7 +176,7 @@ def test_wrap_text_to_colwidths(): def test_wrap_text_wide_chars(): "Internal: Wrap wide characters based on column width" try: - import wcwidth # noqa + import wcwidth # noqa: F401 except ImportError: skip("test_wrap_text_wide_chars is skipped") @@ -242,7 +242,7 @@ def test_wrap_text_to_colwidths_single_ansi_colors_full_cell(): def test_wrap_text_to_colwidths_colors_wide_char(): """Internal: autowrapped text can retain a ANSI colors with wide chars""" try: - import wcwidth # noqa + import wcwidth # noqa: F401 except ImportError: skip("test_wrap_text_to_colwidths_colors_wide_char is skipped") diff --git a/test/test_output.py b/test/test_output.py index 84a4cc41..8871f220 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -131,7 +131,7 @@ def test_plain_maxcolwidth_autowraps_with_sep(): def test_plain_maxcolwidth_autowraps_wide_chars(): "Output: maxcolwidth and autowrapping functions with wide characters" try: - import wcwidth # noqa + import wcwidth # noqa: F401 except ImportError: skip("test_wrap_text_wide_chars is skipped") @@ -546,7 +546,7 @@ def test_grid(): def test_grid_wide_characters(): "Output: grid with wide characters in headers" try: - import wcwidth # noqa + import wcwidth # noqa: F401 except ImportError: skip("test_grid_wide_characters is skipped") headers = list(_test_table_headers) @@ -681,7 +681,7 @@ def test_simple_grid(): def test_simple_grid_wide_characters(): "Output: simple_grid with wide characters in headers" try: - import wcwidth # noqa + import wcwidth # noqa: F401 except ImportError: skip("test_simple_grid_wide_characters is skipped") headers = list(_test_table_headers) @@ -816,7 +816,7 @@ def test_rounded_grid(): def test_rounded_grid_wide_characters(): "Output: rounded_grid with wide characters in headers" try: - import wcwidth # noqa + import wcwidth # noqa: F401 except ImportError: skip("test_rounded_grid_wide_characters is skipped") headers = list(_test_table_headers) @@ -951,7 +951,7 @@ def test_heavy_grid(): def test_heavy_grid_wide_characters(): "Output: heavy_grid with wide characters in headers" try: - import wcwidth # noqa + import wcwidth # noqa: F401 except ImportError: skip("test_heavy_grid_wide_characters is skipped") headers = list(_test_table_headers) @@ -1086,7 +1086,7 @@ def test_mixed_grid(): def test_mixed_grid_wide_characters(): "Output: mixed_grid with wide characters in headers" try: - import wcwidth # noqa + import wcwidth # noqa: F401 except ImportError: skip("test_mixed_grid_wide_characters is skipped") headers = list(_test_table_headers) @@ -1221,7 +1221,7 @@ def test_double_grid(): def test_double_grid_wide_characters(): "Output: double_grid with wide characters in headers" try: - import wcwidth # noqa + import wcwidth # noqa: F401 except ImportError: skip("test_double_grid_wide_characters is skipped") headers = list(_test_table_headers) @@ -1356,7 +1356,7 @@ def test_fancy_grid(): def test_fancy_grid_wide_characters(): "Output: fancy_grid with wide characters in headers" try: - import wcwidth # noqa + import wcwidth # noqa: F401 except ImportError: skip("test_fancy_grid_wide_characters is skipped") headers = list(_test_table_headers) @@ -1525,7 +1525,7 @@ def test_colon_grid(): def test_colon_grid_wide_characters(): "Output: colon_grid with wide chars in header" try: - import wcwidth # noqa + import wcwidth # noqa: F401 except ImportError: skip("test_colon_grid_wide_characters is skipped") headers = list(_test_table_headers) @@ -1619,7 +1619,7 @@ def test_outline(): def test_outline_wide_characters(): "Output: outline with wide characters in headers" try: - import wcwidth # noqa + import wcwidth # noqa: F401 except ImportError: skip("test_outline_wide_characters is skipped") headers = list(_test_table_headers) @@ -1671,7 +1671,7 @@ def test_simple_outline(): def test_simple_outline_wide_characters(): "Output: simple_outline with wide characters in headers" try: - import wcwidth # noqa + import wcwidth # noqa: F401 except ImportError: skip("test_simple_outline_wide_characters is skipped") headers = list(_test_table_headers) @@ -1723,7 +1723,7 @@ def test_rounded_outline(): def test_rounded_outline_wide_characters(): "Output: rounded_outline with wide characters in headers" try: - import wcwidth # noqa + import wcwidth # noqa: F401 except ImportError: skip("test_rounded_outline_wide_characters is skipped") headers = list(_test_table_headers) @@ -1775,7 +1775,7 @@ def test_heavy_outline(): def test_heavy_outline_wide_characters(): "Output: heavy_outline with wide characters in headers" try: - import wcwidth # noqa + import wcwidth # noqa: F401 except ImportError: skip("test_heavy_outline_wide_characters is skipped") headers = list(_test_table_headers) @@ -1827,7 +1827,7 @@ def test_mixed_outline(): def test_mixed_outline_wide_characters(): "Output: mixed_outline with wide characters in headers" try: - import wcwidth # noqa + import wcwidth # noqa: F401 except ImportError: skip("test_mixed_outline_wide_characters is skipped") headers = list(_test_table_headers) @@ -1879,7 +1879,7 @@ def test_double_outline(): def test_double_outline_wide_characters(): "Output: double_outline with wide characters in headers" try: - import wcwidth # noqa + import wcwidth # noqa: F401 except ImportError: skip("test_double_outline_wide_characters is skipped") headers = list(_test_table_headers) @@ -1931,7 +1931,7 @@ def test_fancy_outline(): def test_fancy_outline_wide_characters(): "Output: fancy_outline with wide characters in headers" try: - import wcwidth # noqa + import wcwidth # noqa: F401 except ImportError: skip("test_fancy_outline_wide_characters is skipped") headers = list(_test_table_headers) diff --git a/test/test_regression.py b/test/test_regression.py index c2e95838..35fa42ae 100644 --- a/test/test_regression.py +++ b/test/test_regression.py @@ -303,7 +303,7 @@ class textclass(str): def test_mix_normal_and_wide_characters(): "Regression: wide characters in a grid format (issue #51)" try: - import wcwidth # noqa + import wcwidth # noqa: F401 ru_text = "\u043f\u0440\u0438\u0432\u0435\u0442" cn_text = "\u4f60\u597d" @@ -325,7 +325,7 @@ def test_mix_normal_and_wide_characters(): def test_multiline_with_wide_characters(): "Regression: multiline tables with varying number of wide characters (github issue #28)" try: - import wcwidth # noqa + import wcwidth # noqa: F401 table = [["가나\n가ab", "가나", "가나"]] result = tabulate(table, tablefmt="fancy_grid") diff --git a/test/test_textwrapper.py b/test/test_textwrapper.py index 485fa30e..5e86b5c9 100644 --- a/test/test_textwrapper.py +++ b/test/test_textwrapper.py @@ -47,7 +47,7 @@ def test_wrap_longword_non_wide(): def test_wrap_wide_char_multiword(): """TextWrapper: wrapping support for wide characters with multiple words""" try: - import wcwidth # noqa + import wcwidth # noqa: F401 except ImportError: skip("test_wrap_wide_char is skipped") @@ -63,7 +63,7 @@ def test_wrap_wide_char_multiword(): def test_wrap_wide_char_longword(): """TextWrapper: wrapping wide char word that needs to be broken up""" try: - import wcwidth # noqa + import wcwidth # noqa: F401 except ImportError: skip("test_wrap_wide_char_longword is skipped") From 1b69704b12b13c70b1fa42f942e84d9c134a5763 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Sat, 13 Sep 2025 15:37:02 +0200 Subject: [PATCH 123/204] Remove spurious cast in string interpolation String interpolation is about converting arguments to strings. Explicitly converting to string is useless and hurts readability. --- test/test_api.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_api.py b/test/test_api.py index 9401a303..e1864426 100644 --- a/test/test_api.py +++ b/test/test_api.py @@ -24,7 +24,7 @@ def _check_signature(function, expected_sig): if not signature: skip("") actual_sig = signature(function) - print(f"expected: {expected_sig}\nactual: {str(actual_sig)}\n") + print(f"expected: {expected_sig}\nactual: {actual_sig}\n") assert len(actual_sig.parameters) == len(expected_sig) From 7bacc90422f416f61034c6aeb45be32dc67bafdf Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Wed, 4 Mar 2026 18:48:58 +0100 Subject: [PATCH 124/204] run pre-commit hooks (black) --- tabulate/__init__.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index db1f18ce..9e2925e3 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1190,7 +1190,9 @@ def _align_column_choose_width_fn(has_invisible, enable_widechars, is_multiline) else: line_width_fn = len if is_multiline: - width_fn = lambda s: _align_column_multiline_width(s, line_width_fn) # noqa: E731 + width_fn = lambda s: _align_column_multiline_width( + s, line_width_fn + ) # noqa: E731 else: width_fn = line_width_fn return width_fn @@ -2649,7 +2651,9 @@ def _format_table( padded_widths = [(w + 2 * pad) for w in colwidths] if is_multiline: - pad_row = lambda row, _: row # noqa: E731 # do it later, in _append_multiline_row + pad_row = ( + lambda row, _: row + ) # noqa: E731 # do it later, in _append_multiline_row append_row = partial(_append_multiline_row, pad=pad) else: pad_row = _pad_row From 37e1ed089f779ed5a962e287b12dc9c15e61c7ff Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Wed, 4 Mar 2026 18:50:29 +0100 Subject: [PATCH 125/204] move # nowa: E931 to a different line (flake8) --- tabulate/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 9e2925e3..bc953410 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1190,9 +1190,9 @@ def _align_column_choose_width_fn(has_invisible, enable_widechars, is_multiline) else: line_width_fn = len if is_multiline: - width_fn = lambda s: _align_column_multiline_width( + width_fn = lambda s: _align_column_multiline_width( # noqa: E731 s, line_width_fn - ) # noqa: E731 + ) else: width_fn = line_width_fn return width_fn From 37ac76e9365fa3694e92c8ab651a2cc694438983 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Wed, 4 Mar 2026 19:01:39 +0100 Subject: [PATCH 126/204] restore tabulate.__version__ --- tabulate/__init__.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index bc953410..fb157f43 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1,5 +1,15 @@ """Pretty-print tabular data.""" +from importlib.metadata import ( + version as _version, + PackageNotFoundError as _PackageNotFoundError, +) + +try: + __version__ = _version("tabulate") +except _PackageNotFoundError: + __version__ = "unknown" + import warnings from collections import namedtuple from collections.abc import Iterable, Sized From 35ee0f61544b53067247cfe8fd8b7547b7e1c1e2 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Wed, 4 Mar 2026 19:03:40 +0100 Subject: [PATCH 127/204] update mini-benchmark table --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 4f4ed5c5..4772c5b2 100644 --- a/README.md +++ b/README.md @@ -1172,17 +1172,17 @@ simply joining lists of values with a tab, comma, or other separator. At the same time, `tabulate` is comparable to other table pretty-printers. Given a 10x10 table (a list of lists) of mixed text and numeric data, `tabulate` appears to be faster than `PrettyTable` and `texttable`. -The following mini-benchmark was run in Python 3.11.9 on Windows 11 (x64): +The following mini-benchmark was run in Python 3.13.7 on Windows 11 (x64): ================================== ========== =========== Table formatter time, μs rel. time ================================== ========== =========== - join with tabs and newlines 6.3 1.0 - csv to StringIO 6.6 1.0 - tabulate (0.10.0) 249.2 39.3 - tabulate (0.10.0, WIDE_CHARS_MODE) 325.6 51.4 - texttable (1.7.0) 579.3 91.5 - PrettyTable (3.11.0) 605.5 95.6 + csv to StringIO 11.9 1.0 + join with tabs and newlines 12.1 1.0 + PrettyTable (3.17.0) 468.0 39.3 + tabulate (0.10.0) 553.4 46.5 + tabulate (0.10.0, WIDE_CHARS_MODE) 612.2 51.4 + texttable (1.7.0) 1071.4 90.0 ================================== ========== =========== From 3b4cd509820e4c45cd2aaba833aa585ea6308b94 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Wed, 4 Mar 2026 19:10:09 +0100 Subject: [PATCH 128/204] update HOWTOPUBLISH --- HOWTOPUBLISH | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/HOWTOPUBLISH b/HOWTOPUBLISH index 5a072d10..880ab19c 100644 --- a/HOWTOPUBLISH +++ b/HOWTOPUBLISH @@ -1,7 +1,8 @@ # update contributors and CHANGELOG in README python -m pre_commit run -a # and then commit changes tox -e py310-extra,py311-extra,py312-extra,py313-extra,py314-extra -# tag version release +# tag version release (vX.Y.Z) +python -m pip install build twine python -m build -s # this will update tabulate/version.py python -m pip install . # install tabulate in the current venv python -m pip install -r benchmark/requirements.txt @@ -13,3 +14,4 @@ git push # wait for all CI builds to succeed git push --tags # if CI builds succeed twine upload --repository-url https://test.pypi.org/legacy/ dist/* twine upload dist/* +# use __token__ as username andPyPI API token as password (generate at pypi.org → Account settings → API tokens) \ No newline at end of file From 36c8b07515a67231785c23c6a952e03195c3e986 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Wed, 4 Mar 2026 22:20:06 +0100 Subject: [PATCH 129/204] add ruff, build, twine, tox as dev dependencies --- pyproject.toml | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index b602919e..cbb680f7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -32,7 +32,12 @@ widechars = ["wcwidth"] [project.scripts] tabulate = "tabulate:_main" -# [tool.setuptools] -# packages = ["tabulate"] - [tool.setuptools_scm] + +[dependency-groups] +dev = [ + "build>=1.4.0", + "ruff>=0.15.4", + "tox>=4.47.3", + "twine>=6.2.0", +] From 75640e2b5c362016860521840b01caac18b510f6 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Wed, 4 Mar 2026 22:28:54 +0100 Subject: [PATCH 130/204] use ruff instead of black and flake8 fix #396 --- .pre-commit-config.yaml | 15 +++++---------- pyproject.toml | 10 ++++++++++ tox.ini | 10 ++++------ 3 files changed, 19 insertions(+), 16 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 28c2f8c8..e9808666 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,10 +1,10 @@ repos: -- repo: https://github.com/python/black - rev: 25.1.0 +- repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.15.4 hooks: - - id: black - args: [--safe] - language_version: python3 + - id: ruff + args: [--fix] + - id: ruff-format - repo: https://github.com/pre-commit/pre-commit-hooks rev: v6.0.0 hooks: @@ -12,8 +12,3 @@ repos: - id: check-yaml - id: debug-statements language_version: python3 -- repo: https://github.com/pycqa/flake8 - rev: 7.3.0 - hooks: - - id: flake8 - language_version: python3 \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml index cbb680f7..2ae0586c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -41,3 +41,13 @@ dev = [ "tox>=4.47.3", "twine>=6.2.0", ] + +[tool.ruff] +line-length = 99 + +[tool.ruff.lint] +select = ["E", "F", "W", "C90"] +ignore = ["E203", "E402", "E721", "C901"] + +[tool.ruff.lint.mccabe] +max-complexity = 22 diff --git a/tox.ini b/tox.ini index 77b5f2e7..3baea31a 100644 --- a/tox.ini +++ b/tox.ini @@ -29,9 +29,11 @@ passenv = SSL_CERT_FILE [testenv:lint] -commands = python -m pre_commit run -a +commands = + ruff check . + ruff format --check . deps = - pre-commit + ruff [testenv:py38] basepython = python3.8 @@ -146,7 +148,3 @@ deps = pandas wcwidth -[flake8] -max-complexity = 22 -max-line-length = 99 -ignore = E203, W503, C901, E402, B011 From 4a95974490cde56f81f97aa85dc94958ef309c60 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Wed, 4 Mar 2026 23:00:29 +0100 Subject: [PATCH 131/204] check and format everything with ruff fix #396 --- benchmark/benchmark.py | 8 +-- tabulate/__init__.py | 131 +++++++++------------------------------ test/test_api.py | 6 +- test/test_cli.py | 4 +- test/test_input.py | 56 +++++------------ test/test_internal.py | 4 +- test/test_output.py | 82 +++++++----------------- test/test_regression.py | 8 +-- test/test_textwrapper.py | 10 ++- 9 files changed, 79 insertions(+), 230 deletions(-) diff --git a/benchmark/benchmark.py b/benchmark/benchmark.py index a89b709e..03dfa66c 100644 --- a/benchmark/benchmark.py +++ b/benchmark/benchmark.py @@ -72,13 +72,9 @@ def benchmark(n): if "--onlyself" in sys.argv[1:]: methods = [m for m in methods if m[0].startswith("tabulate")] - results = [ - (desc, timeit(code, setup_code, number=n) / n * 1e6) for desc, code in methods - ] + results = [(desc, timeit(code, setup_code, number=n) / n * 1e6) for desc, code in methods] mintime = min(map(lambda x: x[1], results)) - results = [ - (desc, t, t / mintime) for desc, t in sorted(results, key=lambda x: x[1]) - ] + results = [(desc, t, t / mintime) for desc, t in sorted(results, key=lambda x: x[1])] table = tabulate.tabulate( results, ["Table formatter", "time, μs", "rel. time"], "rst", floatfmt=".1f" ) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index fb157f43..8a4b41ce 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -152,9 +152,7 @@ def _pipe_line_with_colons(colwidths, colaligns): alignment (as in `pipe` output format).""" if not colaligns: # e.g. printing an empty data frame (github issue #15) colaligns = [""] * len(colwidths) - segments = "|".join( - _pipe_segment_with_colons(a, w) for a, w in zip(colaligns, colwidths) - ) + segments = "|".join(_pipe_segment_with_colons(a, w) for a, w in zip(colaligns, colwidths)) return f"|{segments}|" @@ -177,9 +175,7 @@ def _grid_line_with_colons(colwidths, colaligns): in a grid table.""" if not colaligns: colaligns = [""] * len(colwidths) - segments = "+".join( - _grid_segment_with_colons(w, a) for a, w in zip(colaligns, colwidths) - ) + segments = "+".join(_grid_segment_with_colons(w, a) for a, w in zip(colaligns, colwidths)) return f"+{segments}+" @@ -269,12 +265,8 @@ def make_header_line(is_header, colwidths, colaligns): alignment = {"left": "<", "right": ">", "center": "^", "decimal": ">"} # use the column widths generated by tabulate for the asciidoc column width specifiers - asciidoc_alignments = zip( - colwidths, [alignment[colalign] for colalign in colaligns] - ) - asciidoc_column_specifiers = [ - f"{align}{width:d}" for width, align in asciidoc_alignments - ] + asciidoc_alignments = zip(colwidths, [alignment[colalign] for colalign in colaligns]) + asciidoc_column_specifiers = [f"{align}{width:d}" for width, align in asciidoc_alignments] header_list = ['cols="' + (",".join(asciidoc_column_specifiers)) + '"'] # generate the list of options (currently only "header") @@ -1236,9 +1228,7 @@ def _align_column( strings, padfn = _align_column_choose_padfn( strings, alignment, has_invisible, preserve_whitespace ) - width_fn = _align_column_choose_width_fn( - has_invisible, enable_widechars, is_multiline - ) + width_fn = _align_column_choose_width_fn(has_invisible, enable_widechars, is_multiline) s_widths = list(map(width_fn, strings)) maxwidth = max(max(_flat_list(s_widths)), minwidth) @@ -1246,15 +1236,13 @@ def _align_column( if is_multiline: if not enable_widechars and not has_invisible: padded_strings = [ - "\n".join([padfn(maxwidth, s) for s in ms.splitlines()]) - for ms in strings + "\n".join([padfn(maxwidth, s) for s in ms.splitlines()]) for ms in strings ] else: # enable wide-character width corrections s_lens = [[len(s) for s in re.split("[\r\n]", ms)] for ms in strings] visible_widths = [ - [maxwidth - (w - l) for w, l in zip(mw, ml)] - for mw, ml in zip(s_widths, s_lens) + [maxwidth - (w - ln) for w, ln in zip(mw, ml)] for mw, ml in zip(s_widths, s_lens) ] # wcswidth and _visible_width don't count invisible characters; # padfn doesn't need to apply another correction @@ -1268,7 +1256,7 @@ def _align_column( else: # enable wide-character width corrections s_lens = list(map(len, strings)) - visible_widths = [maxwidth - (w - l) for w, l in zip(s_widths, s_lens)] + visible_widths = [maxwidth - (w - ln) for w, ln in zip(s_widths, s_lens)] # wcswidth and _visible_width don't count invisible characters; # padfn doesn't need to apply another correction padded_strings = [padfn(w, s) for s, w in zip(strings, visible_widths)] @@ -1344,19 +1332,13 @@ def _format(val, valtype, floatfmt, intfmt, missingval="", has_invisible=True): elif valtype is int: if isinstance(val, str): val_striped = val.encode("unicode_escape").decode("utf-8") - colored = re.search( - r"(\\[xX]+[0-9a-fA-F]+\[\d+[mM]+)([0-9.]+)(\\.*)$", val_striped - ) + colored = re.search(r"(\\[xX]+[0-9a-fA-F]+\[\d+[mM]+)([0-9.]+)(\\.*)$", val_striped) if colored: total_groups = len(colored.groups()) if total_groups == 3: digits = colored.group(2) if digits.isdigit(): - val_new = ( - colored.group(1) - + format(int(digits), intfmt) - + colored.group(3) - ) + val_new = colored.group(1) + format(int(digits), intfmt) + colored.group(3) val = val_new.encode("utf-8").decode("unicode_escape") intfmt = "" return format(val, intfmt) @@ -1385,15 +1367,11 @@ def _format(val, valtype, floatfmt, intfmt, missingval="", has_invisible=True): return f"{val}" -def _align_header( - header, alignment, width, visible_width, is_multiline=False, width_fn=None -): +def _align_header(header, alignment, width, visible_width, is_multiline=False, width_fn=None): "Pad string header to width chars given known visible_width of the header." if is_multiline: header_lines = re.split(_multiline_codes, header) - padded_lines = [ - _align_header(h, alignment, width, width_fn(h)) for h in header_lines - ] + padded_lines = [_align_header(h, alignment, width, width_fn(h)) for h in header_lines] return "\n".join(padded_lines) # else: not multiline ninvisible = len(header) - visible_width @@ -1507,19 +1485,14 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"): # likely a conventional dict keys = tabular_data.keys() try: - rows = list( - izip_longest(*tabular_data.values()) - ) # columns have to be transposed + rows = list(izip_longest(*tabular_data.values())) # columns have to be transposed except TypeError: # not iterable raise TypeError(err_msg) elif hasattr(tabular_data, "index"): # values is a property, has .index => it's likely a pandas.DataFrame (pandas 0.11.0) keys = list(tabular_data) - if ( - showindex in ["default", "always", True] - and tabular_data.index.name is not None - ): + if showindex in ["default", "always", True] and tabular_data.index.name is not None: if isinstance(tabular_data.index.name, list): keys[:0] = tabular_data.index.name else: @@ -1543,11 +1516,7 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"): if headers == "keys" and not rows: # an empty table (issue #81) headers = [] - elif ( - headers == "keys" - and hasattr(tabular_data, "dtype") - and tabular_data.dtype.names - ): + elif headers == "keys" and hasattr(tabular_data, "dtype") and tabular_data.dtype.names: # numpy record array headers = tabular_data.dtype.names elif ( @@ -1586,9 +1555,7 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"): else: headers = [] elif headers: - raise ValueError( - "headers for a list of dicts is not a dict or a keyword" - ) + raise ValueError("headers for a list of dicts is not a dict or a keyword") rows = [[row.get(k) for k in keys] for row in rows] elif ( @@ -1601,21 +1568,13 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"): # print tabulate(cursor, headers='keys') headers = [column[0] for column in tabular_data.description] - elif ( - dataclasses is not None - and len(rows) > 0 - and dataclasses.is_dataclass(rows[0]) - ): + elif dataclasses is not None and len(rows) > 0 and dataclasses.is_dataclass(rows[0]): # Python's dataclass field_names = [field.name for field in dataclasses.fields(rows[0])] if headers == "keys": headers = field_names rows = [ - ( - [getattr(row, f) for f in field_names] - if not _is_separating_line(row) - else row - ) + ([getattr(row, f) for f in field_names] if not _is_separating_line(row) else row) for row in rows ] @@ -2317,9 +2276,7 @@ def tabulate( if maxheadercolwidths is not None: num_cols = len(list_of_lists[0]) if list_of_lists else len(headers) if isinstance(maxheadercolwidths, int): # Expand scalar for all columns - maxheadercolwidths = _expand_iterable( - maxheadercolwidths, num_cols, maxheadercolwidths - ) + maxheadercolwidths = _expand_iterable(maxheadercolwidths, num_cols, maxheadercolwidths) else: # Ignore col width for any 'trailing' columns maxheadercolwidths = _expand_iterable(maxheadercolwidths, num_cols, None) @@ -2393,17 +2350,13 @@ def tabulate( numparses = _expand_numparse(disable_numparse, len(cols)) coltypes = [_column_type(col, numparse=np) for col, np in zip(cols, numparses)] if isinstance(floatfmt, str): # old version - float_formats = len(cols) * [ - floatfmt - ] # just duplicate the string to use in each column + float_formats = len(cols) * [floatfmt] # just duplicate the string to use in each column else: # if floatfmt is list, tuple etc we have one per column float_formats = list(floatfmt) if len(float_formats) < len(cols): float_formats.extend((len(cols) - len(float_formats)) * [_DEFAULT_FLOATFMT]) if isinstance(intfmt, str): # old version - int_formats = len(cols) * [ - intfmt - ] # just duplicate the string to use in each column + int_formats = len(cols) * [intfmt] # just duplicate the string to use in each column else: # if intfmt is list, tuple etc we have one per column int_formats = list(intfmt) if len(int_formats) < len(cols): @@ -2441,9 +2394,7 @@ def tabulate( break elif align != "global": aligns[idx] = align - minwidths = ( - [width_fn(h) + min_padding for h in headers] if headers else [0] * len(cols) - ) + minwidths = [width_fn(h) + min_padding for h in headers] if headers else [0] * len(cols) aligns_copy = aligns.copy() # Reset alignments in copy of alignments list to "left" for 'colon_grid' format, # which enforces left alignment in the text output of the data. @@ -2490,8 +2441,7 @@ def tabulate( elif align != "global": aligns_headers[hidx] = align minwidths = [ - max(minw, max(width_fn(cl) for cl in c)) - for minw, c in zip(minwidths, t_cols) + max(minw, max(width_fn(cl) for cl in c)) for minw, c in zip(minwidths, t_cols) ] headers = [ _align_header(h, a, minw, width_fn(h), is_multiline, width_fn) @@ -2610,8 +2560,7 @@ def _append_multiline_row( # ] cells_lines = [ - _align_cell_veritically(cl, nlines, w, rowalign) - for cl, w in zip(cells_lines, colwidths) + _align_cell_veritically(cl, nlines, w, rowalign) for cl, w in zip(cells_lines, colwidths) ] lines_cells = [[cl[i] for cl in cells_lines] for i in range(nlines)] for ln in lines_cells: @@ -2661,9 +2610,7 @@ def _format_table( padded_widths = [(w + 2 * pad) for w in colwidths] if is_multiline: - pad_row = ( - lambda row, _: row - ) # noqa: E731 # do it later, in _append_multiline_row + pad_row = lambda row, _: row # noqa: E731 # do it later, in _append_multiline_row append_row = partial(_append_multiline_row, pad=pad) else: pad_row = _pad_row @@ -2715,9 +2662,7 @@ def _format_table( if _is_separating_line(row): _append_line(lines, padded_widths, colaligns, separating_line) else: - append_row( - lines, pad_row(row, pad), padded_widths, colaligns, fmt.datarow - ) + append_row(lines, pad_row(row, pad), padded_widths, colaligns, fmt.datarow) if fmt.linebelow and "linebelow" not in hidden: _append_line(lines, padded_widths, colaligns, fmt.linebelow) @@ -2762,9 +2707,7 @@ def _update_lines(self, lines, new_line): as a single unwrapped string. """ code_matches = [x for x in _ansi_codes.finditer(new_line)] - color_codes = [ - code.string[code.span()[0] : code.span()[1]] for code in code_matches - ] + color_codes = [code.string[code.span()[0] : code.span()[1]] for code in code_matches] # Add color codes from earlier in the unwrapped line, and then track any new ones we add. new_line = "".join(self._active_codes) + new_line @@ -2805,9 +2748,7 @@ def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width): i = 1 # Only count printable characters, so strip_ansi first, index later. stripped_chunk = _strip_ansi(chunk) - while ( - i <= len(stripped_chunk) and self._len(stripped_chunk[:i]) <= space_left - ): + while i <= len(stripped_chunk) and self._len(stripped_chunk[:i]) <= space_left: i = i + 1 # Consider escape codes when breaking words up total_escape_len = 0 @@ -2815,10 +2756,7 @@ def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width): if _ansi_codes.search(chunk) is not None: for group, _, _, _ in _ansi_codes.findall(chunk): escape_len = len(group) - if ( - group - in chunk[last_group : i + total_escape_len + escape_len - 1] - ): + if group in chunk[last_group : i + total_escape_len + escape_len - 1]: total_escape_len += escape_len found = _ansi_codes.search(chunk[last_group:]) last_group += found.end() @@ -2865,7 +2803,6 @@ def _wrap_chunks(self, chunks): chunks.reverse() while chunks: - # Start the list of chunks that will make up the current line. # cur_len is just the length of all the chunks in cur_line. cur_line = [] @@ -2925,10 +2862,7 @@ def _wrap_chunks(self, chunks): self._update_lines(lines, indent + "".join(cur_line)) else: while cur_line: - if ( - cur_line[-1].strip() - and cur_len + self._len(self.placeholder) <= width - ): + if cur_line[-1].strip() and cur_len + self._len(self.placeholder) <= width: cur_line.append(self.placeholder) self._update_lines(lines, indent + "".join(cur_line)) break @@ -2937,10 +2871,7 @@ def _wrap_chunks(self, chunks): else: if lines: prev_line = lines[-1].rstrip() - if ( - self._len(prev_line) + self._len(self.placeholder) - <= self.width - ): + if self._len(prev_line) + self._len(self.placeholder) <= self.width: lines[-1] = prev_line + self.placeholder break self._update_lines(lines, indent + self.placeholder.lstrip()) diff --git a/test/test_api.py b/test/test_api.py index e1864426..20493ec0 100644 --- a/test/test_api.py +++ b/test/test_api.py @@ -12,7 +12,7 @@ def test_tabulate_formats(): - "API: tabulate_formats is a list of strings" "" + "API: tabulate_formats is a list of strings" supported = tabulate_formats print("tabulate_formats = %r" % supported) assert type(supported) is list @@ -33,7 +33,7 @@ def _check_signature(function, expected_sig): def test_tabulate_signature(): - "API: tabulate() type signature is unchanged" "" + "API: tabulate() type signature is unchanged" assert type(tabulate) is type(lambda: None) # noqa expected_sig = [ ("tabular_data", _empty), @@ -61,7 +61,7 @@ def test_tabulate_signature(): def test_simple_separated_format_signature(): - "API: simple_separated_format() type signature is unchanged" "" + "API: simple_separated_format() type signature is unchanged" assert type(simple_separated_format) is type(lambda: None) # noqa expected_sig = [("separator", _empty)] _check_signature(simple_separated_format, expected_sig) diff --git a/test/test_cli.py b/test/test_cli.py index 573c99e7..2f7faa81 100644 --- a/test/test_cli.py +++ b/test/test_cli.py @@ -97,9 +97,7 @@ def __init__(self): self.tmpfile = None def __enter__(self): - self.tmpfile = tempfile.NamedTemporaryFile( - "w+", prefix="tabulate-test-tmp-", delete=False - ) + self.tmpfile = tempfile.NamedTemporaryFile("w+", prefix="tabulate-test-tmp-", delete=False) return self.tmpfile def __exit__(self, exc_type, exc_val, exc_tb): diff --git a/test/test_input.py b/test/test_input.py index 073dead2..fca67506 100644 --- a/test/test_input.py +++ b/test/test_input.py @@ -13,9 +13,7 @@ def test_iterable_of_iterables(): "Input: an iterable of iterables." ii = iter(map(lambda x: iter(x), [range(5), range(5, 0, -1)])) - expected = "\n".join( - ["- - - - -", "0 1 2 3 4", "5 4 3 2 1", "- - - - -"] - ) + expected = "\n".join(["- - - - -", "0 1 2 3 4", "5 4 3 2 1", "- - - - -"]) result = tabulate(ii) assert_equal(expected, result) @@ -83,9 +81,7 @@ def test_list_of_lists_firstrow(): def test_list_of_lists_keys(): "Input: a list of lists with column indices as headers." ll = [["a", "one", 1], ["b", "two", None]] - expected = "\n".join( - ["0 1 2", "--- --- ---", "a one 1", "b two"] - ) + expected = "\n".join(["0 1 2", "--- --- ---", "a one 1", "b two"]) result = tabulate(ll, headers="keys") assert_equal(expected, result) @@ -96,12 +92,8 @@ def test_dict_like(): dd = {"a": range(3), "b": range(101, 105)} # keys' order (hence columns' order) is not deterministic in Python 3 # => we have to consider both possible results as valid - expected1 = "\n".join( - [" a b", "--- ---", " 0 101", " 1 102", " 2 103", " 104"] - ) - expected2 = "\n".join( - [" b a", "--- ---", "101 0", "102 1", "103 2", "104"] - ) + expected1 = "\n".join([" a b", "--- ---", " 0 101", " 1 102", " 2 103", " 104"]) + expected2 = "\n".join([" b a", "--- ---", "101 0", "102 1", "103 2", "104"]) result = tabulate(dd, "keys") print("Keys' order: %s" % dd.keys()) assert_in(result, [expected1, expected2]) @@ -270,9 +262,7 @@ def test_pandas_firstrow(): df = pandas.DataFrame( [["one", 1], ["two", None]], columns=["string", "number"], index=["a", "b"] ) - expected = "\n".join( - ["a one 1.0", "--- ----- -----", "b two nan"] - ) + expected = "\n".join(["a one 1.0", "--- ----- -----", "b two nan"]) result = tabulate(df, headers="firstrow") assert_equal(expected, result) except ImportError: @@ -366,9 +356,7 @@ def test_list_of_namedtuples_keys(): NT = namedtuple("NT", ["foo", "bar"]) lt = [NT(1, 2), NT(3, 4)] - expected = "\n".join( - [" foo bar", "----- -----", " 1 2", " 3 4"] - ) + expected = "\n".join([" foo bar", "----- -----", " 1 2", " 3 4"]) result = tabulate(lt, headers="keys") assert_equal(expected, result) @@ -394,12 +382,8 @@ def test_list_of_userdicts(): def test_list_of_dicts_keys(): "Input: a list of dictionaries, with keys as headers." lod = [{"foo": 1, "bar": 2}, {"foo": 3, "bar": 4}] - expected1 = "\n".join( - [" foo bar", "----- -----", " 1 2", " 3 4"] - ) - expected2 = "\n".join( - [" bar foo", "----- -----", " 2 1", " 4 3"] - ) + expected1 = "\n".join([" foo bar", "----- -----", " 1 2", " 3 4"]) + expected2 = "\n".join([" bar foo", "----- -----", " 2 1", " 4 3"]) result = tabulate(lod, headers="keys") assert_in(result, [expected1, expected2]) @@ -407,12 +391,8 @@ def test_list_of_dicts_keys(): def test_list_of_userdicts_keys(): "Input: a list of UserDicts." lod = [UserDict(foo=1, bar=2), UserDict(foo=3, bar=4)] - expected1 = "\n".join( - [" foo bar", "----- -----", " 1 2", " 3 4"] - ) - expected2 = "\n".join( - [" bar foo", "----- -----", " 2 1", " 4 3"] - ) + expected1 = "\n".join([" foo bar", "----- -----", " 1 2", " 3 4"]) + expected2 = "\n".join([" bar foo", "----- -----", " 2 1", " 4 3"]) result = tabulate(lod, headers="keys") assert_in(result, [expected1, expected2]) @@ -437,12 +417,8 @@ def test_list_of_dicts_firstrow(): "Input: a list of dictionaries, with the first dict as headers." lod = [{"foo": "FOO", "bar": "BAR"}, {"foo": 3, "bar": 4, "baz": 5}] # if some key is missing in the first dict, use the key name instead - expected1 = "\n".join( - [" FOO BAR baz", "----- ----- -----", " 3 4 5"] - ) - expected2 = "\n".join( - [" BAR FOO baz", "----- ----- -----", " 4 3 5"] - ) + expected1 = "\n".join([" FOO BAR baz", "----- ----- -----", " 3 4 5"]) + expected2 = "\n".join([" BAR FOO baz", "----- ----- -----", " 4 3 5"]) result = tabulate(lod, headers="firstrow") assert_in(result, [expected1, expected2]) @@ -451,12 +427,8 @@ def test_list_of_dicts_with_dict_of_headers(): "Input: a dict of user headers for a list of dicts (issue #23)" table = [{"letters": "ABCDE", "digits": 12345}] headers = {"digits": "DIGITS", "letters": "LETTERS"} - expected1 = "\n".join( - [" DIGITS LETTERS", "-------- ---------", " 12345 ABCDE"] - ) - expected2 = "\n".join( - ["LETTERS DIGITS", "--------- --------", "ABCDE 12345"] - ) + expected1 = "\n".join([" DIGITS LETTERS", "-------- ---------", " 12345 ABCDE"]) + expected2 = "\n".join(["LETTERS DIGITS", "--------- --------", "ABCDE 12345"]) result = tabulate(table, headers=headers) assert_in(result, [expected1, expected2]) diff --git a/test/test_internal.py b/test/test_internal.py index fb2cec8b..5d521d04 100644 --- a/test/test_internal.py +++ b/test/test_internal.py @@ -180,9 +180,7 @@ def test_wrap_text_wide_chars(): except ImportError: skip("test_wrap_text_wide_chars is skipped") - rows = [ - ["청자청자청자청자청자", "약간 감싸면 더 잘 보일 수있는 다소 긴 설명입니다"] - ] + rows = [["청자청자청자청자청자", "약간 감싸면 더 잘 보일 수있는 다소 긴 설명입니다"]] widths = [5, 20] expected = [ [ diff --git a/test/test_output.py b/test/test_output.py index 8871f220..68a7905e 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -16,9 +16,7 @@ def test_plain(): "Output: plain with headers" - expected = "\n".join( - ["strings numbers", "spam 41.9999", "eggs 451"] - ) + expected = "\n".join(["strings numbers", "spam 41.9999", "eggs 451"]) result = tabulate(_test_table, _test_table_headers, tablefmt="plain") assert_equal(expected, result) @@ -94,9 +92,7 @@ def test_plain_multiline_with_empty_cells(): def test_plain_multiline_with_empty_cells_headerless(): "Output: plain with multiline cells and empty cells without headers" table = [["0", "", ""], ["1", "", ""], ["2", "very long data", "fold\nthis"]] - expected = "\n".join( - ["0", "1", "2 very long data fold", " this"] - ) + expected = "\n".join(["0", "1", "2 very long data fold", " this"]) result = tabulate(table, tablefmt="plain") assert_equal(expected, result) @@ -105,9 +101,7 @@ def test_plain_maxcolwidth_autowraps(): "Output: maxcolwidth will result in autowrapping longer cells" table = [["hdr", "fold"], ["1", "very long data"]] expected = "\n".join([" hdr fold", " 1 very long", " data"]) - result = tabulate( - table, headers="firstrow", tablefmt="plain", maxcolwidths=[10, 10] - ) + result = tabulate(table, headers="firstrow", tablefmt="plain", maxcolwidths=[10, 10]) assert_equal(expected, result) @@ -122,9 +116,7 @@ def test_plain_maxcolwidth_autowraps_with_sep(): expected = "\n".join( [" hdr fold", " 1 very long", " data", "", " 2 last line"] ) - result = tabulate( - table, headers="firstrow", tablefmt="plain", maxcolwidths=[10, 10] - ) + result = tabulate(table, headers="firstrow", tablefmt="plain", maxcolwidths=[10, 10]) assert_equal(expected, result) @@ -139,7 +131,7 @@ def test_plain_maxcolwidth_autowraps_wide_chars(): ["hdr", "fold"], [ "1", - "약간 감싸면 더 잘 보일 수있는 다소 긴 설명입니다 설명입니다 설명입니다 설명입니다 설명", + "약간 감싸면 더 잘 보일 수있는 다소 긴 설명입니다 설명입니다 설명입니다 설명입니다 설명", # noqa: E501 ], ] expected = "\n".join( @@ -150,9 +142,7 @@ def test_plain_maxcolwidth_autowraps_wide_chars(): " 설명입니다 설명입니다 설명", ] ) - result = tabulate( - table, headers="firstrow", tablefmt="plain", maxcolwidths=[10, 30] - ) + result = tabulate(table, headers="firstrow", tablefmt="plain", maxcolwidths=[10, 30]) assert_equal(expected, result) @@ -189,9 +179,7 @@ def test_maxcolwidth_pad_tailing_widths(): " short", ] ) - result = tabulate( - table, headers="firstrow", tablefmt="plain", maxcolwidths=[None, 6] - ) + result = tabulate(table, headers="firstrow", tablefmt="plain", maxcolwidths=[None, 6]) assert_equal(expected, result) @@ -354,9 +342,7 @@ def test_orgtbl_multiline_2_with_sep_line(): def test_simple_headerless(): "Output: simple without headers" - expected = "\n".join( - ["---- --------", "spam 41.9999", "eggs 451", "---- --------"] - ) + expected = "\n".join(["---- --------", "spam 41.9999", "eggs 451", "---- --------"]) result = tabulate(_test_table, tablefmt="simple") assert_equal(expected, result) @@ -1541,9 +1527,7 @@ def test_colon_grid_wide_characters(): "+-----------+---------+", ] ) - result = tabulate( - _test_table, headers, tablefmt="colon_grid", colalign=["left", "right"] - ) + result = tabulate(_test_table, headers, tablefmt="colon_grid", colalign=["left", "right"]) assert_equal(expected, result) @@ -1980,9 +1964,7 @@ def test_pipe(): def test_pipe_headerless(): "Output: pipe without headers" - expected = "\n".join( - ["|:-----|---------:|", "| spam | 41.9999 |", "| eggs | 451 |"] - ) + expected = "\n".join(["|:-----|---------:|", "| spam | 41.9999 |", "| eggs | 451 |"]) result = tabulate(_test_table, tablefmt="pipe") assert_equal(expected, result) @@ -2417,9 +2399,7 @@ def test_rst_with_empty_values_in_first_column(): def test_rst_headerless(): "Output: rst without headers" - expected = "\n".join( - ["==== ========", "spam 41.9999", "eggs 451", "==== ========"] - ) + expected = "\n".join(["==== ========", "spam 41.9999", "eggs 451", "==== ========"]) result = tabulate(_test_table, tablefmt="rst") assert_equal(expected, result) @@ -2834,9 +2814,7 @@ def test_intfmt_with_string_as_integer(): @mark.skip(reason="It detects all values as floats but there are strings and integers.") def test_intfmt_with_string_with_floats(): "Output: integer format" - result = tabulate( - [[82000.38], ["1500.47"], ["2463"], [92165]], intfmt=",", tablefmt="plain" - ) + result = tabulate([[82000.38], ["1500.47"], ["2463"], [92165]], intfmt=",", tablefmt="plain") expected = "82000.4\n 1500.47\n 2463\n92,165" assert_equal(expected, result) @@ -2880,27 +2858,21 @@ def test_floatfmt(): def test_floatfmt_thousands(): "Output: floating point format" - result = tabulate( - [["1.23456789"], [1.0], ["1,234.56"]], floatfmt=".3f", tablefmt="plain" - ) + result = tabulate([["1.23456789"], [1.0], ["1,234.56"]], floatfmt=".3f", tablefmt="plain") expected = " 1.235\n 1.000\n1234.560" assert_equal(expected, result) def test_floatfmt_multi(): "Output: floating point format different for each column" - result = tabulate( - [[0.12345, 0.12345, 0.12345]], floatfmt=(".1f", ".3f"), tablefmt="plain" - ) + result = tabulate([[0.12345, 0.12345, 0.12345]], floatfmt=(".1f", ".3f"), tablefmt="plain") expected = "0.1 0.123 0.12345" assert_equal(expected, result) def test_colalign_multi(): "Output: string columns with custom colalign" - result = tabulate( - [["one", "two"], ["three", "four"]], colalign=("right",), tablefmt="plain" - ) + result = tabulate([["one", "two"], ["three", "four"]], colalign=("right",), tablefmt="plain") expected = " one two\nthree four" assert_equal(expected, result) @@ -2966,9 +2938,7 @@ def test_colalign_or_headersalign_too_long(): colalign = ("global", "left", "center") headers = ["h"] headersalign = ("center", "right", "same") - result = tabulate( - table, headers=headers, colalign=colalign, headersalign=headersalign - ) + result = tabulate(table, headers=headers, colalign=colalign, headersalign=headersalign) expected = "\n".join([" h", "--- ---", " 1 2", "111 222"]) assert_equal(expected, result) @@ -2977,9 +2947,7 @@ 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" - ) + check_warnings((tabulate, [table], opt), num=2, category=UserWarning, contain="As a string") def test_float_conversions(): @@ -3009,9 +2977,7 @@ def test_float_conversions(): def test_missingval(): "Output: substitution of missing values" - result = tabulate( - [["Alice", 10], ["Bob", None]], missingval="n/a", tablefmt="plain" - ) + result = tabulate([["Alice", 10], ["Bob", None]], missingval="n/a", tablefmt="plain") expected = "Alice 10\nBob n/a" assert_equal(expected, result) @@ -3291,15 +3257,11 @@ def test_disable_numparse_list(): "Output: Default table output, but with number parsing selectively disabled" table_headers = ["h1", "h2", "h3"] test_table = [["foo", "bar", "42992e1"]] - expected = "\n".join( - ["h1 h2 h3", "---- ---- -------", "foo bar 42992e1"] - ) + expected = "\n".join(["h1 h2 h3", "---- ---- -------", "foo bar 42992e1"]) result = tabulate(test_table, table_headers, disable_numparse=[2]) assert_equal(expected, result) - expected = "\n".join( - ["h1 h2 h3", "---- ---- ------", "foo bar 429920"] - ) + expected = "\n".join(["h1 h2 h3", "---- ---- ------", "foo bar 429920"]) result = tabulate(test_table, table_headers, disable_numparse=[0, 1]) assert_equal(expected, result) @@ -3308,9 +3270,7 @@ def test_preserve_whitespace(): "Output: Default table output, but with preserved leading whitespace." table_headers = ["h1", "h2", "h3"] test_table = [[" foo", " bar ", "foo"]] - expected = "\n".join( - ["h1 h2 h3", "----- ------- ----", " foo bar foo"] - ) + expected = "\n".join(["h1 h2 h3", "----- ------- ----", " foo bar foo"]) result = tabulate(test_table, table_headers, preserve_whitespace=True) assert_equal(expected, result) diff --git a/test/test_regression.py b/test/test_regression.py index 35fa42ae..5edaf226 100644 --- a/test/test_regression.py +++ b/test/test_regression.py @@ -151,9 +151,7 @@ def test_simple_separated_format_with_headers(): from tabulate import simple_separated_format expected = " a| b\n 1| 2" - formatted = tabulate( - [[1, 2]], headers=["a", "b"], tablefmt=simple_separated_format("|") - ) + formatted = tabulate([[1, 2]], headers=["a", "b"], tablefmt=simple_separated_format("|")) assert_equal(expected, formatted) @@ -239,9 +237,7 @@ def test_isconvertible_on_set_values(): def test_ansi_color_for_decimal_numbers(): "Regression: ANSI colors for decimal numbers (issue #36)" table = [["Magenta", "\033[95m" + "1.1" + "\033[0m"]] - expected = "\n".join( - ["------- ---", "Magenta \x1b[95m1.1\x1b[0m", "------- ---"] - ) + expected = "\n".join(["------- ---", "Magenta \x1b[95m1.1\x1b[0m", "------- ---"]) result = tabulate(table) assert_equal(expected, result) diff --git a/test/test_textwrapper.py b/test/test_textwrapper.py index 5e86b5c9..6f77cb7c 100644 --- a/test/test_textwrapper.py +++ b/test/test_textwrapper.py @@ -39,9 +39,9 @@ def test_wrap_longword_non_wide(): orig = OTW(width=width) cust = CTW(width=width) - assert orig.wrap(data) == cust.wrap( - data - ), "Failure on non-wide char longword regression check for width " + str(width) + assert orig.wrap(data) == cust.wrap(data), ( + "Failure on non-wide char longword regression check for width " + str(width) + ) def test_wrap_wide_char_multiword(): @@ -111,9 +111,7 @@ def test_wrapper_len_ignores_color_chars(): def test_wrap_full_line_color(): """TextWrapper: Wrap a line when the full thing is enclosed in color tags""" # This has both a text color and a background color - data = ( - "\033[31m\033[104mThis is a test string for testing TextWrap with colors\033[0m" - ) + data = "\033[31m\033[104mThis is a test string for testing TextWrap with colors\033[0m" expected = [ "\033[31m\033[104mThis is a test\033[0m", From 0e581068eefe852ba357d6c25202be2160159d0d Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Wed, 4 Mar 2026 23:08:31 +0100 Subject: [PATCH 132/204] add tox-uv plugin as a dev dependency --- pyproject.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/pyproject.toml b/pyproject.toml index 2ae0586c..27596a6c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -39,6 +39,7 @@ dev = [ "build>=1.4.0", "ruff>=0.15.4", "tox>=4.47.3", + "tox-uv>=1.0", "twine>=6.2.0", ] From f4f06884eb37c9eff0a30f1b345a4e36376d2474 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Wed, 4 Mar 2026 23:12:35 +0100 Subject: [PATCH 133/204] upgrade github actions' versions --- .github/workflows/lint.yml | 4 ++-- .github/workflows/tabulate.yml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 3bf20ee2..be87d66e 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -12,9 +12,9 @@ jobs: python-version: ['3.13'] steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v5 + uses: actions/setup-python@v6 with: python-version: ${{ matrix.python-version }} - name: Install dependencies diff --git a/.github/workflows/tabulate.yml b/.github/workflows/tabulate.yml index 141a686f..691613c1 100644 --- a/.github/workflows/tabulate.yml +++ b/.github/workflows/tabulate.yml @@ -13,9 +13,9 @@ jobs: runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v5 + uses: actions/setup-python@v6 with: python-version: ${{ matrix.python-version }} allow-prereleases: true From 6a1ee349545e4ea36bd7fba4165e37d11e81a7b6 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Wed, 4 Mar 2026 23:29:40 +0100 Subject: [PATCH 134/204] update the list of contributors --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 4772c5b2..ad9fcff2 100644 --- a/README.md +++ b/README.md @@ -1279,4 +1279,5 @@ Vijaya Krishna Kasula, Furcy Pin, Christian Fibich, Shaun Duncan, Dimitri Papadopoulos, Élie Goudout, Racerroar888, Phill Zarfos, Keyacom, Andrew Coffey, Arpit Jain, Israel Roldan, ilya112358, Dan Nicholson, Frederik Scheerer, cdar07 (cdar), Racerroar888, -Perry Kundert. +Perry Kundert, Hnasar, Jun Koo, Jo2234, Bjorn Olsen, George Schizas, +Kadir Can Ozden. From 106b77e86320a15d002998e2243e5decbf62f959 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Wed, 4 Mar 2026 23:34:56 +0100 Subject: [PATCH 135/204] update CHANGELOG --- CHANGELOG | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 27374413..178695cd 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,7 @@ -- 0.10.0: Add support for Python 3.11, 3.12, 3.13. - Drop support for Python 3.7, 3.8. +- 0.11.0: + Drop support of the legacy `youtrack` format. +- 0.10.0: Add support for Python 3.11, 3.12, 3.13, 3.14. + Drop support for Python 3.7, 3.8, 3.9. PRESERVE_STERILITY global is replaced with preserve_sterility function argument. New formatting options: headersglobalalign, headersalign, colglobalalign. New output format: ``colon_grid`` (Pandoc grid_tables with alignment) From 5768953f2edb5a5d51c83b5d67f244194b762fd2 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Wed, 4 Mar 2026 23:35:36 +0100 Subject: [PATCH 136/204] [breaking] remove support of the legacy `youtrack` format --- tabulate/__init__.py | 11 ----------- test/test_output.py | 13 ------------- 2 files changed, 24 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 8a4b41ce..b9f9f568 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -627,16 +627,6 @@ def escape_empty(val): padding=1, with_header_hide=None, ), - "youtrack": TableFormat( - lineabove=None, - linebelowheader=None, - linebetweenrows=None, - linebelow=None, - headerrow=DataRow("|| ", " || ", " || "), - datarow=DataRow("| ", " | ", " |"), - padding=1, - with_header_hide=None, - ), "html": TableFormat( lineabove=_html_begin_table_without_header, linebelowheader="", @@ -766,7 +756,6 @@ def escape_empty(val): # TODO: Add multiline support for the remaining table formats: # - mediawiki: Replace \n with
# - moinmoin: TBD -# - youtrack: TBD # - html: Replace \n with
# - latex*: Use "makecell" package: In header, replace X\nY with # \thead{X\\Y} and in data row, replace X\nY with \makecell{X\\Y} diff --git a/test/test_output.py b/test/test_output.py index 68a7905e..d9405a64 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -2530,19 +2530,6 @@ def test_moinmoin(): assert_equal(expected, result) -def test_youtrack(): - "Output: youtrack with headers" - expected = "\n".join( - [ - "|| strings || numbers ||", - "| spam | 41.9999 |", - "| eggs | 451 |", - ] - ) - result = tabulate(_test_table, _test_table_headers, tablefmt="youtrack") - assert_equal(expected, result) - - def test_moinmoin_headerless(): "Output: moinmoin without headers" expected = "\n".join( From 1818a3b4ce66b69b08e8f76cfd25c32a67dcdd53 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Wed, 4 Mar 2026 23:51:36 +0100 Subject: [PATCH 137/204] require wcwidth>=0.6.0 (optional dependency for widechars) --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 27596a6c..e4d75224 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -27,7 +27,7 @@ dynamic = ["version"] Homepage = "https://github.com/astanin/python-tabulate" [project.optional-dependencies] -widechars = ["wcwidth"] +widechars = ["wcwidth>=0.6.0"] [project.scripts] tabulate = "tabulate:_main" From 032dc0d107fedd4ce7921c1a494a76a2910f49ff Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 5 Mar 2026 00:19:11 +0100 Subject: [PATCH 138/204] fix #399 - avoid infinite loop in _CustomTextWrap on wide characters with width=1 --- tabulate/__init__.py | 4 ++++ test/test_textwrapper.py | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index b9f9f568..ae184f17 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -2739,6 +2739,10 @@ def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width): stripped_chunk = _strip_ansi(chunk) while i <= len(stripped_chunk) and self._len(stripped_chunk[:i]) <= space_left: i = i + 1 + # Always consume at least one character so _wrap_chunks makes + # progress even when the first character is wider than space_left + # (e.g. a 2-column CJK char in a 1-column-wide slot). + i = max(i, 2) # Consider escape codes when breaking words up total_escape_len = 0 last_group = 0 diff --git a/test/test_textwrapper.py b/test/test_textwrapper.py index 6f77cb7c..03574c2c 100644 --- a/test/test_textwrapper.py +++ b/test/test_textwrapper.py @@ -286,3 +286,41 @@ def test_wrap_optional_bool_strs(): ] expected = "\n".join(expected) assert_equal(expected, result) + + +def test_wrap_wide_char_no_column_overflow(): + "TextWrapper: wide chars must not overflow the requested column width." + try: + import wcwidth + except ImportError: + skip("test_wrap_wide_char_no_column_overflow is skipped") + + # Each Korean character occupies 2 display columns. + data = "\ud55c\uae00\ud14c\uc2a4\ud2b8" # 한글테스트 + for width in [2, 3, 4, 5, 6]: + wrapper = CTW(width=width) + lines = wrapper.wrap(data) + for line in lines: + display_width = wcwidth.wcswidth(line) + assert display_width <= width, ( + f"Line {repr(line)} has display width {display_width} " + f"which exceeds requested column width {width}" + ) + + +def test_wrap_wide_char_narrower_than_char_width(): + """TextWrapper: column width smaller than a single wide char must not hang (issue #399). + + When the requested width is 1 but every character is 2 display columns + wide, _handle_long_word must still make progress (one character per line) + rather than looping forever. + """ + try: + import wcwidth # noqa: F401 + except ImportError: + skip("test_wrap_wide_char_narrower_than_char_width is skipped") + + data = "\ud55c\uae00" # 한글 -- each char is 2 display cols wide + # width=1 is narrower than any character; each char should still get its own line + result = CTW(width=1).wrap(data) + assert result == ["\ud55c", "\uae00"] From 897875659611d88673fbac9a9f6333624417d85c Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 5 Mar 2026 00:31:13 +0100 Subject: [PATCH 139/204] add test_grapheme_clusters.py from pull request #391 --- test/test_grapheme_clusters.py | 239 +++++++++++++++++++++++++++++++++ 1 file changed, 239 insertions(+) create mode 100644 test/test_grapheme_clusters.py diff --git a/test/test_grapheme_clusters.py b/test/test_grapheme_clusters.py new file mode 100644 index 00000000..af380b45 --- /dev/null +++ b/test/test_grapheme_clusters.py @@ -0,0 +1,239 @@ +"""Tests for Unicode grapheme cluster handling in tabulate.""" + +import pytest + +from tabulate import tabulate + +try: + import wcwidth + + HAS_WCWIDTH = True + HAS_WCWIDTH_030 = hasattr(wcwidth, "wrap") +except ImportError: + wcwidth = None + HAS_WCWIDTH = False + HAS_WCWIDTH_030 = False + +requires_wcwidth = pytest.mark.skipif(not HAS_WCWIDTH, reason="requires wcwidth") + +requires_wcwidth_030 = pytest.mark.skipif(not HAS_WCWIDTH_030, reason="requires wcwidth >= 0.3.0") + + +class TestGraphemeClusterWidth: + """Tests for correct width calculation of grapheme clusters.""" + + @requires_wcwidth + def test_zwj_family_emoji_width(self): + """ZWJ family emoji has display width 2.""" + family = "\U0001f468\u200d\U0001f469\u200d\U0001f467" + assert wcwidth.wcswidth(family) == 2 + + @requires_wcwidth + def test_regional_indicator_flag_width(self): + """Regional indicator pair (flag) has display width 2.""" + us_flag = "\U0001f1fa\U0001f1f8" + assert wcwidth.wcswidth(us_flag) == 2 + + @requires_wcwidth + def test_vs16_emoji_width(self): + """VS16 variation selector creates wide emoji.""" + heart = "\u2764\ufe0f" + assert wcwidth.wcswidth(heart) == 2 + + +class TestGraphemeClusterAlignment: + """Tests for correct alignment of cells containing grapheme clusters.""" + + @requires_wcwidth + def test_zwj_alignment_in_grid(self): + """ZWJ emoji aligns correctly in grid format.""" + family = "\U0001f468\u200d\U0001f469\u200d\U0001f467" + data = [ + ["ABC", "text"], + [family, "emoji"], + ] + result = tabulate(data, headers=["col", "desc"], tablefmt="grid") + lines = result.split("\n") + + border_width = len(lines[0]) + for line in lines: + from tabulate import _visible_width + + assert _visible_width(line) == border_width + + @requires_wcwidth + def test_flag_alignment_in_grid(self): + """Regional indicator flags align correctly in grid format.""" + us_flag = "\U0001f1fa\U0001f1f8" + data = [ + ["AB", "text"], + [us_flag, "flag"], + ] + result = tabulate(data, headers=["col", "desc"], tablefmt="grid") + lines = result.split("\n") + + border_width = len(lines[0]) + for line in lines: + from tabulate import _visible_width + + assert _visible_width(line) == border_width + + +class TestGraphemeClusterWrapping: + """Tests for grapheme cluster preservation during text wrapping. + + These tests require wcwidth >= 0.3.0 for iter_graphemes and wrap() APIs. + """ + + @requires_wcwidth_030 + def test_zwj_not_broken_during_wrap(self): + """ZWJ sequence preserved as single unit during wrap.""" + family = "\U0001f468\u200d\U0001f469\u200d\U0001f467" + data = [[f"A{family}B"]] + result = tabulate(data, tablefmt="plain", maxcolwidths=3) + + graphemes_in_result = [] + for line in result.split("\n"): + graphemes_in_result.extend(list(wcwidth.iter_graphemes(line.strip()))) + + assert family in graphemes_in_result + + @requires_wcwidth_030 + def test_flag_not_broken_during_wrap(self): + """Regional indicator flag preserved as single unit during wrap.""" + us_flag = "\U0001f1fa\U0001f1f8" + gb_flag = "\U0001f1ec\U0001f1e7" + fr_flag = "\U0001f1eb\U0001f1f7" + flags = us_flag + gb_flag + fr_flag + + data = [[flags]] + result = tabulate(data, tablefmt="plain", maxcolwidths=5) + + graphemes_in_result = [] + for line in result.split("\n"): + graphemes_in_result.extend(list(wcwidth.iter_graphemes(line.strip()))) + + assert us_flag in graphemes_in_result + assert gb_flag in graphemes_in_result + assert fr_flag in graphemes_in_result + + @requires_wcwidth_030 + def test_vs16_not_broken_during_wrap(self): + """VS16 variation selector kept with base character during wrap.""" + heart = "\u2764\ufe0f" + data = [[heart * 3]] + result = tabulate(data, tablefmt="plain", maxcolwidths=4) + + graphemes_in_result = [] + for line in result.split("\n"): + graphemes_in_result.extend(list(wcwidth.iter_graphemes(line.strip()))) + + heart_count = sum(1 for g in graphemes_in_result if g == heart) + assert heart_count == 3 + + @requires_wcwidth_030 + def test_skin_tone_modifier_not_broken(self): + """Skin tone modifier preserved with emoji during wrap.""" + wave_light = "\U0001f44b\U0001f3fb" + data = [[f"Hi{wave_light}there"]] + result = tabulate(data, tablefmt="plain", maxcolwidths=5) + + graphemes_in_result = [] + for line in result.split("\n"): + graphemes_in_result.extend(list(wcwidth.iter_graphemes(line.strip()))) + + assert wave_light in graphemes_in_result + + +class TestComplexGraphemeClusters: + """Tests for complex grapheme cluster scenarios. + + These tests require wcwidth >= 0.3.0 for iter_graphemes API. + """ + + @requires_wcwidth_030 + def test_multiple_zwj_sequences_in_cell(self): + """Multiple ZWJ sequences in single cell handled correctly.""" + family = "\U0001f468\u200d\U0001f469\u200d\U0001f467" + technologist = "\U0001f468\U0001f3fb\u200d\U0001f4bb" + data = [[f"{family} and {technologist}"]] + result = tabulate(data, tablefmt="plain", maxcolwidths=15) + + graphemes_in_result = [] + for line in result.split("\n"): + graphemes_in_result.extend(list(wcwidth.iter_graphemes(line.strip()))) + + assert family in graphemes_in_result + assert technologist in graphemes_in_result + + @requires_wcwidth_030 + def test_flags_with_text_wrap(self): + """Flags interspersed with text wrap correctly.""" + us_flag = "\U0001f1fa\U0001f1f8" + data = [[f"Visit {us_flag} USA today!"]] + result = tabulate(data, tablefmt="plain", maxcolwidths=10) + + graphemes_in_result = [] + for line in result.split("\n"): + graphemes_in_result.extend(list(wcwidth.iter_graphemes(line.strip()))) + + assert us_flag in graphemes_in_result + + @requires_wcwidth_030 + def test_combining_marks_preserved(self): + """Combining diacritical marks stay with base character.""" + e_acute = "e\u0301" + data = [[f"caf{e_acute} au lait"]] + result = tabulate(data, tablefmt="plain", maxcolwidths=5) + + graphemes_in_result = [] + for line in result.split("\n"): + graphemes_in_result.extend(list(wcwidth.iter_graphemes(line.strip()))) + + assert e_acute in graphemes_in_result + + +class TestAnsiWithGraphemeClusters: + """Tests for ANSI escape codes combined with grapheme clusters.""" + + @requires_wcwidth + def test_ansi_colored_zwj_width(self): + """ANSI colored ZWJ emoji has correct width.""" + family = "\U0001f468\u200d\U0001f469\u200d\U0001f467" + colored = f"\x1b[31m{family}\x1b[0m" + + from tabulate import _visible_width + + assert _visible_width(colored) == 2 + + @requires_wcwidth + def test_ansi_colored_zwj_alignment(self): + """ANSI colored ZWJ emoji aligns correctly.""" + family = "\U0001f468\u200d\U0001f469\u200d\U0001f467" + colored = f"\x1b[31m{family}\x1b[0m" + data = [ + ["AB", "text"], + [colored, "emoji"], + ] + result = tabulate(data, headers=["col", "desc"], tablefmt="grid") + lines = result.split("\n") + + from tabulate import _visible_width + + border_width = _visible_width(lines[0]) + for line in lines: + assert _visible_width(line) == border_width + + @requires_wcwidth_030 + def test_ansi_colored_flag_wrap(self): + """ANSI colored flag not broken during wrap.""" + us_flag = "\U0001f1fa\U0001f1f8" + colored = f"\x1b[34m{us_flag}\x1b[0m" + data = [[f"A{colored}B"]] + result = tabulate(data, tablefmt="plain", maxcolwidths=4) + + assert "\U0001f1fa" in result + assert "\U0001f1f8" in result + lines = [line.strip() for line in result.split("\n") if line.strip()] + flag_parts_same_line = any("\U0001f1fa" in line and "\U0001f1f8" in line for line in lines) + assert flag_parts_same_line From 4c9a049790c336bf02dcd4eb6aab36777687d4ff Mon Sep 17 00:00:00 2001 From: Jeff Quast Date: Thu, 5 Mar 2026 01:09:00 +0100 Subject: [PATCH 140/204] add fallback for measuring visible width with wcwidth < 0.3 based on pull request #391 --- README.md | 2 +- tabulate/__init__.py | 18 ++++++++++---- test/test_grapheme_clusters.py | 43 ++++++++++++++++++++++++++++++++++ 3 files changed, 57 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index ad9fcff2..405736e9 100644 --- a/README.md +++ b/README.md @@ -1280,4 +1280,4 @@ Dimitri Papadopoulos, Élie Goudout, Racerroar888, Phill Zarfos, Keyacom, Andrew Coffey, Arpit Jain, Israel Roldan, ilya112358, Dan Nicholson, Frederik Scheerer, cdar07 (cdar), Racerroar888, Perry Kundert, Hnasar, Jun Koo, Jo2234, Bjorn Olsen, George Schizas, -Kadir Can Ozden. +Kadir Can Ozden, Jeff Quast. diff --git a/tabulate/__init__.py b/tabulate/__init__.py index ae184f17..bafe51fd 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1111,13 +1111,21 @@ def _visible_width(s): """ # optional wide-character support if wcwidth is not None and WIDE_CHARS_MODE: - len_fn = wcwidth.wcswidth - else: - len_fn = len + # when already a string, it could contain terminal sequences, + # wcwidth >= 0.3.0 handles ANSI codes internally, + if hasattr(wcwidth, "width"): + return wcwidth.width(str(s)) + # while previous versions need them stripped first. + if isinstance(s, (str, bytes)): + return wcwidth.wcswidth(_strip_ansi(str(s))) + + # Otherwise, coerce to string, guaranteed to be without any control codes, + # we can use wcswidth() directly. + return wcwidth.wcswidth(str(s)) if isinstance(s, (str, bytes)): - return len_fn(_strip_ansi(s)) + return len(_strip_ansi(s)) else: - return len_fn(str(s)) + return len(str(s)) def _is_multiline(s): diff --git a/test/test_grapheme_clusters.py b/test/test_grapheme_clusters.py index af380b45..0a032b0d 100644 --- a/test/test_grapheme_clusters.py +++ b/test/test_grapheme_clusters.py @@ -1,5 +1,7 @@ """Tests for Unicode grapheme cluster handling in tabulate.""" +import unittest.mock as mock + import pytest from tabulate import tabulate @@ -9,15 +11,21 @@ HAS_WCWIDTH = True HAS_WCWIDTH_030 = hasattr(wcwidth, "wrap") + HAS_WCWIDTH_WIDTH = hasattr(wcwidth, "width") except ImportError: wcwidth = None HAS_WCWIDTH = False HAS_WCWIDTH_030 = False + HAS_WCWIDTH_WIDTH = False requires_wcwidth = pytest.mark.skipif(not HAS_WCWIDTH, reason="requires wcwidth") requires_wcwidth_030 = pytest.mark.skipif(not HAS_WCWIDTH_030, reason="requires wcwidth >= 0.3.0") +requires_wcwidth_width = pytest.mark.skipif( + not HAS_WCWIDTH_WIDTH, reason="requires wcwidth with width() API" +) + class TestGraphemeClusterWidth: """Tests for correct width calculation of grapheme clusters.""" @@ -237,3 +245,38 @@ def test_ansi_colored_flag_wrap(self): lines = [line.strip() for line in result.split("\n") if line.strip()] flag_parts_same_line = any("\U0001f1fa" in line and "\U0001f1f8" in line for line in lines) assert flag_parts_same_line + + +class TestVisibleWidthFallback: + """Tests for _visible_width wcwidth version compatibility. + + Covers both the modern wcwidth.width() path (>= 0.3.0) and the legacy + wcswidth() path used when width() is not available. + """ + + @requires_wcwidth_width + def test_visible_width_new_api_strips_ansi(self): + """_visible_width returns correct width via wcwidth.width() with ANSI codes.""" + from tabulate import _visible_width + + # Two Korean chars (each 2 cols wide) wrapped in ANSI color codes. + # wcwidth.width() handles ANSI internally, so no explicit stripping needed. + colored_wide = "\x1b[31m한글\x1b[0m" + assert _visible_width(colored_wide) == 4 + + @requires_wcwidth + def test_visible_width_legacy_api_strips_ansi(self): + """_visible_width strips ANSI before wcswidth() when width() is unavailable.""" + import tabulate as tabulate_module + from tabulate import _visible_width + + # Build a mock wcwidth that exposes only wcswidth(), not width(). + # spec= limits auto-created attributes, so hasattr(mock, "width") is False. + legacy_wcwidth = mock.MagicMock(spec=["wcswidth"]) + legacy_wcwidth.wcswidth.side_effect = wcwidth.wcswidth + + colored_wide = "\x1b[31m한글\x1b[0m" + with mock.patch.object(tabulate_module, "wcwidth", legacy_wcwidth): + result = _visible_width(colored_wide) + + assert result == 4 From 553ecc0e7ecb1d04ca52bbbce188e57112d5032a Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 5 Mar 2026 00:08:10 +0100 Subject: [PATCH 141/204] Prefer f-strings --- test/test_textwrapper.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/test_textwrapper.py b/test/test_textwrapper.py index 03574c2c..caf85e29 100644 --- a/test/test_textwrapper.py +++ b/test/test_textwrapper.py @@ -17,7 +17,7 @@ def test_wrap_multiword_non_wide(): assert [line.rstrip() for line in orig.wrap(data)] == [ line.rstrip() for line in cust.wrap(data) - ], "Failure on non-wide char multiword regression check for width " + str(width) + ], f"Failure on non-wide char multiword regression check for width {width}" def test_wrap_multiword_non_wide_with_hypens(): @@ -29,7 +29,7 @@ def test_wrap_multiword_non_wide_with_hypens(): assert [line.rstrip() for line in orig.wrap(data)] == [ line.rstrip() for line in cust.wrap(data) - ], "Failure on non-wide char hyphen regression check for width " + str(width) + ], f"Failure on non-wide char hyphen regression check for width {width}" def test_wrap_longword_non_wide(): @@ -40,7 +40,7 @@ def test_wrap_longword_non_wide(): cust = CTW(width=width) assert orig.wrap(data) == cust.wrap(data), ( - "Failure on non-wide char longword regression check for width " + str(width) + f"Failure on non-wide char longword regression check for width {width}" ) From 0e842e1b08abc848f9bad2208c5a78f0d7743941 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Wed, 4 Mar 2026 23:46:00 +0100 Subject: [PATCH 142/204] A few ruff / pre-commit details - The proper hook for the linter is `ruff-check` nowadays. - Use `extend-select` and let the linter choose its default rule sets - compatible with formatters. - No need to specify the directory to check, ruff operates on `.` by default. - The `debug-statements` hook can be replaced by Ruff debugger (T100) rules if needed. - Add the `end-of-file-fixer` hook. --- .pre-commit-config.yaml | 7 +++---- HOWTOPUBLISH | 2 +- benchmark/requirements.txt | 2 +- pyproject.toml | 4 ++-- tox.ini | 5 ++--- 5 files changed, 9 insertions(+), 11 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index e9808666..9d940f05 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -2,13 +2,12 @@ repos: - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.15.4 hooks: - - id: ruff - args: [--fix] + - id: ruff-check + args: ["--fix", "--show-fixes"] - id: ruff-format - repo: https://github.com/pre-commit/pre-commit-hooks rev: v6.0.0 hooks: + - id: end-of-file-fixer - id: trailing-whitespace - id: check-yaml - - id: debug-statements - language_version: python3 diff --git a/HOWTOPUBLISH b/HOWTOPUBLISH index 880ab19c..a5b0fb40 100644 --- a/HOWTOPUBLISH +++ b/HOWTOPUBLISH @@ -14,4 +14,4 @@ git push # wait for all CI builds to succeed git push --tags # if CI builds succeed twine upload --repository-url https://test.pypi.org/legacy/ dist/* twine upload dist/* -# use __token__ as username andPyPI API token as password (generate at pypi.org → Account settings → API tokens) \ No newline at end of file +# use __token__ as username andPyPI API token as password (generate at pypi.org → Account settings → API tokens) diff --git a/benchmark/requirements.txt b/benchmark/requirements.txt index 81086efe..861b7eea 100644 --- a/benchmark/requirements.txt +++ b/benchmark/requirements.txt @@ -1,2 +1,2 @@ prettytable -texttable \ No newline at end of file +texttable diff --git a/pyproject.toml b/pyproject.toml index e4d75224..95fddcaf 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -47,8 +47,8 @@ dev = [ line-length = 99 [tool.ruff.lint] -select = ["E", "F", "W", "C90"] -ignore = ["E203", "E402", "E721", "C901"] +extend-select = ["W", "C90"] +ignore = ["E721", "C901"] [tool.ruff.lint.mccabe] max-complexity = 22 diff --git a/tox.ini b/tox.ini index 3baea31a..8eb0a182 100644 --- a/tox.ini +++ b/tox.ini @@ -30,8 +30,8 @@ passenv = [testenv:lint] commands = - ruff check . - ruff format --check . + ruff check + ruff format --check deps = ruff @@ -147,4 +147,3 @@ deps = numpy pandas wcwidth - From 3381cfcabe361feb3973945aebb74a310ca1008b Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 5 Mar 2026 00:16:04 +0100 Subject: [PATCH 143/204] Apply ruff rule RUF100 Unused blanket `noqa` directive --- tabulate/__init__.py | 2 +- test/test_api.py | 6 +++--- test/test_output.py | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index bafe51fd..2ced035a 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1318,7 +1318,7 @@ def _format(val, valtype, floatfmt, intfmt, missingval="", has_invisible=True): tabulate(tbl, headers=hrow) == good_result True - """ # noqa: E501 + """ if val is None: return missingval if isinstance(val, (bytes, str)) and not val: diff --git a/test/test_api.py b/test/test_api.py index 20493ec0..512a84d6 100644 --- a/test/test_api.py +++ b/test/test_api.py @@ -17,7 +17,7 @@ def test_tabulate_formats(): print("tabulate_formats = %r" % supported) assert type(supported) is list for fmt in supported: - assert type(fmt) is str # noqa + assert type(fmt) is str def _check_signature(function, expected_sig): @@ -34,7 +34,7 @@ def _check_signature(function, expected_sig): def test_tabulate_signature(): "API: tabulate() type signature is unchanged" - assert type(tabulate) is type(lambda: None) # noqa + assert type(tabulate) is type(lambda: None) expected_sig = [ ("tabular_data", _empty), ("headers", ()), @@ -62,6 +62,6 @@ def test_tabulate_signature(): def test_simple_separated_format_signature(): "API: simple_separated_format() type signature is unchanged" - assert type(simple_separated_format) is type(lambda: None) # noqa + assert type(simple_separated_format) is type(lambda: None) expected_sig = [("separator", _empty)] _check_signature(simple_separated_format, expected_sig) diff --git a/test/test_output.py b/test/test_output.py index d9405a64..7a56ad9a 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -131,7 +131,7 @@ def test_plain_maxcolwidth_autowraps_wide_chars(): ["hdr", "fold"], [ "1", - "약간 감싸면 더 잘 보일 수있는 다소 긴 설명입니다 설명입니다 설명입니다 설명입니다 설명", # noqa: E501 + "약간 감싸면 더 잘 보일 수있는 다소 긴 설명입니다 설명입니다 설명입니다 설명입니다 설명", ], ] expected = "\n".join( @@ -2557,7 +2557,7 @@ def test_html(): [ "", "", - '', # noqa + '', "", "", '', @@ -2578,7 +2578,7 @@ def test_unsafehtml(): [ "
<strings> <&numbers&>
<strings> <&numbers&>
spam > 41.9999
", "", - "", # noqa + "", "", "", '', From 8f32086665760bcb2bd729623dc58a8da259a68b Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 5 Mar 2026 00:20:22 +0100 Subject: [PATCH 144/204] Apply ruff/Pylint rule PLW0108 Lambda may be unnecessary; consider inlining inner function --- test/test_input.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/test_input.py b/test/test_input.py index fca67506..c2d19c5d 100644 --- a/test/test_input.py +++ b/test/test_input.py @@ -12,7 +12,7 @@ def test_iterable_of_iterables(): "Input: an iterable of iterables." - ii = iter(map(lambda x: iter(x), [range(5), range(5, 0, -1)])) + ii = iter(map(iter, [range(5), range(5, 0, -1)])) expected = "\n".join(["- - - - -", "0 1 2 3 4", "5 4 3 2 1", "- - - - -"]) result = tabulate(ii) assert_equal(expected, result) @@ -20,7 +20,7 @@ def test_iterable_of_iterables(): def test_iterable_of_iterables_headers(): "Input: an iterable of iterables with headers." - ii = iter(map(lambda x: iter(x), [range(5), range(5, 0, -1)])) + ii = iter(map(iter, [range(5), range(5, 0, -1)])) expected = "\n".join( [ " a b c d e", @@ -35,7 +35,7 @@ def test_iterable_of_iterables_headers(): def test_iterable_of_iterables_firstrow(): "Input: an iterable of iterables with the first row as headers" - ii = iter(map(lambda x: iter(x), ["abcde", range(5), range(5, 0, -1)])) + ii = iter(map(iter, ["abcde", range(5), range(5, 0, -1)])) expected = "\n".join( [ " a b c d e", From 5373ebfa9568db65cf6b9a4edfe22662d028ef12 Mon Sep 17 00:00:00 2001 From: Mayukha Vadari Date: Wed, 4 Mar 2026 20:31:15 -0400 Subject: [PATCH 145/204] fix #176 - implement Decimal fixed-point support * fix decimal precision issue * fix other float to Decimal * fix float precision * add test * clean up * fix bug * expand test * fix test to get around weird precision issues in python2.7 * lint * respond to comments --------- Co-authored-by: Sergey Astanin --- tabulate/__init__.py | 3 +++ test/test_output.py | 11 +++++++++++ 2 files changed, 14 insertions(+) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 2ced035a..da88b04f 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -13,6 +13,7 @@ import warnings from collections import namedtuple from collections.abc import Iterable, Sized +from decimal import Decimal from html import escape as htmlescape from itertools import chain, zip_longest as izip_longest from functools import reduce, partial @@ -1356,6 +1357,8 @@ def _format(val, valtype, floatfmt, intfmt, missingval="", has_invisible=True): else: if isinstance(val, str) and "," in val: val = val.replace(",", "") # handle thousands-separators + if isinstance(val, Decimal): + return format(val, floatfmt) try: return format(float(val), floatfmt) except (ValueError, TypeError): diff --git a/test/test_output.py b/test/test_output.py index 7a56ad9a..7b44dddc 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -1,5 +1,6 @@ """Test output of the various forms of tabular data.""" +from decimal import Decimal from pytest import mark from common import assert_equal, raises, skip, check_warnings @@ -2857,6 +2858,16 @@ def test_floatfmt_multi(): assert_equal(expected, result) +def test_floatfmt_decimal(): + result = tabulate( + [[Decimal("99999998999.999980"), 1234.5, 1.2345678, "inf"]], + floatfmt=".6f", + tablefmt="plain", + ) + expected = "99999998999.999980 1234.500000 1.234568 inf" + assert_equal(expected, result) + + def test_colalign_multi(): "Output: string columns with custom colalign" result = tabulate([["one", "two"], ["three", "four"]], colalign=("right",), tablefmt="plain") From 877c0206130816534267b2b9b765afa47d990417 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 5 Mar 2026 01:34:56 +0100 Subject: [PATCH 146/204] update contributors list and CHANGELOG - add Decimal format support --- CHANGELOG | 4 +++- README.md | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 178695cd..a82abc0a 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,7 @@ - 0.11.0: - Drop support of the legacy `youtrack` format. + Drop support of the legacy `youtrack` format. + Add support of the `Decimal` data type. + Various bug fixes. - 0.10.0: Add support for Python 3.11, 3.12, 3.13, 3.14. Drop support for Python 3.7, 3.8, 3.9. PRESERVE_STERILITY global is replaced with preserve_sterility function argument. diff --git a/README.md b/README.md index 405736e9..10b54c84 100644 --- a/README.md +++ b/README.md @@ -1280,4 +1280,4 @@ Dimitri Papadopoulos, Élie Goudout, Racerroar888, Phill Zarfos, Keyacom, Andrew Coffey, Arpit Jain, Israel Roldan, ilya112358, Dan Nicholson, Frederik Scheerer, cdar07 (cdar), Racerroar888, Perry Kundert, Hnasar, Jun Koo, Jo2234, Bjorn Olsen, George Schizas, -Kadir Can Ozden, Jeff Quast. +Kadir Can Ozden, Jeff Quast, Mayukha Vadari. From c576b072819bb5010125dd6e746e0c9ac69fa8f9 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 5 Mar 2026 01:44:45 +0100 Subject: [PATCH 147/204] add test case from pull request #387 - test_wrap_color_line_longword_zerowidth --- test/test_textwrapper.py | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/test/test_textwrapper.py b/test/test_textwrapper.py index caf85e29..7cd1581c 100644 --- a/test/test_textwrapper.py +++ b/test/test_textwrapper.py @@ -174,6 +174,44 @@ def test_wrap_color_line_longword(): assert_equal(expected, result) +def test_wrap_color_line_longword_zerowidth(): + """Lines with zero-width symbols (accents) must include those symbols with the prior symbol. + Let's exercise the calculation where the available symbols never satisfy the available width, + and ensure chunk calculation succeeds and ANSI colors are maintained. + + Most combining marks combine with the preceding character (even in right-to-left alphabets): + - "e\u0301" → "é" (e + combining acute accent) + - "a\u0308" → "ä" (a + combining diaeresis) + - "n\u0303" → "ñ" (n + combining tilde) + Enclosing Marks: Some combining marks enclose the base character: + - "A\u20dd" → Ⓐ Combining enclosing circle + Multiple Combining Marks: You can stack multiple combining marks on a single base character: + - "e\u0301\u0308" → e with both acute accent and diaeresis + Zero width space → "ab" with a : + - "a\u200bb" + + """ + try: + import wcwidth # noqa + except ImportError: + skip("test_wrap_wide_char is skipped") + + # Exactly filled, with a green zero-width segment at the end. + data = ( + "This_is_A\u20dd_\033[31mte\u0301st_string_\u200b" + "to_te\u0301\u0308st_a\u0308ccent\033[32m\u200b\033[0m" + ) + + expected = [ + "This_is_A\u20dd_\033[31mte\u0301\033[0m", + "\033[31mst_string_\u200bto\033[0m", + "\033[31m_te\u0301\u0308st_a\u0308ccent\033[32m\u200b\033[0m", + ] + wrapper = CTW(width=12) + result = wrapper.wrap(data) + assert_equal(expected, result) + + def test_wrap_color_line_multiple_escapes(): data = "012345(\x1b[32ma\x1b[0mbc\x1b[32mdefghij\x1b[0m)" expected = [ From b577975155c3e27bbc3d440794f445e917e479e0 Mon Sep 17 00:00:00 2001 From: Rebecca Jean Herman Date: Tue, 20 Aug 2024 15:15:35 +0200 Subject: [PATCH 148/204] minor change to fix issue preventing passing in an interable for showindex --- tabulate/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index da88b04f..c45c6aa2 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1600,7 +1600,7 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"): # add or remove an index column showindex_is_a_str = type(showindex) in [str, bytes] - if showindex == "default" and index is not None: + if showindex_is_a_str and showindex == "default" and index is not None: rows = _prepend_row_index(rows, index) elif isinstance(showindex, Sized) and not showindex_is_a_str: rows = _prepend_row_index(rows, list(showindex)) From 067271664fe1d2845550ca3e86739bc237785eec Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 5 Mar 2026 02:16:42 +0100 Subject: [PATCH 149/204] add test case and update contributors for pull request #337 --- README.md | 2 +- test/test_regression.py | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 10b54c84..77a243e1 100644 --- a/README.md +++ b/README.md @@ -1280,4 +1280,4 @@ Dimitri Papadopoulos, Élie Goudout, Racerroar888, Phill Zarfos, Keyacom, Andrew Coffey, Arpit Jain, Israel Roldan, ilya112358, Dan Nicholson, Frederik Scheerer, cdar07 (cdar), Racerroar888, Perry Kundert, Hnasar, Jun Koo, Jo2234, Bjorn Olsen, George Schizas, -Kadir Can Ozden, Jeff Quast, Mayukha Vadari. +Kadir Can Ozden, Jeff Quast, Mayukha Vadari, Rebecca Jean Herman. diff --git a/test/test_regression.py b/test/test_regression.py index 5edaf226..de950b30 100644 --- a/test/test_regression.py +++ b/test/test_regression.py @@ -471,6 +471,22 @@ def count(start, step=1): assert_equal(expected, result) +def test_numpy_array_as_showindex(): + "Regression: numpy array as showindex must not raise ValueError on == comparison" + try: + import numpy as np + except ImportError: + raise skip("") + + table = [["a"], ["b"], ["c"]] + # np.array([...]) == "default" returns an element-wise boolean array whose + # truth value is ambiguous; the fix short-circuits the comparison when + # showindex is not a string. + expected = "10 a\n20 b\n30 c" + result = tabulate(table, showindex=np.array([10, 20, 30]), tablefmt="plain") + assert_equal(expected, result) + + def test_preserve_line_breaks_with_maxcolwidths(): "Regression: preserve line breaks when using maxcolwidths (github issue #190)" table = [["123456789 bbb\nccc"]] From ab790a6a160889e6505554f9829cbe43efb25a94 Mon Sep 17 00:00:00 2001 From: J08nY Date: Thu, 19 Oct 2023 13:09:56 +0200 Subject: [PATCH 150/204] Fix colalign in HTML when default is right. --- tabulate/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index c45c6aa2..4d01db9c 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -210,7 +210,7 @@ def _html_begin_table_without_header(colwidths_ignore, colaligns_ignore): def _html_row_with_attrs(celltag, unsafe, cell_values, colwidths, colaligns): alignment = { - "left": "", + "left": ' style="text-align: left;"', "right": ' style="text-align: right;"', "center": ' style="text-align: center;"', "decimal": ' style="text-align: right;"', @@ -233,7 +233,7 @@ def _html_row_with_attrs(celltag, unsafe, cell_values, colwidths, colaligns): def _moin_row_with_attrs(celltag, cell_values, colwidths, colaligns, header=""): alignment = { - "left": "", + "left": ' style="text-align: left;"', "right": '', "center": '', "decimal": '', From ebd50a75e116f367680f01fb28ef1f67ad3189f5 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 5 Mar 2026 02:36:16 +0100 Subject: [PATCH 151/204] update html and moinmoin output tests - add explicit text-align: left style related: pull request #295 --- tabulate/__init__.py | 8 ++++---- test/test_output.py | 30 +++++++++++++++--------------- 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 4d01db9c..249b3ff8 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -233,7 +233,7 @@ def _html_row_with_attrs(celltag, unsafe, cell_values, colwidths, colaligns): def _moin_row_with_attrs(celltag, cell_values, colwidths, colaligns, header=""): alignment = { - "left": ' style="text-align: left;"', + "left": '', "right": '', "center": '', "decimal": '', @@ -2149,11 +2149,11 @@ def tabulate( ... headers="firstrow", tablefmt="html"))
strings numbers
strings numbers
spam 41.9999
- + - - + +
strings numbers
strings numbers
spam 41.9999
eggs 451
spam 41.9999
eggs 451
diff --git a/test/test_output.py b/test/test_output.py index 7b44dddc..310ad124 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -2522,9 +2522,9 @@ def test_moinmoin(): "Output: moinmoin with headers" expected = "\n".join( [ - "|| ''' strings ''' || ''' numbers ''' ||", - '|| spam || 41.9999 ||', - '|| eggs || 451 ||', + "|| ''' strings ''' || ''' numbers ''' ||", + '|| spam || 41.9999 ||', + '|| eggs || 451 ||', ] ) result = tabulate(_test_table, _test_table_headers, tablefmt="moinmoin") @@ -2535,8 +2535,8 @@ def test_moinmoin_headerless(): "Output: moinmoin without headers" expected = "\n".join( [ - '|| spam || 41.9999 ||', - '|| eggs || 451 ||', + '|| spam || 41.9999 ||', + '|| eggs || 451 ||', ] ) result = tabulate(_test_table, tablefmt="moinmoin") @@ -2558,11 +2558,11 @@ def test_html(): [ "", "", - '', + '', "", "", - '', - '', + '', + '', "", "
<strings> <&numbers&>
<strings> <&numbers&>
spam > 41.9999
eggs & 451
spam > 41.9999
eggs & 451
", ] @@ -2579,11 +2579,11 @@ def test_unsafehtml(): [ "", "", - "", + "", "", "", - '', - '', + '', + '', "", "
strings numbers
strings numbers
spam 41.9999
eggs 451.0
spam 41.9999
eggs 451.0
", ] @@ -2602,8 +2602,8 @@ def test_html_headerless(): [ "", "", - '', - '', + '', + '', "", "
spam > 41.9999
eggs &451
spam > 41.9999
eggs &451
", ] @@ -2620,8 +2620,8 @@ def test_unsafehtml_headerless(): [ "", "", - '', - '', + '', + '', "", "
spam41.9999
eggs451.0
spam41.9999
eggs451.0
", ] From caec0c32bae0091f086d5ee4d11b8766820ef4ac Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 5 Mar 2026 02:37:54 +0100 Subject: [PATCH 152/204] ruff format --- test/test_output.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_output.py b/test/test_output.py index 310ad124..93de112e 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -2579,7 +2579,7 @@ def test_unsafehtml(): [ "", "", - "", + '', "", "", '', From 1c7bbd83c04e0d6b3fdabfc0c78d077439c0b74c Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 5 Mar 2026 02:50:56 +0100 Subject: [PATCH 153/204] update Contributors --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 77a243e1..cefbe720 100644 --- a/README.md +++ b/README.md @@ -1280,4 +1280,5 @@ Dimitri Papadopoulos, Élie Goudout, Racerroar888, Phill Zarfos, Keyacom, Andrew Coffey, Arpit Jain, Israel Roldan, ilya112358, Dan Nicholson, Frederik Scheerer, cdar07 (cdar), Racerroar888, Perry Kundert, Hnasar, Jun Koo, Jo2234, Bjorn Olsen, George Schizas, -Kadir Can Ozden, Jeff Quast, Mayukha Vadari, Rebecca Jean Herman. +Kadir Can Ozden, Jeff Quast, Mayukha Vadari, Rebecca Jean Herman, +Ján Jančár (J08nY). From b7dced48b168e71c50f390bb1c5b06ecfe9e4fde Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 5 Mar 2026 10:05:45 +0100 Subject: [PATCH 154/204] remove py38 and py39 from the env_list in tox.ini --- tox.ini | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tox.ini b/tox.ini index 8eb0a182..476c57b8 100644 --- a/tox.ini +++ b/tox.ini @@ -1,4 +1,4 @@ -# Tox (http://tox.testrun.org/) is a tool for running tests +# Tox (http://tox.readthedocs.org/) is a tool for running tests # in multiple virtualenvs. This configuration file will run the # test suite on all supported python versions. To use it, "pip install tox" # and then run "tox" from this directory. @@ -8,7 +8,7 @@ # for testing and it is disabled by default. [tox] -envlist = lint, py{38, 39, 310, 311, 312, 313, 314} +envlist = lint, py{310, 311, 312, 313, 314} isolated_build = True [gh] From 71282a68dc3a5ab1e42449dd196cb97b0d5a88c9 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 5 Mar 2026 10:33:25 +0100 Subject: [PATCH 155/204] add wcwidth>=0.6.0 as a dependency of the github workflows --- .github/workflows/tabulate.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/tabulate.yml b/.github/workflows/tabulate.yml index 691613c1..7e808322 100644 --- a/.github/workflows/tabulate.yml +++ b/.github/workflows/tabulate.yml @@ -22,7 +22,7 @@ jobs: - name: Install dependencies run: | python -m pip install --upgrade pip - python -m pip install pytest numpy pandas + python -m pip install pytest numpy pandas "wcwidth>=0.6.0" - name: Run tests run: | - pytest -v --doctest-modules --ignore benchmark/benchmark.py + pytest -v --doctest-modules --ignore benchmark From 9794747bdc02e71b034b2031f5644e5d61f86891 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 5 Mar 2026 10:38:11 +0100 Subject: [PATCH 156/204] add codecov to github actions --- .github/workflows/tabulate.yml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.github/workflows/tabulate.yml b/.github/workflows/tabulate.yml index 7e808322..50472508 100644 --- a/.github/workflows/tabulate.yml +++ b/.github/workflows/tabulate.yml @@ -8,6 +8,7 @@ jobs: build: strategy: matrix: + # Python 3.9 is not supported anymore, but it still works... python-version: ['3.9', '3.10', '3.11', '3.12', '3.13', '3.14'] os: ["ubuntu-latest", "windows-latest", "macos-latest"] runs-on: ${{ matrix.os }} @@ -25,4 +26,8 @@ jobs: python -m pip install pytest numpy pandas "wcwidth>=0.6.0" - name: Run tests run: | - pytest -v --doctest-modules --ignore benchmark + pytest -v --doctest-modules --ignore benchmark --cov=tabulate --cov-branch --cov-report=xml + - name: Upload coverage reports to Codecov + uses: codecov/codecov-action@v5 + with: + token: ${{ secrets.CODECOV_TOKEN }} From 28ca4d473bdac2d33d6072d9f426ce0d31ddd0bd Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 5 Mar 2026 10:39:25 +0100 Subject: [PATCH 157/204] add pytest-cov to the list of github actions' dependencies --- .github/workflows/tabulate.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/tabulate.yml b/.github/workflows/tabulate.yml index 50472508..5458c382 100644 --- a/.github/workflows/tabulate.yml +++ b/.github/workflows/tabulate.yml @@ -23,7 +23,7 @@ jobs: - name: Install dependencies run: | python -m pip install --upgrade pip - python -m pip install pytest numpy pandas "wcwidth>=0.6.0" + python -m pip install pytest pytest-cov numpy pandas "wcwidth>=0.6.0" - name: Run tests run: | pytest -v --doctest-modules --ignore benchmark --cov=tabulate --cov-branch --cov-report=xml From c26c2ef3ffac0507ce9d285d966af1a2540ae73a Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 5 Mar 2026 10:43:55 +0100 Subject: [PATCH 158/204] add code coverage badge to README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cefbe720..69fbebb3 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ pip install tabulate Build status ------------ -[![python-tabulate](https://github.com/astanin/python-tabulate/actions/workflows/tabulate.yml/badge.svg)](https://github.com/astanin/python-tabulate/actions/workflows/tabulate.yml) +[![python-tabulate](https://github.com/astanin/python-tabulate/actions/workflows/tabulate.yml/badge.svg)](https://github.com/astanin/python-tabulate/actions/workflows/tabulate.yml) [![codecov](https://codecov.io/github/astanin/python-tabulate/graph/badge.svg?token=Aa6wexP5wq)](https://codecov.io/github/astanin/python-tabulate) Library usage ------------- From 40d9cb5b99b165064b7b0f7c88f1fe807a0dcdfb Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 5 Mar 2026 10:47:58 +0100 Subject: [PATCH 159/204] remove `youtrack` examples from the documentation --- README.md | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/README.md b/README.md index 69fbebb3..c939d48a 100644 --- a/README.md +++ b/README.md @@ -196,7 +196,6 @@ Supported table formats are: - "rst" - "mediawiki" - "moinmoin" -- "youtrack" - "html" - "unsafehtml" - "latex" @@ -584,17 +583,6 @@ MediaWiki-based sites: ``` -`youtrack` format produces a table markup used in Youtrack tickets: - -```pycon ->>> print(tabulate(table, headers, tablefmt="youtrack")) -|| item || qty || -| spam | 42 | -| eggs | 451 | -| bacon | 0 | - -``` - `textile` format produces a table markup used in [Textile](http://redcloth.org/hobix.com/textile/) format: From 9019f2fbd7f2878c7ea94ee632e06476d851b866 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 5 Mar 2026 10:52:59 +0100 Subject: [PATCH 160/204] add style="text-align: left;" to the examples of the `html` format output --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index c939d48a..5d2e0f9b 100644 --- a/README.md +++ b/README.md @@ -604,12 +604,12 @@ and a .str property so that the raw HTML remains accessible. >>> print(tabulate(table, headers, tablefmt="html"))
strings numbers
strings numbers
spam 41.9999
- + - - - + + +
item qty
item qty
spam 42
eggs 451
bacon 0
spam 42
eggs 451
bacon 0
From 0c7d5012ed9c66137d6c0c6c83a552339098e57e Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 5 Mar 2026 11:15:46 +0100 Subject: [PATCH 161/204] fix examples in README.md to pass doctests --- README.md | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 5d2e0f9b..b6bb8eba 100644 --- a/README.md +++ b/README.md @@ -502,10 +502,10 @@ format: >>> print(tabulate(table, headers, tablefmt="asciidoc")) [cols="<8,>7",options="header"] |==== -| item | qty -| spam | 42 -| eggs | 451 -| bacon | 0 +| item | qty +| spam | 42 +| eggs | 451 +| bacon | 0 |==== ``` @@ -576,10 +576,10 @@ MediaWiki-based sites: ```pycon >>> print(tabulate(table, headers, tablefmt="moinmoin")) -|| ''' item ''' || ''' qty ''' || -|| spam || 42 || -|| eggs || 451 || -|| bacon || 0 || +|| ''' item ''' || ''' qty ''' || +|| spam || 42 || +|| eggs || 451 || +|| bacon || 0 || ``` @@ -1068,12 +1068,17 @@ If false, only whitespaces will be considered as potentially good places for lin | John Smith | Middle- | | | Manager | +------------+---------+ + +``` + +```pycon >>> print(tabulate([["John Smith", "Middle-Manager"]], headers=["Name", "Title"], tablefmt="grid", maxcolwidths=[None, 5], break_long_words=False, break_on_hyphens=False)) +------------+----------------+ | Name | Title | +============+================+ | John Smith | Middle-Manager | +------------+----------------+ + ``` ### Adding Separating lines From 26ccb780f4ae05995485e6f3199bcc5f7214decf Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 5 Mar 2026 11:16:12 +0100 Subject: [PATCH 162/204] add README doctests to tox tests and github actions --- .github/workflows/tabulate.yml | 2 +- tox.ini | 30 +++++++++++++++--------------- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/.github/workflows/tabulate.yml b/.github/workflows/tabulate.yml index 5458c382..1e2577bb 100644 --- a/.github/workflows/tabulate.yml +++ b/.github/workflows/tabulate.yml @@ -26,7 +26,7 @@ jobs: python -m pip install pytest pytest-cov numpy pandas "wcwidth>=0.6.0" - name: Run tests run: | - pytest -v --doctest-modules --ignore benchmark --cov=tabulate --cov-branch --cov-report=xml + pytest -v --doctest-modules --ignore benchmark --doctest-glob="README.md" --cov=tabulate --cov-branch --cov-report=xml - name: Upload coverage reports to Codecov uses: codecov/codecov-action@v5 with: diff --git a/tox.ini b/tox.ini index 476c57b8..3dcc7300 100644 --- a/tox.ini +++ b/tox.ini @@ -20,7 +20,7 @@ python = 3.14: py314-extra [testenv] -commands = pytest -v --doctest-modules --ignore benchmark {posargs} +commands = pytest -v --doctest-modules --ignore benchmark --doctest-glob="README.md" {posargs} deps = pytest passenv = @@ -37,13 +37,13 @@ deps = [testenv:py38] basepython = python3.8 -commands = pytest -v --doctest-modules --ignore benchmark {posargs} +commands = pytest -v --doctest-modules --ignore benchmark --doctest-glob="README.md" {posargs} deps = pytest [testenv:py38-extra] basepython = python3.8 -commands = pytest -v --doctest-modules --ignore benchmark {posargs} +commands = pytest -v --doctest-modules --ignore benchmark --doctest-glob="README.md" {posargs} deps = pytest numpy @@ -53,13 +53,13 @@ deps = [testenv:py39] basepython = python3.9 -commands = pytest -v --doctest-modules --ignore benchmark {posargs} +commands = pytest -v --doctest-modules --ignore benchmark --doctest-glob="README.md" {posargs} deps = pytest [testenv:py39-extra] basepython = python3.9 -commands = pytest -v --doctest-modules --ignore benchmark {posargs} +commands = pytest -v --doctest-modules --ignore benchmark --doctest-glob="README.md" {posargs} deps = pytest numpy @@ -69,14 +69,14 @@ deps = [testenv:py310] basepython = python3.10 -commands = pytest -v --doctest-modules --ignore benchmark {posargs} +commands = pytest -v --doctest-modules --ignore benchmark --doctest-glob="README.md" {posargs} deps = pytest [testenv:py310-extra] basepython = python3.10 setenv = PYTHONDEVMODE = 1 -commands = pytest -v --doctest-modules --ignore benchmark {posargs} +commands = pytest -v --doctest-modules --ignore benchmark --doctest-glob="README.md" {posargs} deps = pytest numpy @@ -86,14 +86,14 @@ deps = [testenv:py311] basepython = python3.11 -commands = pytest -v --doctest-modules --ignore benchmark {posargs} +commands = pytest -v --doctest-modules --ignore benchmark --doctest-glob="README.md" {posargs} deps = pytest [testenv:py311-extra] basepython = python3.11 setenv = PYTHONDEVMODE = 1 -commands = pytest -v --doctest-modules --ignore benchmark {posargs} +commands = pytest -v --doctest-modules --ignore benchmark --doctest-glob="README.md" {posargs} deps = pytest numpy @@ -102,14 +102,14 @@ deps = [testenv:py312] basepython = python3.12 -commands = pytest -v --doctest-modules --ignore benchmark {posargs} +commands = pytest -v --doctest-modules --ignore benchmark --doctest-glob="README.md" {posargs} deps = pytest [testenv:py312-extra] basepython = python3.12 setenv = PYTHONDEVMODE = 1 -commands = pytest -v --doctest-modules --ignore benchmark {posargs} +commands = pytest -v --doctest-modules --ignore benchmark --doctest-glob="README.md" {posargs} deps = pytest numpy @@ -118,14 +118,14 @@ deps = [testenv:py313] basepython = python3.13 -commands = pytest -v --doctest-modules --ignore benchmark {posargs} +commands = pytest -v --doctest-modules --ignore benchmark --doctest-glob="README.md" {posargs} deps = pytest [testenv:py313-extra] basepython = python3.13 setenv = PYTHONDEVMODE = 1 -commands = pytest -v --doctest-modules --ignore benchmark {posargs} +commands = pytest -v --doctest-modules --ignore benchmark --doctest-glob="README.md" {posargs} deps = pytest numpy @@ -134,14 +134,14 @@ deps = [testenv:py314] basepython = python3.14 -commands = pytest -v --doctest-modules --ignore benchmark {posargs} +commands = pytest -v --doctest-modules --ignore benchmark --doctest-glob="README.md" {posargs} deps = pytest [testenv:py314-extra] basepython = python3.14 setenv = PYTHONDEVMODE = 1 -commands = pytest -v --doctest-modules --ignore benchmark {posargs} +commands = pytest -v --doctest-modules --ignore benchmark --doctest-glob="README.md" {posargs} deps = pytest numpy From d4c0ef0422ea7fbf5c4cdd5905ae2e0860a8abda Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 5 Mar 2026 09:39:27 +0100 Subject: [PATCH 163/204] Enforce ruff/isort rules (I) --- pyproject.toml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 95fddcaf..2ba8dade 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -47,8 +47,13 @@ dev = [ line-length = 99 [tool.ruff.lint] -extend-select = ["W", "C90"] +extend-select = ["W", "I", "C90"] ignore = ["E721", "C901"] [tool.ruff.lint.mccabe] max-complexity = 22 + +[tool.ruff.lint.isort] +combine-as-imports = true +force-sort-within-sections = true +known-local-folder = ["common"] From f1a64ecd81a1c5c31f4d5899bb7060acd1a5e499 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 5 Mar 2026 09:40:21 +0100 Subject: [PATCH 164/204] Apply ruff/isort rule I001 --- benchmark/benchmark.py | 6 ++++-- tabulate/__init__.py | 14 +++++++------- test/common.py | 5 +++-- test/test_api.py | 6 +++--- test/test_cli.py | 6 +----- test/test_input.py | 3 ++- test/test_internal.py | 2 +- test/test_output.py | 6 ++++-- test/test_regression.py | 3 ++- test/test_textwrapper.py | 6 +++--- 10 files changed, 30 insertions(+), 27 deletions(-) diff --git a/benchmark/benchmark.py b/benchmark/benchmark.py index 03dfa66c..2fd1e3a7 100644 --- a/benchmark/benchmark.py +++ b/benchmark/benchmark.py @@ -1,8 +1,10 @@ +import sys from timeit import timeit -import tabulate + import prettytable import texttable -import sys + +import tabulate setup_code = r""" from csv import writer diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 249b3ff8..9e487857 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1,8 +1,8 @@ """Pretty-print tabular data.""" from importlib.metadata import ( - version as _version, PackageNotFoundError as _PackageNotFoundError, + version as _version, ) try: @@ -10,19 +10,19 @@ except _PackageNotFoundError: __version__ = "unknown" -import warnings from collections import namedtuple from collections.abc import Iterable, Sized +import dataclasses from decimal import Decimal +from functools import partial, reduce from html import escape as htmlescape -from itertools import chain, zip_longest as izip_longest -from functools import reduce, partial import io -import re +from itertools import chain, zip_longest as izip_longest import math -import textwrap -import dataclasses +import re import sys +import textwrap +import warnings try: import wcwidth # optional wide-character (CJK) support diff --git a/test/common.py b/test/common.py index 31d6b82c..b557b850 100644 --- a/test/common.py +++ b/test/common.py @@ -1,7 +1,8 @@ -import pytest # noqa: F401 -from pytest import skip, raises # noqa: F401 import warnings +import pytest # noqa: F401 +from pytest import raises, skip # noqa: F401 + def assert_equal(expected, result): print("Expected:\n%r\n" % expected) diff --git a/test/test_api.py b/test/test_api.py index 512a84d6..3e0963a2 100644 --- a/test/test_api.py +++ b/test/test_api.py @@ -1,11 +1,11 @@ """API properties.""" -from tabulate import tabulate, tabulate_formats, simple_separated_format -from common import skip +from tabulate import simple_separated_format, tabulate, tabulate_formats +from common import skip try: - from inspect import signature, _empty + from inspect import _empty, signature except ImportError: signature = None _empty = None diff --git a/test/test_cli.py b/test/test_cli.py index 2f7faa81..625eea11 100644 --- a/test/test_cli.py +++ b/test/test_cli.py @@ -1,16 +1,12 @@ """Command-line interface.""" import os -import sys - - import subprocess +import sys import tempfile - from common import assert_equal - SAMPLE_SIMPLE_FORMAT = "\n".join( [ "----- ------ -------------", diff --git a/test/test_input.py b/test/test_input.py index c2d19c5d..908d8d7e 100644 --- a/test/test_input.py +++ b/test/test_input.py @@ -1,6 +1,7 @@ """Test support of the various forms of tabular data.""" -from tabulate import tabulate, SEPARATING_LINE +from tabulate import SEPARATING_LINE, tabulate + from common import assert_equal, assert_in, raises, skip try: diff --git a/test/test_internal.py b/test/test_internal.py index 5d521d04..49ae0ba6 100644 --- a/test/test_internal.py +++ b/test/test_internal.py @@ -2,7 +2,7 @@ import tabulate as T -from common import assert_equal, skip, rows_to_pipe_table_str, cols_to_pipe_str +from common import assert_equal, cols_to_pipe_str, rows_to_pipe_table_str, skip def test_multiline_width(): diff --git a/test/test_output.py b/test/test_output.py index 93de112e..088dff7e 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -1,10 +1,12 @@ """Test output of the various forms of tabular data.""" from decimal import Decimal + from pytest import mark -from common import assert_equal, raises, skip, check_warnings -from tabulate import tabulate, simple_separated_format, SEPARATING_LINE +from tabulate import SEPARATING_LINE, simple_separated_format, tabulate + +from common import assert_equal, check_warnings, raises, skip # _test_table shows # - coercion of a string to a number, diff --git a/test/test_regression.py b/test/test_regression.py index de950b30..c23d34dc 100644 --- a/test/test_regression.py +++ b/test/test_regression.py @@ -1,6 +1,7 @@ """Regression tests.""" -from tabulate import tabulate, TableFormat, Line, DataRow +from tabulate import DataRow, Line, TableFormat, tabulate + from common import assert_equal, skip diff --git a/test/test_textwrapper.py b/test/test_textwrapper.py index 7cd1581c..41f523cf 100644 --- a/test/test_textwrapper.py +++ b/test/test_textwrapper.py @@ -1,11 +1,11 @@ """Discretely test functionality of our custom TextWrapper""" import datetime - -from tabulate import _CustomTextWrap as CTW, tabulate, _strip_ansi from textwrap import TextWrapper as OTW -from common import skip, assert_equal +from tabulate import _CustomTextWrap as CTW, _strip_ansi, tabulate + +from common import assert_equal, skip def test_wrap_multiword_non_wide(): From 47e97ae44ccfe909a7c7553f2bbc1a1d2adce32f Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 5 Mar 2026 09:59:28 +0100 Subject: [PATCH 165/204] Proper initialization for `__version__` Also, AppVeyor is not used any more, is it? --- tabulate/__init__.py | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 9e487857..f4ba6ac5 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -8,7 +8,10 @@ try: __version__ = _version("tabulate") except _PackageNotFoundError: - __version__ = "unknown" + try: + from .version import version as __version__ # noqa: F401 + except ImportError: + __version__ = "unknown" from collections import namedtuple from collections.abc import Iterable, Sized @@ -35,11 +38,6 @@ def _is_file(f): __all__ = ["tabulate", "tabulate_formats", "simple_separated_format"] -try: - from .version import version as __version__ # noqa: F401 -except ImportError: - pass # running __init__.py as a script, AppVeyor pytests - # minimum extra space in headers MIN_PADDING = 2 From f19e02ba196fc7f67709312d00723ecd152aa532 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 5 Mar 2026 10:16:15 +0100 Subject: [PATCH 166/204] Apply ruff preview rule RUF010 Use explicit conversion flag --- test/test_textwrapper.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_textwrapper.py b/test/test_textwrapper.py index 41f523cf..e6bab0f5 100644 --- a/test/test_textwrapper.py +++ b/test/test_textwrapper.py @@ -341,7 +341,7 @@ def test_wrap_wide_char_no_column_overflow(): for line in lines: display_width = wcwidth.wcswidth(line) assert display_width <= width, ( - f"Line {repr(line)} has display width {display_width} " + f"Line {line!r} has display width {display_width} " f"which exceeds requested column width {width}" ) From 0dc72a90939d0f8355b10a1472db522db95cce66 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 5 Mar 2026 10:21:34 +0100 Subject: [PATCH 167/204] Apply ruff/Pylint preview rule PLR0402 Use `from ... import ...` in lieu of alias --- test/test_grapheme_clusters.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_grapheme_clusters.py b/test/test_grapheme_clusters.py index 0a032b0d..ef6d4e7a 100644 --- a/test/test_grapheme_clusters.py +++ b/test/test_grapheme_clusters.py @@ -1,6 +1,6 @@ """Tests for Unicode grapheme cluster handling in tabulate.""" -import unittest.mock as mock +from unittest import mock import pytest From 3fcf88e36c13073c2157ca435c0125c4a662dcf0 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 5 Mar 2026 10:28:42 +0100 Subject: [PATCH 168/204] Use `is` to compare types This is consistent with other similar checks in the code base. --- tabulate/__init__.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index f4ba6ac5..c3f60d34 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -124,13 +124,11 @@ def _is_separating_line_value(value): def _is_separating_line(row): row_type = type(row) - is_sl = (row_type == list or row_type == str) and ( + return (row_type is list or row_type is str) and ( (len(row) >= 1 and _is_separating_line_value(row[0])) or (len(row) >= 2 and _is_separating_line_value(row[1])) ) - return is_sl - def _pipe_segment_with_colons(align, colwidth): """Return a segment of a horizontal line with optional colons which From ffac028f30000ee2d308b0457a0682d05eca14a7 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 5 Mar 2026 10:10:30 +0100 Subject: [PATCH 169/204] Apply ruff/flake8-implicit-str-concat rule ISC003 Explicitly concatenated string should be implicitly concatenated --- tabulate/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index c3f60d34..b0810a95 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -300,7 +300,7 @@ def make_header_line(is_header, colwidths, colaligns): else: raise ValueError( "_asciidoc_row() requires two (colwidths, colaligns) " - + "or three (cell_values, colwidths, colaligns) arguments) " + "or three (cell_values, colwidths, colaligns) arguments) " ) @@ -1409,7 +1409,7 @@ def _prepend_row_index(rows, index): if isinstance(index, Sized) and len(index) != len(rows): raise ValueError( "index must be as long as the number of data rows: " - + f"len(index)={len(index)} len(rows)={len(rows)}" + f"len(index)={len(index)} len(rows)={len(rows)}" ) sans_rows, separating_lines = _remove_separating_lines(rows) new_rows = [] From ce6758741f33a38a1807affae1a1e3dc544cc56c Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 5 Mar 2026 10:11:55 +0100 Subject: [PATCH 170/204] Enforce ruff/flake8-implicit-str-concat rules (ISC) --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 2ba8dade..600114b2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -47,7 +47,7 @@ dev = [ line-length = 99 [tool.ruff.lint] -extend-select = ["W", "I", "C90"] +extend-select = ["W", "ISC", "I", "C90"] ignore = ["E721", "C901"] [tool.ruff.lint.mccabe] From 6050befd1f8dc7981b378cdf1eb04dcb67ebb9f9 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 5 Mar 2026 10:43:55 +0100 Subject: [PATCH 171/204] =?UTF-8?q?setuptools=20=E2=86=92=20flit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Also: - Write package version to `_version.py` instead of `version.py`. - Get rid of the `README` symlink, `README.md` is good enough nowadays. - I have deliberately removed from the sdist: hidden files, `HOWTOPUBLISH` and `benchmark`. --- HOWTOPUBLISH | 4 ++-- MANIFEST.in | 6 ------ README | 1 - pyproject.toml | 10 ++++++++-- 4 files changed, 10 insertions(+), 11 deletions(-) delete mode 100644 MANIFEST.in delete mode 120000 README diff --git a/HOWTOPUBLISH b/HOWTOPUBLISH index a5b0fb40..24203ded 100644 --- a/HOWTOPUBLISH +++ b/HOWTOPUBLISH @@ -3,12 +3,12 @@ python -m pre_commit run -a # and then commit changes tox -e py310-extra,py311-extra,py312-extra,py313-extra,py314-extra # tag version release (vX.Y.Z) python -m pip install build twine -python -m build -s # this will update tabulate/version.py +python -m build -s # this will update tabulate/_version.py python -m pip install . # install tabulate in the current venv python -m pip install -r benchmark/requirements.txt python benchmark/benchmark.py # then update README # move tag to the last commit -python -m build -s # update tabulate/version.py +python -m build -s # update tabulate/_version.py python -m build -nswx . git push # wait for all CI builds to succeed git push --tags # if CI builds succeed diff --git a/MANIFEST.in b/MANIFEST.in deleted file mode 100644 index 90c057b7..00000000 --- a/MANIFEST.in +++ /dev/null @@ -1,6 +0,0 @@ -include LICENSE -include README -include README.md -include CHANGELOG -include test/common.py -include benchmark.py diff --git a/README b/README deleted file mode 120000 index 42061c01..00000000 --- a/README +++ /dev/null @@ -1 +0,0 @@ -README.md \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml index 600114b2..2a80daa5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [build-system] -requires = ["setuptools>=77.0.3", "setuptools_scm[toml]>=3.4.3"] -build-backend = "setuptools.build_meta" +requires = ["flit>=3.12", "flit_scm"] +build-backend = "flit_scm:buildapi" [project] name = "tabulate" @@ -32,7 +32,12 @@ widechars = ["wcwidth>=0.6.0"] [project.scripts] tabulate = "tabulate:_main" +[tool.flit.sdist] +include = ["CHANGELOG", "test/", "tox.ini"] +exclude = ["tabulate/_version.py"] + [tool.setuptools_scm] +write_to = "tabulate/_version.py" [dependency-groups] dev = [ @@ -45,6 +50,7 @@ dev = [ [tool.ruff] line-length = 99 +exclude = ["tabulate/_version.py"] [tool.ruff.lint] extend-select = ["W", "ISC", "I", "C90"] From 2939dc1d17e13a71c256042d9ad46bfd9d8a07b8 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 5 Mar 2026 14:42:03 +0100 Subject: [PATCH 172/204] add pre_commit to dev dependencies --- pyproject.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/pyproject.toml b/pyproject.toml index 2a80daa5..b328c93f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -43,6 +43,7 @@ write_to = "tabulate/_version.py" dev = [ "build>=1.4.0", "ruff>=0.15.4", + "pre_commit>=4.5.1", "tox>=4.47.3", "tox-uv>=1.0", "twine>=6.2.0", From 3aa568c66987dbc97c079c6a2e4bd0ad362a949f Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 5 Mar 2026 14:52:01 +0100 Subject: [PATCH 173/204] fix #408 - remove trailing whitespace from asciidoc output --- README.md | 8 ++++---- tabulate/__init__.py | 11 +++++++---- test/test_output.py | 10 +++++----- test/test_regression.py | 11 +++++++++++ 4 files changed, 27 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index b6bb8eba..e8f47d73 100644 --- a/README.md +++ b/README.md @@ -502,10 +502,10 @@ format: >>> print(tabulate(table, headers, tablefmt="asciidoc")) [cols="<8,>7",options="header"] |==== -| item | qty -| spam | 42 -| eggs | 451 -| bacon | 0 +| item | qty +| spam | 42 +| eggs | 451 +| bacon | 0 |==== ``` diff --git a/tabulate/__init__.py b/tabulate/__init__.py index b0810a95..0d2d59d4 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -278,12 +278,14 @@ def make_header_line(is_header, colwidths, colaligns): # generate the list of entries in the table header field - return "[{}]\n|====".format(",".join(header_list)) + line = "[{}]\n|====".format(",".join(header_list)) + return line.rstrip() if len(args) == 2: # two arguments are passed if called in the context of aboveline # print the table header with column widths and optional header tag - return make_header_line(False, *args) + line = make_header_line(False, *args) + return line.rstrip() elif len(args) == 3: # three arguments are passed if called in the context of dataline or headerline @@ -293,9 +295,10 @@ def make_header_line(is_header, colwidths, colaligns): data_line = "|" + "|".join(cell_values) if is_header: - return make_header_line(True, colwidths, colaligns) + "\n" + data_line + line = make_header_line(True, colwidths, colaligns) + "\n" + data_line + return line.rstrip() else: - return data_line + return data_line.rstrip() else: raise ValueError( diff --git a/test/test_output.py b/test/test_output.py index 088dff7e..e49674f9 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -2088,9 +2088,9 @@ def test_asciidoc(): [ '[cols="<11,>11",options="header"]', "|====", - "| strings | numbers ", - "| spam | 41.9999 ", - "| eggs | 451 ", + "| strings | numbers", + "| spam | 41.9999", + "| eggs | 451", "|====", ] ) @@ -2104,8 +2104,8 @@ def test_asciidoc_headerless(): [ '[cols="<6,>10"]', "|====", - "| spam | 41.9999 ", - "| eggs | 451 ", + "| spam | 41.9999", + "| eggs | 451", "|====", ] ) diff --git a/test/test_regression.py b/test/test_regression.py index c23d34dc..67ef59f4 100644 --- a/test/test_regression.py +++ b/test/test_regression.py @@ -580,3 +580,14 @@ def test_mixed_bool_strings_and_numeric_strings(): result = tabulate([["False"], ["1."]]) expected = "\n".join(["-----", "False", " 1", "-----"]) assert_equal(expected, result) + + +def test_asciidoc_without_trailing_whitespace(): + "Regression: asciidoc format output must not generate trailing whitespace (issue #408)" + result = tabulate([["foo"]], headers=("longheader",), tablefmt="asciidoc") + expected = '[cols="<14",options="header"]\n|====\n| longheader\n| foo\n|====' + assert_equal(expected, result) + + result = tabulate([["longtext"]], headers=("bar",), tablefmt="asciidoc") + expected = '[cols="<10",options="header"]\n|====\n| bar\n| longtext\n|====' + assert_equal(expected, result) From 7c70bf451bc00ba64c3d8587909fa08d16a958e0 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 5 Mar 2026 14:59:13 +0100 Subject: [PATCH 174/204] update CHANGELOG --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index a82abc0a..940582a1 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,6 +1,7 @@ - 0.11.0: Drop support of the legacy `youtrack` format. Add support of the `Decimal` data type. + Improve output of `github` and `asciidoc` formats. Various bug fixes. - 0.10.0: Add support for Python 3.11, 3.12, 3.13, 3.14. Drop support for Python 3.7, 3.8, 3.9. From 8014ec66820c89307005b26f878119baa5bf6932 Mon Sep 17 00:00:00 2001 From: Kevin Deldycke Date: Thu, 5 Mar 2026 16:02:56 +0400 Subject: [PATCH 175/204] Fix alignments in `github` tables Closes #53, follow-up on #261 --- README.md | 4 ++-- tabulate/__init__.py | 14 ++++--------- test/test_output.py | 47 ++++++++++++++++++++++++++++++++++++++++---- 3 files changed, 49 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index e8f47d73..d4123284 100644 --- a/README.md +++ b/README.md @@ -233,12 +233,12 @@ bacon 0 ``` `github` follows the conventions of GitHub flavored Markdown. It -corresponds to the `pipe` format without alignment colons: +corresponds to the `pipe` format with the same alignment colons: ```pycon >>> print(tabulate(table, headers, tablefmt="github")) | item | qty | -|--------|-------| +|:-------|------:| | spam | 42 | | eggs | 451 | | bacon | 0 | diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 0d2d59d4..d83dbc4e 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -522,16 +522,6 @@ def escape_empty(val): padding=1, with_header_hide=None, ), - "github": TableFormat( - lineabove=Line("|", "-", "|", "|"), - linebelowheader=Line("|", "-", "|", "|"), - linebetweenrows=None, - linebelow=None, - headerrow=DataRow("|", "|", "|"), - datarow=DataRow("|", "|", "|"), - padding=1, - with_header_hide=["lineabove"], - ), "pipe": TableFormat( lineabove=_pipe_line_with_colons, linebelowheader=_pipe_line_with_colons, @@ -719,6 +709,10 @@ def escape_empty(val): ), } +# "github" is an alias for "pipe": both produce GitHub-flavored Markdown with +# alignment colons in the separator row. +_table_formats["github"] = _table_formats["pipe"] + tabulate_formats = sorted(_table_formats.keys()) diff --git a/test/test_output.py b/test/test_output.py index e49674f9..ea3da87f 100644 --- a/test/test_output.py +++ b/test/test_output.py @@ -369,9 +369,9 @@ def test_simple_headerless_with_sep_line_with_padding_in_tablefmt(): "Output: simple without headers with sep line with padding in tablefmt" expected = "\n".join( [ - "|------|----------|", + "|:-----|---------:|", "| spam | 41.9999 |", - "|------|----------|", + "|:-----|---------:|", "| eggs | 451 |", ] ) @@ -489,7 +489,7 @@ def test_github(): expected = "\n".join( [ "| strings | numbers |", - "|-----------|-----------|", + "|:----------|----------:|", "| spam | 41.9999 |", "| eggs | 451 |", ] @@ -506,7 +506,7 @@ def test_github_multiline(): [ "| more | more spam |", "| spam eggs | & eggs |", - "|-------------|-------------|", + "|------------:|:------------|", "| 2 | foo |", "| | bar |", ] @@ -515,6 +515,45 @@ def test_github_multiline(): assert_equal(expected, result) +def test_github_with_colalign(): + "Output: github with explicit column alignment" + expected = "\n".join( + [ + "| Name | Age |", + "|:-------|------:|", + "| Alice | 24 |", + "| Bob | 19 |", + ] + ) + result = tabulate( + [["Alice", 24], ["Bob", 19]], + ["Name", "Age"], + tablefmt="github", + colalign=("left", "right"), + ) + assert_equal(expected, result) + + +def test_github_no_alignment(): + "Output: github without alignment hints when numalign/stralign are disabled" + expected = "\n".join( + [ + "| strings | numbers |", + "|-----------|-----------|", + "| spam | 41.9999 |", + "| eggs | 451 |", + ] + ) + result = tabulate( + _test_table, + _test_table_headers, + tablefmt="github", + numalign=None, + stralign=None, + ) + assert_equal(expected, result) + + def test_grid(): "Output: grid with headers" expected = "\n".join( From ce67960bdaa0ba13fc8648dd5ae21a259d155459 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 5 Mar 2026 10:56:30 +0100 Subject: [PATCH 176/204] Apply ruff/flake8-comprehensions C416 Unnecessary list comprehension (rewrite using `list()`) --- tabulate/__init__.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index d83dbc4e..0115579c 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -2378,7 +2378,7 @@ def tabulate( assert isinstance(colalign, Iterable) if isinstance(colalign, str): warnings.warn( - f"As a string, `colalign` is interpreted as {[c for c in colalign]}. " + f"As a string, `colalign` is interpreted as {list(colalign)}. " f'Did you mean `colglobalalign = "{colalign}"` or `colalign = ("{colalign}",)`?', stacklevel=2, ) @@ -2420,7 +2420,7 @@ def tabulate( assert isinstance(headersalign, Iterable) if isinstance(headersalign, str): warnings.warn( - f"As a string, `headersalign` is interpreted as {[c for c in headersalign]}. " + f"As a string, `headersalign` is interpreted as {list(headersalign)}. " f'Did you mean `headersglobalalign = "{headersalign}"` ' f'or `headersalign = ("{headersalign}",)`?', stacklevel=2, @@ -2699,7 +2699,7 @@ def _update_lines(self, lines, new_line): as add any colors from previous lines order to preserve the same formatting as a single unwrapped string. """ - code_matches = [x for x in _ansi_codes.finditer(new_line)] + code_matches = list(_ansi_codes.finditer(new_line)) color_codes = [code.string[code.span()[0] : code.span()[1]] for code in code_matches] # Add color codes from earlier in the unwrapped line, and then track any new ones we add. From e9a56a653046d906ad7ac070618d5006d61b90d7 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 5 Mar 2026 10:41:07 +0100 Subject: [PATCH 177/204] Apply ruff/flake8-comprehensions rule C417 Unnecessary `map()` usage (rewrite using a list comprehension) --- benchmark/benchmark.py | 2 +- tabulate/__init__.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/benchmark/benchmark.py b/benchmark/benchmark.py index 2fd1e3a7..d405f5c7 100644 --- a/benchmark/benchmark.py +++ b/benchmark/benchmark.py @@ -75,7 +75,7 @@ def benchmark(n): methods = [m for m in methods if m[0].startswith("tabulate")] results = [(desc, timeit(code, setup_code, number=n) / n * 1e6) for desc, code in methods] - mintime = min(map(lambda x: x[1], results)) + mintime = min(x[1] for x in results) results = [(desc, t, t / mintime) for desc, t in sorted(results, key=lambda x: x[1])] table = tabulate.tabulate( results, ["Table formatter", "time, μs", "rel. time"], "rst", floatfmt=".1f" diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 0115579c..de774e86 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1589,7 +1589,7 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"): headers = list(map(str, headers)) # rows = list(map(list, rows)) - rows = list(map(lambda r: r if _is_separating_line(r) else list(r), rows)) + rows = [r if _is_separating_line(r) else list(r) for r in rows] # add or remove an index column showindex_is_a_str = type(showindex) in [str, bytes] From 57e39b13160cf7fcc0373b14f2df86c1e7826fae Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 5 Mar 2026 10:41:53 +0100 Subject: [PATCH 178/204] Apply ruff/flake8-comprehensions rule C419 Unnecessary list comprehension --- test/common.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/common.py b/test/common.py index b557b850..5f00852a 100644 --- a/test/common.py +++ b/test/common.py @@ -41,6 +41,6 @@ def check_warnings(func_args_kwargs, *, num=None, category=None, contain=None): if num is not None: assert len(W) == num if category is not None: - assert all([issubclass(w.category, category) for w in W]) + 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]) + assert all(contain in str(w.message) for w in W) From 26269e6b3c9362340845488715fcd3bebf2876b2 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 5 Mar 2026 10:57:48 +0100 Subject: [PATCH 179/204] Apply ruff/flake8-comprehensions rule C420 Unnecessary dict comprehension for iterable; use `dict.fromkeys` instead --- test/test_regression.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_regression.py b/test/test_regression.py index 67ef59f4..c3dfac9d 100644 --- a/test/test_regression.py +++ b/test/test_regression.py @@ -171,7 +171,7 @@ def test_numeric_column_headers(): expected = " 42\n----\n 1\n 2" assert_equal(expected, result) - lod = [{p: i for p in range(5)} for i in range(5)] + lod = [dict.fromkeys(range(5), i) for i in range(5)] result = tabulate(lod, "keys") expected = "\n".join( [ From 527d31ed0c5a71418ecc8fc34dcfe6453acd35f1 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 5 Mar 2026 10:45:28 +0100 Subject: [PATCH 180/204] Enforce ruff/flake8-comprehensions rules (C4) --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index b328c93f..d510943e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -54,7 +54,7 @@ line-length = 99 exclude = ["tabulate/_version.py"] [tool.ruff.lint] -extend-select = ["W", "ISC", "I", "C90"] +extend-select = ["W", "C4", "ISC", "I", "C90"] ignore = ["E721", "C901"] [tool.ruff.lint.mccabe] From 86112e6de997a9eb3dc1bf4e9a004bcf25ad680a Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 5 Mar 2026 15:11:41 +0100 Subject: [PATCH 181/204] add [too.pytest.ini_options] to pyproject.toml --- pyproject.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index d510943e..0c9e04c1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -49,6 +49,9 @@ dev = [ "twine>=6.2.0", ] +[tool.pytest.ini_options] +addopts = "-v --doctest-modules --ignore=benchmark --doctest-glob=README.md" + [tool.ruff] line-length = 99 exclude = ["tabulate/_version.py"] From a783de20125f1168e8870d700f24f4bf0249ae4b Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 5 Mar 2026 15:17:42 +0100 Subject: [PATCH 182/204] add regression test for unescaped pipe character in github output (issue #241) --- test/test_regression.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/test/test_regression.py b/test/test_regression.py index c3dfac9d..a0b8c57b 100644 --- a/test/test_regression.py +++ b/test/test_regression.py @@ -591,3 +591,10 @@ def test_asciidoc_without_trailing_whitespace(): result = tabulate([["longtext"]], headers=("bar",), tablefmt="asciidoc") expected = '[cols="<10",options="header"]\n|====\n| bar\n| longtext\n|====' assert_equal(expected, result) + + +def test_github_escape_pipe_character(): + "Regression: github format must escape pipe character with a backslash (issue #241)" + result = tabulate([["foo|bar"]], headers=("spam|eggs",), tablefmt="github") + expected = '| spam\\|eggs |\n|-------------|\n| foo\\|bar |' + assert_equal(expected, result) From 8abc5c92c618aa78ac4e8aca488402cbfcf03801 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 5 Mar 2026 15:41:02 +0100 Subject: [PATCH 183/204] ignore _version.py --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 0495ac79..8ba99796 100644 --- a/.gitignore +++ b/.gitignore @@ -19,3 +19,4 @@ website-build/ ## Unit test / coverage reports .coverage .tox +/tabulate/_version.py From 46c9fe38d36e1f185271884ace2e80415389216c Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 5 Mar 2026 15:42:52 +0100 Subject: [PATCH 184/204] replace DataRow namedtuple with a dataclass with the same name and an optional escape_map generalize LaTeX escaping function, move escaping to _build_simple_row --- tabulate/__init__.py | 43 ++++++++++++++++++++++++++++--------------- 1 file changed, 28 insertions(+), 15 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index de774e86..4c358a90 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -4,6 +4,7 @@ PackageNotFoundError as _PackageNotFoundError, version as _version, ) +from typing import Callable, Union try: __version__ = _version("tabulate") @@ -17,6 +18,7 @@ from collections.abc import Iterable, Sized import dataclasses from decimal import Decimal +from dataclasses import dataclass from functools import partial, reduce from html import escape as htmlescape import io @@ -69,7 +71,12 @@ def _is_file(f): Line = namedtuple("Line", ["begin", "hline", "sep", "end"]) -DataRow = namedtuple("DataRow", ["begin", "sep", "end"]) +@dataclass +class DataRow: + begin: str + sep: str + end: str + escape_map: dict = None # A table structure is supposed to be: @@ -323,13 +330,7 @@ def make_header_line(is_header, colwidths, colaligns): } -def _latex_row(cell_values, colwidths, colaligns, escrules=LATEX_ESCAPE_RULES): - def escape_char(c): - return escrules.get(c, c) - - escaped_values = ["".join(map(escape_char, cell)) for cell in cell_values] - rowfmt = DataRow("", "&", "\\\\") - return _build_simple_row(escaped_values, rowfmt) +_latex_row = DataRow("", "&", "\\\\", LATEX_ESCAPE_RULES) def _rst_escape_first_column(rows, headers): @@ -652,8 +653,8 @@ def escape_empty(val): linebelowheader=Line("\\hline", "", "", ""), linebetweenrows=None, linebelow=Line("\\hline\n\\end{tabular}", "", "", ""), - headerrow=partial(_latex_row, escrules={}), - datarow=partial(_latex_row, escrules={}), + headerrow=DataRow("", "&", "\\\\", {}), + datarow=DataRow("", "&", "\\\\", {}), padding=1, with_header_hide=None, ), @@ -2506,13 +2507,24 @@ def _pad_row(cells, padding): return cells -def _build_simple_row(padded_cells, rowfmt): +def _build_simple_row(padded_cells: list[list], rowfmt: DataRow) -> str: "Format row according to DataRow format without padding." - begin, sep, end = rowfmt - return (begin + sep.join(padded_cells) + end).rstrip() + begin = rowfmt.begin + sep = rowfmt.sep + end = rowfmt.end + escape_map: dict = rowfmt.escape_map + + if escape_map: + def escape_char(c): + return escape_map.get(c, c) + escaped_cells = ["".join(map(escape_char, cell)) for cell in padded_cells] + else: + escaped_cells = padded_cells + + return (begin + sep.join(escaped_cells) + end).rstrip() -def _build_row(padded_cells, colwidths, colaligns, rowfmt): +def _build_row(padded_cells: list[list], colwidths: list[int], colaligns: list[str], rowfmt: Union[DataRow, Callable]) -> str: "Return a string which represents a row of data cells." if not rowfmt: return None @@ -2571,7 +2583,8 @@ def _build_line(colwidths, colaligns, linefmt): else: begin, fill, sep, end = linefmt cells = [fill * w for w in colwidths] - return _build_simple_row(cells, (begin, sep, end)) + rowfmt = DataRow(begin, sep, end) + return _build_simple_row(cells, rowfmt) def _append_line(lines, colwidths, colaligns, linefmt): From e6a24aa6e00ca8ce9a1987f28c11ca08c6f19383 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Thu, 5 Mar 2026 15:46:56 +0100 Subject: [PATCH 185/204] fix #241 - escape pipe character in github and pipe formats --- tabulate/__init__.py | 18 ++++++++++++++---- test/test_regression.py | 2 +- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 4c358a90..43146d66 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -17,8 +17,8 @@ from collections import namedtuple from collections.abc import Iterable, Sized import dataclasses -from decimal import Decimal from dataclasses import dataclass +from decimal import Decimal from functools import partial, reduce from html import escape as htmlescape import io @@ -333,6 +333,9 @@ def make_header_line(is_header, colwidths, colaligns): _latex_row = DataRow("", "&", "\\\\", LATEX_ESCAPE_RULES) +GITHUB_ESCAPE_RULES = {r"|": r"\|"} + + def _rst_escape_first_column(rows, headers): def escape_empty(val): if isinstance(val, (str, bytes)) and not val.strip(): @@ -528,8 +531,8 @@ def escape_empty(val): linebelowheader=_pipe_line_with_colons, linebetweenrows=None, linebelow=None, - headerrow=DataRow("|", "|", "|"), - datarow=DataRow("|", "|", "|"), + headerrow=DataRow("|", "|", "|", GITHUB_ESCAPE_RULES), + datarow=DataRow("|", "|", "|", GITHUB_ESCAPE_RULES), padding=1, with_header_hide=["lineabove"], ), @@ -2515,8 +2518,10 @@ def _build_simple_row(padded_cells: list[list], rowfmt: DataRow) -> str: escape_map: dict = rowfmt.escape_map if escape_map: + def escape_char(c): return escape_map.get(c, c) + escaped_cells = ["".join(map(escape_char, cell)) for cell in padded_cells] else: escaped_cells = padded_cells @@ -2524,7 +2529,12 @@ def escape_char(c): return (begin + sep.join(escaped_cells) + end).rstrip() -def _build_row(padded_cells: list[list], colwidths: list[int], colaligns: list[str], rowfmt: Union[DataRow, Callable]) -> str: +def _build_row( + padded_cells: list[list], + colwidths: list[int], + colaligns: list[str], + rowfmt: Union[DataRow, Callable], +) -> str: "Return a string which represents a row of data cells." if not rowfmt: return None diff --git a/test/test_regression.py b/test/test_regression.py index a0b8c57b..051bf031 100644 --- a/test/test_regression.py +++ b/test/test_regression.py @@ -596,5 +596,5 @@ def test_asciidoc_without_trailing_whitespace(): def test_github_escape_pipe_character(): "Regression: github format must escape pipe character with a backslash (issue #241)" result = tabulate([["foo|bar"]], headers=("spam|eggs",), tablefmt="github") - expected = '| spam\\|eggs |\n|-------------|\n| foo\\|bar |' + expected = "| spam\\|eggs |\n|:------------|\n| foo\\|bar |" assert_equal(expected, result) From 4552d6efcd17fd937e64d4851f0ca8cf7a64c7b8 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 5 Mar 2026 10:43:55 +0100 Subject: [PATCH 186/204] A few fixes for flit builds The build backend should be `flit_core`, not `flit`: https://flit.pypa.io/en/stable/pyproject_toml.html#build-system-section File `_version.py` should be part of sdist and wheel distributions. --- .gitignore | 2 +- pyproject.toml | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index 8ba99796..61d0c83e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ -/tabulate/version.py +/tabulate/_version.py build dist diff --git a/pyproject.toml b/pyproject.toml index 0c9e04c1..fb782b8b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,5 +1,5 @@ [build-system] -requires = ["flit>=3.12", "flit_scm"] +requires = ["flit_core>=3.12", "flit_scm"] build-backend = "flit_scm:buildapi" [project] @@ -34,7 +34,6 @@ tabulate = "tabulate:_main" [tool.flit.sdist] include = ["CHANGELOG", "test/", "tox.ini"] -exclude = ["tabulate/_version.py"] [tool.setuptools_scm] write_to = "tabulate/_version.py" From 315f6c17252c9e1d2f81a4a4e55e7c68ec55938b Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 5 Mar 2026 10:43:55 +0100 Subject: [PATCH 187/204] One last fix for flit builds It's `_version.py`, not `version.py` any more. --- tabulate/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 43146d66..e2df82d1 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -7,10 +7,10 @@ from typing import Callable, Union try: - __version__ = _version("tabulate") + __version__ = _version("tabulate") # installed package except _PackageNotFoundError: try: - from .version import version as __version__ # noqa: F401 + from ._version import version as __version__ # editable / source checkout except ImportError: __version__ = "unknown" From 7e3925ec413389892757a2c3acd403b5bd5f5376 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 5 Mar 2026 18:33:11 +0100 Subject: [PATCH 188/204] Stop testing unsupported Python 3.8 and 3.9 Either support Python 3.8 and 3.9 officially and keep testing these versions, or stop testing. This grey area where you don't support versions but still test them just in case doesn't help. For example, ruff targets `requires-python` and generates code that may not be compatible with earlier versions. Such code will break CI tests with unsupported versions of Python. --- tox.ini | 32 -------------------------------- 1 file changed, 32 deletions(-) diff --git a/tox.ini b/tox.ini index 3dcc7300..4a0ae289 100644 --- a/tox.ini +++ b/tox.ini @@ -35,38 +35,6 @@ commands = deps = ruff -[testenv:py38] -basepython = python3.8 -commands = pytest -v --doctest-modules --ignore benchmark --doctest-glob="README.md" {posargs} -deps = - pytest - -[testenv:py38-extra] -basepython = python3.8 -commands = pytest -v --doctest-modules --ignore benchmark --doctest-glob="README.md" {posargs} -deps = - pytest - numpy - pandas - wcwidth - - -[testenv:py39] -basepython = python3.9 -commands = pytest -v --doctest-modules --ignore benchmark --doctest-glob="README.md" {posargs} -deps = - pytest - -[testenv:py39-extra] -basepython = python3.9 -commands = pytest -v --doctest-modules --ignore benchmark --doctest-glob="README.md" {posargs} -deps = - pytest - numpy - pandas - wcwidth - - [testenv:py310] basepython = python3.10 commands = pytest -v --doctest-modules --ignore benchmark --doctest-glob="README.md" {posargs} From 382a933132b0767fcb1624ebc143d4171c9366fc Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 5 Mar 2026 19:42:24 +0100 Subject: [PATCH 189/204] Simplify version and imports --- tabulate/__init__.py | 30 +++++++++++++----------------- 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index e2df82d1..9ee72fe6 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1,19 +1,5 @@ """Pretty-print tabular data.""" -from importlib.metadata import ( - PackageNotFoundError as _PackageNotFoundError, - version as _version, -) -from typing import Callable, Union - -try: - __version__ = _version("tabulate") # installed package -except _PackageNotFoundError: - try: - from ._version import version as __version__ # editable / source checkout - except ImportError: - __version__ = "unknown" - from collections import namedtuple from collections.abc import Iterable, Sized import dataclasses @@ -21,12 +7,14 @@ from decimal import Decimal from functools import partial, reduce from html import escape as htmlescape +from importlib.metadata import PackageNotFoundError, version import io from itertools import chain, zip_longest as izip_longest import math import re import sys import textwrap +from typing import Callable, Union import warnings try: @@ -34,9 +22,13 @@ except ImportError: wcwidth = None - -def _is_file(f): - return isinstance(f, io.IOBase) +try: + __version__ = version("tabulate") # installed package +except PackageNotFoundError: + try: + from ._version import version as __version__ # editable / source checkout + except ImportError: + __version__ = "unknown" __all__ = ["tabulate", "tabulate_formats", "simple_separated_format"] @@ -125,6 +117,10 @@ class DataRow: ) +def _is_file(f): + return isinstance(f, io.IOBase) + + def _is_separating_line_value(value): return type(value) is str and value.strip() == SEPARATING_LINE From 200b7844c9695b5bd80f207875676b55a73a2ad2 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 5 Mar 2026 19:30:20 +0100 Subject: [PATCH 190/204] Use enumerate The resulting code is faster, simpler and more readable. --- test/common.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/test/common.py b/test/common.py index 5f00852a..6afb4be0 100644 --- a/test/common.py +++ b/test/common.py @@ -11,8 +11,7 @@ def assert_equal(expected, result): def assert_in(result, expected_set): - nums = range(1, len(expected_set) + 1) - for i, expected in zip(nums, expected_set): + for i, expected in enumerate(expected_set, start=1): print("Expected %d:\n%s\n" % (i, expected)) print("Got:\n%s\n" % result) assert result in expected_set From 94b7491f7df6fd103f7801a47d527fdf18e13633 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Fri, 6 Mar 2026 11:05:37 +0100 Subject: [PATCH 191/204] Stop testing unsupported Python 3.8 and 3.9 (again) Either support Python 3.8 and 3.9 officially and keep testing these versions, or stop testing. This grey area where you don't support versions but still test them just in case doesn't help. For example, ruff targets `requires-python` and generates code that may not be compatible with earlier versions. Such code will break CI tests with unsupported versions of Python. --- .github/workflows/tabulate.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/tabulate.yml b/.github/workflows/tabulate.yml index 1e2577bb..6913ba3e 100644 --- a/.github/workflows/tabulate.yml +++ b/.github/workflows/tabulate.yml @@ -8,8 +8,7 @@ jobs: build: strategy: matrix: - # Python 3.9 is not supported anymore, but it still works... - python-version: ['3.9', '3.10', '3.11', '3.12', '3.13', '3.14'] + python-version: ['3.10', '3.11', '3.12', '3.13', '3.14'] os: ["ubuntu-latest", "windows-latest", "macos-latest"] runs-on: ${{ matrix.os }} From 164b36740fccadd5bcccbdedc88e9b109d9a9bdd Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Mon, 9 Mar 2026 15:25:15 +0100 Subject: [PATCH 192/204] fix GH103 and GH103 of sp-repo-review recommendations GH102: Auto-cancel on repeated PRs GH103: At least one workflow with manual dispatch trigger --- .github/workflows/tabulate.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/tabulate.yml b/.github/workflows/tabulate.yml index 6913ba3e..81069dc2 100644 --- a/.github/workflows/tabulate.yml +++ b/.github/workflows/tabulate.yml @@ -3,6 +3,7 @@ name: pytest on: - push - pull_request + - workflow_dispatch jobs: build: @@ -30,3 +31,7 @@ jobs: uses: codecov/codecov-action@v5 with: token: ${{ secrets.CODECOV_TOKEN }} + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true From c327d6c41981d3668b96caeb4bab10478c263030 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Mon, 9 Mar 2026 17:06:48 +0100 Subject: [PATCH 193/204] implement support of JSONL and CSV input formats in command line utility fix #173 New CLI parameter: --headers HEADERS where HEADERS can be "firstrow", "keys", "HEADER1,HEADER2,...", "KEY1:HEADER1,KEY2:HEADER2,..." --read FILEFORMAT where FILEFORMAT can be "rsv" (default), "csv", "jsonl" Deprecated CLI parameter: --header Usage examples: cat ./examples/people.csv | tabulate -r csv --headers firstrow id name email "favorite" fruit ---- ------ ----------------- ------------------ 1 Alice alice@example.com apple, kiwi 2 Bob bob@example.com banana, orange, lychee 3 Carol pear cat ./examples/people.jsonl | tabulate -r jsonl -f grid --headers 'id:ID,name:First Name,email:Email' +------+--------------+-------------------+ | ID | First Name | Email | +======+==============+===================+ | 1 | Alice | alice@example.com | +------+--------------+-------------------+ | 2 | Bob | bob@example.com | +------+--------------+-------------------+ --- examples/people.csv | 6 ++ examples/people.jsonl | 2 + tabulate/__init__.py | 132 ++++++++++++++++++++++++++++++++---------- 3 files changed, 109 insertions(+), 31 deletions(-) create mode 100644 examples/people.csv create mode 100644 examples/people.jsonl diff --git a/examples/people.csv b/examples/people.csv new file mode 100644 index 00000000..dfbf6dc5 --- /dev/null +++ b/examples/people.csv @@ -0,0 +1,6 @@ +id,name,email,"""favorite"" fruit" +1,Alice,alice@example.com,"apple, kiwi" +2,Bob,bob@example.com,"banana, +orange, +lychee" +3,Carol,,pear diff --git a/examples/people.jsonl b/examples/people.jsonl new file mode 100644 index 00000000..7f3e1138 --- /dev/null +++ b/examples/people.jsonl @@ -0,0 +1,2 @@ +{"id": 1, "name": "Alice", "email": "alice@example.com"} +{"id": 2, "name": "Bob", "email": "bob@example.com"} \ No newline at end of file diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 9ee72fe6..8911685e 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -2900,8 +2900,7 @@ def _main(): """\ Usage: tabulate [options] [FILE ...] - Pretty-print tabular data. - See also https://github.com/astanin/python-tabulate + Pretty-print tabular data. Use Python module for more features. FILE a filename of the file with tabular data; if "-" or missing, read data from stdin. @@ -2909,16 +2908,35 @@ def _main(): Options: -h, --help show this message - -1, --header use the first row of data as a table header - -o FILE, --output FILE print table to FILE (default: stdout) - -s REGEXP, --sep REGEXP use a custom column separator (default: whitespace) + + INPUT: + -r, --read FILEFORMAT parse input FILEs as: + rsv (REGEXP-separated values, default), + csv (comma-separated valued, Excel dialect), + jsonl (one JSON object per line) + -s REGEXP, --sep REGEXP column separator for rsv data (default: whitespace) + + FORMAT: + --headers HEADERS HEADERS can be one of: + "firstrow" (for csv and rsv data), + "keys" (for jsonl data), + "HEADER1,HEADER2,..." (for csv and rsv data), + "KEY1:HEADER1,KEY2:HEADER2,..." (for jsonl data) + -1 use the first row of input data as a table header + (the same as --headers firstrow) -F FPFMT, --float FPFMT floating point number format (default: g) -I INTFMT, --int INTFMT integer point number format (default: "") - -f FMT, --format FMT set output table format; supported formats: - plain, simple, grid, fancy_grid, pipe, orgtbl, - rst, mediawiki, html, latex, latex_raw, - latex_booktabs, latex_longtable, tsv - (default: simple) + -f FMT, --format FMT set output table format (default: simple) + + Supported output formats: asciidoc, colon_grid, double_grid, double_outline, + fancy_grid, fancy_outline, github, grid, heavy_grid, heavy_outline, html, jira, + latex, latex_booktabs, latex_longtable, latex_raw, mediawiki, mixed_grid, mixed_outline, + moinmoin, orgtbl, outline, pipe, plain, presto, pretty, psql, rounded_grid, + rounded_outline, rst, simple, simple_grid, simple_outline, textile, tsv, unsafehtml. + + OUTPUT: + -o FILE, --output FILE print table to FILE (default: stdout) + """ import getopt @@ -2926,10 +2944,12 @@ def _main(): try: opts, args = getopt.getopt( sys.argv[1:], - "h1o:s:F:I:f:", + "h1H:r:o:s:F:I:f:", [ "help", - "header", + "header", # deprecated in CLI > 0.10 + "headers=", # CLI > 0.10 + "read=", # CLI > 0.10 "output=", "sep=", "float=", @@ -2939,7 +2959,7 @@ def _main(): ], ) except getopt.GetoptError as e: - print(e) + print(e, file=sys.stderr) print(usage) sys.exit(2) headers = [] @@ -2947,11 +2967,20 @@ def _main(): intfmt = _DEFAULT_INTFMT colalign = None tablefmt = "simple" + fileformat = "rsv" sep = r"\s+" outfile = "-" + special_headers_values = ["firstrow", "keys"] for opt, value in opts: if opt in ["-1", "--header"]: + # "header" option is for backwards compatibility with CLI <= 0.10 + # CLI >= 0.11 should user --headers headers = "firstrow" + if opt in ["-H", "--headers"]: + if value in special_headers_values: + headers = value + else: + headers = value # may need to be processed elif opt in ["-o", "--output"]: outfile = value elif opt in ["-F", "--float"]: @@ -2960,9 +2989,11 @@ def _main(): intfmt = value elif opt in ["-C", "--colalign"]: colalign = value.split() + elif opt in ["-r", "--read"]: + fileformat = value.lower() elif opt in ["-f", "--format"]: if value not in tabulate_formats: - print("%s is not a supported table format" % value) + print(f"{value} is not a supported output format", file=sys.stderr) print(usage) sys.exit(3) tablefmt = value @@ -2971,39 +3002,78 @@ def _main(): elif opt in ["-h", "--help"]: print(usage) sys.exit(0) + # choose a reader and parse headers option + if fileformat == "rsv": + reader = partial(_read_rsv_file, sep=sep) + if type(headers) is str and headers not in special_headers_values: + # parse as CSV values + headers = headers.split(",") + elif fileformat == "csv": + reader = _read_csv_file + if type(headers) is str and headers not in special_headers_values: + # parse as CSV values + headers = headers.split(",") + elif fileformat == "jsonl": + reader = _read_jsonl_file + if not headers: + headers = "keys" # reasonable default + if type(headers) is str and headers not in special_headers_values: + # "," and ":" in header titles are not supported in CLI + try: + headers2 = dict(tuple(hh.split(":",2)) for hh in headers.split(",")) + except: + print(f"cannot parse headers parameter: {headers}", file=sys.stderr) + headers2 = [] + headers = headers2 + else: + print(f"{fileformat} is not a supported file format") + sys.exit(3) + # format all input files files = [sys.stdin] if not args else args with sys.stdout if outfile == "-" else open(outfile, "w") as out: for f in files: if f == "-": f = sys.stdin - if _is_file(f): - _pprint_file( - f, + _open_and_pprint_file(reader, f, headers=headers, tablefmt=tablefmt, - sep=sep, floatfmt=floatfmt, intfmt=intfmt, file=out, colalign=colalign, ) - else: - with open(f) as fobj: - _pprint_file( - fobj, - headers=headers, - tablefmt=tablefmt, - sep=sep, - floatfmt=floatfmt, - intfmt=intfmt, - file=out, - colalign=colalign, - ) -def _pprint_file(fobject, headers, tablefmt, sep, floatfmt, intfmt, file, colalign): +def _read_rsv_file(fobject, sep): rows = fobject.readlines() table = [re.split(sep, r.rstrip()) for r in rows if r.strip()] + return table + + +def _read_jsonl_file(fobject): + import json + rows:list[str] = fobject.readlines() + table = [json.loads(row) for row in rows] + return table + + +def _read_csv_file(fobject): + import csv + reader = csv.reader(fobject, dialect="excel") + table = [list(row) for row in reader] + return table + + +def _open_and_pprint_file(reader, f, *args, **kwargs): + if _is_file(f): + _pprint_file(reader, f, *args, **kwargs) + else: + with open(f) as fobj: + _pprint_file(reader, fobj, *args, **kwargs) + + +def _pprint_file(reader, fobject, headers, tablefmt, floatfmt, intfmt, file, colalign): + table = reader(fobject) print( tabulate( table, From 696c5eb25ea2d9d4cb396be04fa3fae22a0620e3 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Mon, 9 Mar 2026 17:20:37 +0100 Subject: [PATCH 194/204] update README.md and CHANGELOG with new CLI usage (JSONL format, --headers option) --- CHANGELOG | 2 ++ README.md | 58 ++++++++++++++++++++++++++++++++++++++----------------- 2 files changed, 42 insertions(+), 18 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 940582a1..ce390bb2 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -2,6 +2,8 @@ Drop support of the legacy `youtrack` format. Add support of the `Decimal` data type. Improve output of `github` and `asciidoc` formats. + Add support of CSV and JSONL input data in CLI utility. + Always add `text-align: left` in HTML output. Various bug fixes. - 0.10.0: Add support for Python 3.11, 3.12, 3.13, 3.14. Drop support for Python 3.7, 3.8, 3.9. diff --git a/README.md b/README.md index d4123284..0283a0c3 100644 --- a/README.md +++ b/README.md @@ -1127,24 +1127,46 @@ itself (terminals would show this text). For example: Usage of the command line utility --------------------------------- - Usage: tabulate [options] [FILE ...] - - FILE a filename of the file with tabular data; - if "-" or missing, read data from stdin. - - Options: - - -h, --help show this message - -1, --header use the first row of data as a table header - -o FILE, --output FILE print table to FILE (default: stdout) - -s REGEXP, --sep REGEXP use a custom column separator (default: whitespace) - -F FPFMT, --float FPFMT floating point number format (default: g) - -I INTFMT, --int INTFMT integer point number format (default: "") - -f FMT, --format FMT set output table format; supported formats: - plain, simple, github, grid, fancy_grid, pipe, - orgtbl, rst, mediawiki, html, latex, latex_raw, - latex_booktabs, latex_longtable, tsv - (default: simple) +``` +Usage: tabulate [options] [FILE ...] + +Pretty-print tabular data. Use Python module for more features. + +FILE a filename of the file with tabular data; + if "-" or missing, read data from stdin. + +Options: + +-h, --help show this message + +INPUT: +-r, --read FILEFORMAT parse input FILEs as: + rsv (REGEXP-separated values, default), + csv (comma-separated valued, Excel dialect), + jsonl (one JSON object per line) +-s REGEXP, --sep REGEXP column separator for rsv data (default: whitespace) + +FORMAT: +--headers HEADERS HEADERS can be one of: + "firstrow" (for csv and rsv data), + "keys" (for jsonl data), + "HEADER1,HEADER2,..." (for csv and rsv data), + "KEY1:HEADER1,KEY2:HEADER2,..." (for jsonl data) +-1 use the first row of input data as a table header + (the same as --headers firstrow) +-F FPFMT, --float FPFMT floating point number format (default: g) +-I INTFMT, --int INTFMT integer point number format (default: "") +-f FMT, --format FMT set output table format (default: simple) + +Supported output formats: asciidoc, colon_grid, double_grid, double_outline, +fancy_grid, fancy_outline, github, grid, heavy_grid, heavy_outline, html, jira, +latex, latex_booktabs, latex_longtable, latex_raw, mediawiki, mixed_grid, mixed_outline, +moinmoin, orgtbl, outline, pipe, plain, presto, pretty, psql, rounded_grid, +rounded_outline, rst, simple, simple_grid, simple_outline, textile, tsv, unsafehtml. + +OUTPUT: +-o FILE, --output FILE print table to FILE (default: stdout) +``` Performance considerations -------------------------- From b47acc1b80b8d15d65f589396169e6f2fc1d3f38 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Mon, 9 Mar 2026 17:22:17 +0100 Subject: [PATCH 195/204] move implementation of the CLI utility to tabulate/cli.py --- pyproject.toml | 2 +- tabulate/__init__.py | 193 +------------------------------------ tabulate/__main__.py | 3 + tabulate/cli.py | 222 +++++++++++++++++++++++++++++++++++++++++++ test/test_cli.py | 14 +-- 5 files changed, 234 insertions(+), 200 deletions(-) create mode 100644 tabulate/__main__.py create mode 100644 tabulate/cli.py diff --git a/pyproject.toml b/pyproject.toml index fb782b8b..126ef55b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -30,7 +30,7 @@ Homepage = "https://github.com/astanin/python-tabulate" widechars = ["wcwidth>=0.6.0"] [project.scripts] -tabulate = "tabulate:_main" +tabulate = "tabulate.cli:_main" [tool.flit.sdist] include = ["CHANGELOG", "test/", "tox.ini"] diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 8911685e..109c1d36 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -12,7 +12,6 @@ from itertools import chain, zip_longest as izip_longest import math import re -import sys import textwrap from typing import Callable, Union import warnings @@ -2896,196 +2895,6 @@ def _wrap_chunks(self, chunks): return lines -def _main(): - """\ - Usage: tabulate [options] [FILE ...] - - Pretty-print tabular data. Use Python module for more features. - - FILE a filename of the file with tabular data; - if "-" or missing, read data from stdin. - - Options: - - -h, --help show this message - - INPUT: - -r, --read FILEFORMAT parse input FILEs as: - rsv (REGEXP-separated values, default), - csv (comma-separated valued, Excel dialect), - jsonl (one JSON object per line) - -s REGEXP, --sep REGEXP column separator for rsv data (default: whitespace) - - FORMAT: - --headers HEADERS HEADERS can be one of: - "firstrow" (for csv and rsv data), - "keys" (for jsonl data), - "HEADER1,HEADER2,..." (for csv and rsv data), - "KEY1:HEADER1,KEY2:HEADER2,..." (for jsonl data) - -1 use the first row of input data as a table header - (the same as --headers firstrow) - -F FPFMT, --float FPFMT floating point number format (default: g) - -I INTFMT, --int INTFMT integer point number format (default: "") - -f FMT, --format FMT set output table format (default: simple) - - Supported output formats: asciidoc, colon_grid, double_grid, double_outline, - fancy_grid, fancy_outline, github, grid, heavy_grid, heavy_outline, html, jira, - latex, latex_booktabs, latex_longtable, latex_raw, mediawiki, mixed_grid, mixed_outline, - moinmoin, orgtbl, outline, pipe, plain, presto, pretty, psql, rounded_grid, - rounded_outline, rst, simple, simple_grid, simple_outline, textile, tsv, unsafehtml. - - OUTPUT: - -o FILE, --output FILE print table to FILE (default: stdout) - - """ - import getopt - - usage = textwrap.dedent(_main.__doc__) - try: - opts, args = getopt.getopt( - sys.argv[1:], - "h1H:r:o:s:F:I:f:", - [ - "help", - "header", # deprecated in CLI > 0.10 - "headers=", # CLI > 0.10 - "read=", # CLI > 0.10 - "output=", - "sep=", - "float=", - "int=", - "colalign=", - "format=", - ], - ) - except getopt.GetoptError as e: - print(e, file=sys.stderr) - print(usage) - sys.exit(2) - headers = [] - floatfmt = _DEFAULT_FLOATFMT - intfmt = _DEFAULT_INTFMT - colalign = None - tablefmt = "simple" - fileformat = "rsv" - sep = r"\s+" - outfile = "-" - special_headers_values = ["firstrow", "keys"] - for opt, value in opts: - if opt in ["-1", "--header"]: - # "header" option is for backwards compatibility with CLI <= 0.10 - # CLI >= 0.11 should user --headers - headers = "firstrow" - if opt in ["-H", "--headers"]: - if value in special_headers_values: - headers = value - else: - headers = value # may need to be processed - elif opt in ["-o", "--output"]: - outfile = value - elif opt in ["-F", "--float"]: - floatfmt = value - elif opt in ["-I", "--int"]: - intfmt = value - elif opt in ["-C", "--colalign"]: - colalign = value.split() - elif opt in ["-r", "--read"]: - fileformat = value.lower() - elif opt in ["-f", "--format"]: - if value not in tabulate_formats: - print(f"{value} is not a supported output format", file=sys.stderr) - print(usage) - sys.exit(3) - tablefmt = value - elif opt in ["-s", "--sep"]: - sep = value - elif opt in ["-h", "--help"]: - print(usage) - sys.exit(0) - # choose a reader and parse headers option - if fileformat == "rsv": - reader = partial(_read_rsv_file, sep=sep) - if type(headers) is str and headers not in special_headers_values: - # parse as CSV values - headers = headers.split(",") - elif fileformat == "csv": - reader = _read_csv_file - if type(headers) is str and headers not in special_headers_values: - # parse as CSV values - headers = headers.split(",") - elif fileformat == "jsonl": - reader = _read_jsonl_file - if not headers: - headers = "keys" # reasonable default - if type(headers) is str and headers not in special_headers_values: - # "," and ":" in header titles are not supported in CLI - try: - headers2 = dict(tuple(hh.split(":",2)) for hh in headers.split(",")) - except: - print(f"cannot parse headers parameter: {headers}", file=sys.stderr) - headers2 = [] - headers = headers2 - else: - print(f"{fileformat} is not a supported file format") - sys.exit(3) - # format all input files - files = [sys.stdin] if not args else args - with sys.stdout if outfile == "-" else open(outfile, "w") as out: - for f in files: - if f == "-": - f = sys.stdin - _open_and_pprint_file(reader, f, - headers=headers, - tablefmt=tablefmt, - floatfmt=floatfmt, - intfmt=intfmt, - file=out, - colalign=colalign, - ) - - -def _read_rsv_file(fobject, sep): - rows = fobject.readlines() - table = [re.split(sep, r.rstrip()) for r in rows if r.strip()] - return table - - -def _read_jsonl_file(fobject): - import json - rows:list[str] = fobject.readlines() - table = [json.loads(row) for row in rows] - return table - - -def _read_csv_file(fobject): - import csv - reader = csv.reader(fobject, dialect="excel") - table = [list(row) for row in reader] - return table - - -def _open_and_pprint_file(reader, f, *args, **kwargs): - if _is_file(f): - _pprint_file(reader, f, *args, **kwargs) - else: - with open(f) as fobj: - _pprint_file(reader, fobj, *args, **kwargs) - - -def _pprint_file(reader, fobject, headers, tablefmt, floatfmt, intfmt, file, colalign): - table = reader(fobject) - print( - tabulate( - table, - headers, - tablefmt, - floatfmt=floatfmt, - intfmt=intfmt, - colalign=colalign, - ), - file=file, - ) - - if __name__ == "__main__": + from .cli import _main _main() diff --git a/tabulate/__main__.py b/tabulate/__main__.py new file mode 100644 index 00000000..c6efd79c --- /dev/null +++ b/tabulate/__main__.py @@ -0,0 +1,3 @@ +from tabulate.cli import _main + +_main() diff --git a/tabulate/cli.py b/tabulate/cli.py new file mode 100644 index 00000000..0ccec5d0 --- /dev/null +++ b/tabulate/cli.py @@ -0,0 +1,222 @@ +"""Command-line interface for tabulate.""" + +import re +import sys +import textwrap +from functools import partial + +try: + from . import ( + _DEFAULT_FLOATFMT, + _DEFAULT_INTFMT, + _is_file, + tabulate, + tabulate_formats, + ) +except ImportError: + # running as a script: python tabulate/cli.py + import sys as _sys + import os as _os + _sys.path.insert(0, _os.path.dirname(_os.path.dirname(_os.path.abspath(__file__)))) + from tabulate import ( + _DEFAULT_FLOATFMT, + _DEFAULT_INTFMT, + _is_file, + tabulate, + tabulate_formats, + ) + + +def _main(): + """\ + Usage: tabulate [options] [FILE ...] + + Pretty-print tabular data. Use Python module for more features. + + FILE a filename of the file with tabular data; + if "-" or missing, read data from stdin. + + Options: + + -h, --help show this message + + INPUT: + -r, --read FILEFORMAT parse input FILEs as: + rsv (REGEXP-separated values, default), + csv (comma-separated valued, Excel dialect), + jsonl (one JSON object per line) + -s REGEXP, --sep REGEXP column separator for rsv data (default: whitespace) + + FORMAT: + --headers HEADERS HEADERS can be one of: + "firstrow" (for csv and rsv data), + "keys" (for jsonl data), + "HEADER1,HEADER2,..." (for csv and rsv data), + "KEY1:HEADER1,KEY2:HEADER2,..." (for jsonl data) + -1 use the first row of input data as a table header + (the same as --headers firstrow) + -F FPFMT, --float FPFMT floating point number format (default: g) + -I INTFMT, --int INTFMT integer point number format (default: "") + -f FMT, --format FMT set output table format (default: simple) + + Supported output formats: asciidoc, colon_grid, double_grid, double_outline, + fancy_grid, fancy_outline, github, grid, heavy_grid, heavy_outline, html, jira, + latex, latex_booktabs, latex_longtable, latex_raw, mediawiki, mixed_grid, mixed_outline, + moinmoin, orgtbl, outline, pipe, plain, presto, pretty, psql, rounded_grid, + rounded_outline, rst, simple, simple_grid, simple_outline, textile, tsv, unsafehtml. + + OUTPUT: + -o FILE, --output FILE print table to FILE (default: stdout) + + """ + import getopt + + usage = textwrap.dedent(_main.__doc__) + try: + opts, args = getopt.getopt( + sys.argv[1:], + "h1H:r:o:s:F:I:f:", + [ + "help", + "header", # deprecated in CLI > 0.10 + "headers=", # CLI > 0.10 + "read=", # CLI > 0.10 + "output=", + "sep=", + "float=", + "int=", + "colalign=", + "format=", + ], + ) + except getopt.GetoptError as e: + print(e, file=sys.stderr) + print(usage) + sys.exit(2) + headers = [] + floatfmt = _DEFAULT_FLOATFMT + intfmt = _DEFAULT_INTFMT + colalign = None + tablefmt = "simple" + fileformat = "rsv" + sep = r"\s+" + outfile = "-" + special_headers_values = ["firstrow", "keys"] + for opt, value in opts: + if opt in ["-1", "--header"]: + # "header" option is for backwards compatibility with CLI <= 0.10 + # CLI >= 0.11 should user --headers + headers = "firstrow" + if opt in ["-H", "--headers"]: + if value in special_headers_values: + headers = value + else: + headers = value # may need to be processed + elif opt in ["-o", "--output"]: + outfile = value + elif opt in ["-F", "--float"]: + floatfmt = value + elif opt in ["-I", "--int"]: + intfmt = value + elif opt in ["-C", "--colalign"]: + colalign = value.split() + elif opt in ["-r", "--read"]: + fileformat = value.lower() + elif opt in ["-f", "--format"]: + if value not in tabulate_formats: + print(f"{value} is not a supported output format", file=sys.stderr) + print(usage) + sys.exit(3) + tablefmt = value + elif opt in ["-s", "--sep"]: + sep = value + elif opt in ["-h", "--help"]: + print(usage) + sys.exit(0) + # choose a reader and parse headers option + if fileformat == "rsv": + reader = partial(_read_rsv_file, sep=sep) + if type(headers) is str and headers not in special_headers_values: + # parse as CSV values + headers = headers.split(",") + elif fileformat == "csv": + reader = _read_csv_file + if type(headers) is str and headers not in special_headers_values: + # parse as CSV values + headers = headers.split(",") + elif fileformat == "jsonl": + reader = _read_jsonl_file + if not headers: + headers = "keys" # reasonable default + if type(headers) is str and headers not in special_headers_values: + # "," and ":" in header titles are not supported in CLI + try: + headers2 = dict(tuple(hh.split(":",2)) for hh in headers.split(",")) + except: + print(f"cannot parse headers parameter: {headers}", file=sys.stderr) + headers2 = [] + headers = headers2 + else: + print(f"{fileformat} is not a supported file format") + sys.exit(3) + # format all input files + files = [sys.stdin] if not args else args + with sys.stdout if outfile == "-" else open(outfile, "w") as out: + for f in files: + if f == "-": + f = sys.stdin + _open_and_pprint_file(reader, f, + headers=headers, + tablefmt=tablefmt, + floatfmt=floatfmt, + intfmt=intfmt, + file=out, + colalign=colalign, + ) + + +def _read_rsv_file(fobject, sep): + rows = fobject.readlines() + table = [re.split(sep, r.rstrip()) for r in rows if r.strip()] + return table + + +def _read_jsonl_file(fobject): + import json + rows:list[str] = fobject.readlines() + table = [json.loads(row) for row in rows] + return table + + +def _read_csv_file(fobject): + import csv + reader = csv.reader(fobject, dialect="excel") + table = [list(row) for row in reader] + return table + + +def _open_and_pprint_file(reader, f, *args, **kwargs): + if _is_file(f): + _pprint_file(reader, f, *args, **kwargs) + else: + with open(f) as fobj: + _pprint_file(reader, fobj, *args, **kwargs) + + +def _pprint_file(reader, fobject, headers, tablefmt, floatfmt, intfmt, file, colalign): + table = reader(fobject) + print( + tabulate( + table, + headers, + tablefmt, + floatfmt=floatfmt, + intfmt=intfmt, + colalign=colalign, + ), + file=file, + ) + + +if __name__ == "__main__": + _main() diff --git a/test/test_cli.py b/test/test_cli.py index 625eea11..3cba9647 100644 --- a/test/test_cli.py +++ b/test/test_cli.py @@ -104,7 +104,7 @@ def __exit__(self, exc_type, exc_val, exc_tb): def test_script_from_stdin_to_stdout(): """Command line utility: read from stdin, print to stdout""" - cmd = [sys.executable, "tabulate/__init__.py"] + cmd = [sys.executable, "tabulate/cli.py"] out = run_and_capture_stdout(cmd, input=sample_input()) expected = SAMPLE_SIMPLE_FORMAT print("got: ", repr(out)) @@ -117,7 +117,7 @@ def test_script_from_file_to_stdout(): with TemporaryTextFile() as tmpfile: tmpfile.write(sample_input()) tmpfile.seek(0) - cmd = [sys.executable, "tabulate/__init__.py", tmpfile.name] + cmd = [sys.executable, "tabulate/cli.py", tmpfile.name] out = run_and_capture_stdout(cmd) expected = SAMPLE_SIMPLE_FORMAT print("got: ", repr(out)) @@ -133,7 +133,7 @@ def test_script_from_file_to_file(): input_file.seek(0) cmd = [ sys.executable, - "tabulate/__init__.py", + "tabulate/cli.py", "-o", output_file.name, input_file.name, @@ -156,7 +156,7 @@ def test_script_from_file_to_file(): def test_script_header_option(): """Command line utility: -1, --header option""" for option in ["-1", "--header"]: - cmd = [sys.executable, "tabulate/__init__.py", option] + cmd = [sys.executable, "tabulate/cli.py", option] raw_table = sample_input(with_headers=True) out = run_and_capture_stdout(cmd, input=raw_table) expected = SAMPLE_SIMPLE_FORMAT_WITH_HEADERS @@ -169,7 +169,7 @@ def test_script_header_option(): def test_script_sep_option(): """Command line utility: -s, --sep option""" for option in ["-s", "--sep"]: - cmd = [sys.executable, "tabulate/__init__.py", option, ","] + cmd = [sys.executable, "tabulate/cli.py", option, ","] raw_table = sample_input(sep=",") out = run_and_capture_stdout(cmd, input=raw_table) expected = SAMPLE_SIMPLE_FORMAT @@ -183,7 +183,7 @@ def test_script_floatfmt_option(): for option in ["-F", "--float"]: cmd = [ sys.executable, - "tabulate/__init__.py", + "tabulate/cli.py", option, ".1e", "--format", @@ -200,7 +200,7 @@ def test_script_floatfmt_option(): def test_script_format_option(): """Command line utility: -f, --format option""" for option in ["-f", "--format"]: - cmd = [sys.executable, "tabulate/__init__.py", "-1", option, "grid"] + cmd = [sys.executable, "tabulate/cli.py", "-1", option, "grid"] raw_table = sample_input(with_headers=True) out = run_and_capture_stdout(cmd, input=raw_table) expected = SAMPLE_GRID_FORMAT_WITH_HEADERS From 791c4bf2fa3e06a8e21d01efee65f6649b51e5a1 Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Mon, 9 Mar 2026 17:34:32 +0100 Subject: [PATCH 196/204] add tests for the new CLI utility options --- test/test_cli.py | 84 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) diff --git a/test/test_cli.py b/test/test_cli.py index 3cba9647..1ca64b06 100644 --- a/test/test_cli.py +++ b/test/test_cli.py @@ -208,3 +208,87 @@ def test_script_format_option(): print("got: ", repr(out)) print("expected:", repr(expected)) assert_equal(out.splitlines(), expected.splitlines()) + + +SAMPLE_INPUT_JSONL = "\n".join( + [ + '{"id": 1, "name": "Alice", "email": "alice@example.com"}', + '{"id": 2, "name": "Bob", "email": "bob@example.com"}', + ] +) + +SAMPLE_GRID_FORMAT = "\n".join( + [ + "+------+--------+-------------------+", + "| id | name | email |", + "+======+========+===================+", + "| 1 | Alice | alice@example.com |", + "+------+--------+-------------------+", + "| 2 | Bob | bob@example.com |", + "+------+--------+-------------------+", + ] +) + + +def test_module_jsonl_from_stdin(): + """Command line utility: python -m tabulate with JSONL input from stdin""" + cmd = [sys.executable, "-m", "tabulate", "-r", "jsonl", "-f", "grid"] + out = run_and_capture_stdout(cmd, input=SAMPLE_INPUT_JSONL) + expected = SAMPLE_GRID_FORMAT + print("got: ", repr(out)) + print("expected:", repr(expected)) + assert_equal(out.splitlines(), expected.splitlines()) + + +SAMPLE_REMAPPED_HEADERS = "\n".join( + [ + " ID First Name Email", + "---- ------------ -----------------", + " 1 Alice alice@example.com", + " 2 Bob bob@example.com", + ] +) + + +SAMPLE_INPUT_CSV = ( + 'id,name,email,"""favorite"" fruit"\n' + '1,Alice,alice@example.com,"apple, kiwi"\n' + '2,Bob,bob@example.com,"banana,\norange,\nlychee"\n' + "3,Carol,,pear\n" +) + +SAMPLE_CSV_FORMAT = "\n".join( + [ + "-- ----- ----------------- ----------------", + "id name email \"favorite\" fruit", + "1 Alice alice@example.com apple, kiwi", + "2 Bob bob@example.com banana,", + " orange,", + " lychee", + "3 Carol pear", + "-- ----- ----------------- ----------------", + ] +) + +def test_module_csv_from_stdin(): + """Command line utility: python -m tabulate with CSV input from stdin""" + cmd = [sys.executable, "-m", "tabulate", "-r", "csv"] + out = run_and_capture_stdout(cmd, input=SAMPLE_INPUT_CSV) + expected = SAMPLE_CSV_FORMAT + print("got: ", repr(out)) + print("expected:", repr(expected)) + assert_equal(out.splitlines(), expected.splitlines()) + + +def test_module_jsonl_remapped_headers(): + """Command line utility: --headers with key:header remapping for JSONL input""" + cmd = [ + sys.executable, "-m", "tabulate", + "-r", "jsonl", + "--headers", "id:ID,name:First Name,email:Email", + ] + out = run_and_capture_stdout(cmd, input=SAMPLE_INPUT_JSONL) + expected = SAMPLE_REMAPPED_HEADERS + print("got: ", repr(out)) + print("expected:", repr(expected)) + assert_equal(out.splitlines(), expected.splitlines()) From 17bf1cf0b03390090fe26d858eee0eddbd8598fd Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Tue, 10 Mar 2026 09:32:47 +0100 Subject: [PATCH 197/204] run all CLI tests also in-process for coverage report - old tests: launch tabulate via subprocess (still necessary) - new tests: the same checks for coverage reports --- tabulate/cli.py | 4 +- test/test_cli.py | 180 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 182 insertions(+), 2 deletions(-) diff --git a/tabulate/cli.py b/tabulate/cli.py index 0ccec5d0..ab7d571c 100644 --- a/tabulate/cli.py +++ b/tabulate/cli.py @@ -13,7 +13,7 @@ tabulate, tabulate_formats, ) -except ImportError: +except ImportError: # pragma: no cover # running as a script: python tabulate/cli.py import sys as _sys import os as _os @@ -218,5 +218,5 @@ def _pprint_file(reader, fobject, headers, tablefmt, floatfmt, intfmt, file, col ) -if __name__ == "__main__": +if __name__ == "__main__": # pragma: no cover _main() diff --git a/test/test_cli.py b/test/test_cli.py index 1ca64b06..01624482 100644 --- a/test/test_cli.py +++ b/test/test_cli.py @@ -1,11 +1,32 @@ """Command-line interface.""" +import contextlib +import io import os import subprocess import sys import tempfile +from unittest.mock import patch from common import assert_equal +from tabulate.cli import _main + + +class _UnclosableStringIO(io.StringIO): + """StringIO that ignores close() so getvalue() works after a 'with' block.""" + def close(self): + pass # _main does `with sys.stdout as out:`, which would close a plain StringIO + + +def run_main_in_process(args, input_text=None): + """Call _main() in-process, capturing stdout. Returns the captured output.""" + stdin = io.StringIO(input_text) if input_text is not None else sys.stdin + stdout = _UnclosableStringIO() + with patch("sys.argv", ["tabulate"] + args), \ + patch("sys.stdin", stdin), \ + contextlib.redirect_stdout(stdout): + _main() + return stdout.getvalue() SAMPLE_SIMPLE_FORMAT = "\n".join( [ @@ -292,3 +313,162 @@ def test_module_jsonl_remapped_headers(): print("got: ", repr(out)) print("expected:", repr(expected)) assert_equal(out.splitlines(), expected.splitlines()) + + +# --------------------------------------------------------------------------- +# In-process tests: same scenarios as above but calling _main() directly so +# that coverage.py can instrument the code in tabulate/cli.py. +# --------------------------------------------------------------------------- + +def test_inprocess_stdin_to_stdout(): + """In-process: read RSV from stdin, print to stdout""" + out = run_main_in_process([], input_text=sample_input()) + assert_equal(out.splitlines(), SAMPLE_SIMPLE_FORMAT.splitlines()) + + +def test_inprocess_header_option(): + """In-process: -1 / --header / --headers firstrow""" + for args in [["-1"], ["--header"], ["--headers", "firstrow"]]: + out = run_main_in_process(args, input_text=sample_input(with_headers=True)) + assert_equal(out.splitlines(), SAMPLE_SIMPLE_FORMAT_WITH_HEADERS.splitlines()) + + +def test_inprocess_sep_option(): + """In-process: -s / --sep""" + for opt in ["-s", "--sep"]: + out = run_main_in_process([opt, ","], input_text=sample_input(sep=",")) + assert_equal(out.splitlines(), SAMPLE_SIMPLE_FORMAT.splitlines()) + + +def test_inprocess_floatfmt_option(): + """In-process: -F / --float""" + for opt in ["-F", "--float"]: + out = run_main_in_process([opt, ".1e", "--format", "grid"], input_text=sample_input()) + assert_equal(out.splitlines(), SAMPLE_GRID_FORMAT_WITH_DOT1E_FLOATS.splitlines()) + + +def test_inprocess_format_option(): + """In-process: -f / --format""" + for opt in ["-f", "--format"]: + out = run_main_in_process(["-1", opt, "grid"], input_text=sample_input(with_headers=True)) + assert_equal(out.splitlines(), SAMPLE_GRID_FORMAT_WITH_HEADERS.splitlines()) + + +def test_inprocess_file_to_file(): + """In-process: read from file, write to file (-o)""" + with TemporaryTextFile() as input_file: + with TemporaryTextFile() as output_file: + input_file.write(sample_input()) + input_file.flush() + run_main_in_process(["-o", output_file.name, input_file.name]) + output_file.seek(0) + out = output_file.file.read() + assert_equal(out.splitlines(), SAMPLE_SIMPLE_FORMAT.splitlines()) + + +def test_inprocess_jsonl_from_stdin(): + """In-process: JSONL input from stdin, grid format""" + out = run_main_in_process(["-r", "jsonl", "-f", "grid"], input_text=SAMPLE_INPUT_JSONL) + assert_equal(out.splitlines(), SAMPLE_GRID_FORMAT.splitlines()) + + +def test_inprocess_jsonl_remapped_headers(): + """In-process: JSONL input with key:header remapping""" + out = run_main_in_process( + ["-r", "jsonl", "--headers", "id:ID,name:First Name,email:Email"], + input_text=SAMPLE_INPUT_JSONL, + ) + assert_equal(out.splitlines(), SAMPLE_REMAPPED_HEADERS.splitlines()) + + +def test_inprocess_csv_from_stdin(): + """In-process: CSV input from stdin""" + out = run_main_in_process(["-r", "csv"], input_text=SAMPLE_INPUT_CSV) + assert_equal(out.splitlines(), SAMPLE_CSV_FORMAT.splitlines()) + + +def test_inprocess_invalid_option(): + """In-process: unrecognised option exits with code 2""" + import pytest + with pytest.raises(SystemExit) as exc_info: + run_main_in_process(["--no-such-option"], input_text="a b\n1 2\n") + assert exc_info.value.code == 2 + + +def test_inprocess_help_option(): + """In-process: --help / -h exits with code 0""" + import pytest + for opt in ["-h", "--help"]: + with pytest.raises(SystemExit) as exc_info: + run_main_in_process([opt], input_text="") + assert exc_info.value.code == 0 + + +def test_inprocess_invalid_format(): + """In-process: unknown --format value exits with code 3""" + import pytest + with pytest.raises(SystemExit) as exc_info: + run_main_in_process(["-f", "nosuchformat"], input_text="a b\n1 2\n") + assert exc_info.value.code == 3 + + +def test_inprocess_invalid_fileformat(): + """In-process: unknown --read value exits with code 3""" + import pytest + with pytest.raises(SystemExit) as exc_info: + run_main_in_process(["-r", "xml"], input_text="") + assert exc_info.value.code == 3 + + +def test_inprocess_int_option(): + """In-process: -I / --int option""" + jsonl_ints = '{"n": 1000000}\n{"n": 2000000}\n' + for opt in ["-I", "--int"]: + out = run_main_in_process( + ["-r", "jsonl", opt, "_"], input_text=jsonl_ints + ) + assert "1_000_000" in out + + +def test_inprocess_colalign_option(): + """In-process: --colalign option""" + out = run_main_in_process( + ["--colalign", "left left left", "-1"], + input_text=sample_input(with_headers=True), + ) + assert "Planet" in out + + +def test_inprocess_rsv_custom_headers(): + """In-process: --headers with custom column names for RSV input""" + out = run_main_in_process( + ["--headers", "Planet,Radius,Mass"], input_text=sample_input() + ) + assert_equal(out.splitlines(), SAMPLE_SIMPLE_FORMAT_WITH_HEADERS.splitlines()) + + +def test_inprocess_csv_custom_headers(): + """In-process: --headers with custom column names overrides CSV first row""" + csv_data = "Sun,696000,1.9891e9\nEarth,6371,5973.6\n" + out = run_main_in_process( + ["-r", "csv", "--headers", "Planet,Radius,Mass"], input_text=csv_data + ) + assert "Planet" in out and "Radius" in out and "Mass" in out + + +def test_inprocess_stdin_dash_arg(): + """In-process: '-' as filename reads from stdin""" + out = run_main_in_process(["-"], input_text=sample_input()) + assert_equal(out.splitlines(), SAMPLE_SIMPLE_FORMAT.splitlines()) + + +def test_inprocess_jsonl_malformed_headers(): + """In-process: malformed key:header mapping falls back to no headers""" + # A header spec without ':' can't be parsed into key-value pairs; + # _main catches the ValueError and proceeds with an empty headers list. + out = run_main_in_process( + ["-r", "jsonl", "--headers", "no_colon_here"], + input_text=SAMPLE_INPUT_JSONL, + ) + # output should still be produced (graceful fallback), with raw keys as headers + assert out.strip() != "" From cf15727ee7b12bd40eb08ac57de79974de11505e Mon Sep 17 00:00:00 2001 From: Sergey Astanin Date: Tue, 10 Mar 2026 11:13:08 +0100 Subject: [PATCH 198/204] ruff format & ruff check --- examples/people.jsonl | 2 +- tabulate/__init__.py | 1 + tabulate/cli.py | 35 ++++++++++++++++++++--------------- test/test_cli.py | 39 +++++++++++++++++++++++++-------------- 4 files changed, 47 insertions(+), 30 deletions(-) diff --git a/examples/people.jsonl b/examples/people.jsonl index 7f3e1138..8dd35b43 100644 --- a/examples/people.jsonl +++ b/examples/people.jsonl @@ -1,2 +1,2 @@ {"id": 1, "name": "Alice", "email": "alice@example.com"} -{"id": 2, "name": "Bob", "email": "bob@example.com"} \ No newline at end of file +{"id": 2, "name": "Bob", "email": "bob@example.com"} diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 109c1d36..4aa34ee5 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -2897,4 +2897,5 @@ def _wrap_chunks(self, chunks): if __name__ == "__main__": from .cli import _main + _main() diff --git a/tabulate/cli.py b/tabulate/cli.py index ab7d571c..cfae6fea 100644 --- a/tabulate/cli.py +++ b/tabulate/cli.py @@ -1,9 +1,9 @@ """Command-line interface for tabulate.""" +from functools import partial import re import sys import textwrap -from functools import partial try: from . import ( @@ -15,8 +15,9 @@ ) except ImportError: # pragma: no cover # running as a script: python tabulate/cli.py - import sys as _sys import os as _os + import sys as _sys + _sys.path.insert(0, _os.path.dirname(_os.path.dirname(_os.path.abspath(__file__)))) from tabulate import ( _DEFAULT_FLOATFMT, @@ -79,8 +80,8 @@ def _main(): [ "help", "header", # deprecated in CLI > 0.10 - "headers=", # CLI > 0.10 - "read=", # CLI > 0.10 + "headers=", # CLI > 0.10 + "read=", # CLI > 0.10 "output=", "sep=", "float=", @@ -151,8 +152,8 @@ def _main(): if type(headers) is str and headers not in special_headers_values: # "," and ":" in header titles are not supported in CLI try: - headers2 = dict(tuple(hh.split(":",2)) for hh in headers.split(",")) - except: + headers2 = dict(tuple(hh.split(":", 2)) for hh in headers.split(",")) + except Exception: print(f"cannot parse headers parameter: {headers}", file=sys.stderr) headers2 = [] headers = headers2 @@ -165,14 +166,16 @@ def _main(): for f in files: if f == "-": f = sys.stdin - _open_and_pprint_file(reader, f, - headers=headers, - tablefmt=tablefmt, - floatfmt=floatfmt, - intfmt=intfmt, - file=out, - colalign=colalign, - ) + _open_and_pprint_file( + reader, + f, + headers=headers, + tablefmt=tablefmt, + floatfmt=floatfmt, + intfmt=intfmt, + file=out, + colalign=colalign, + ) def _read_rsv_file(fobject, sep): @@ -183,13 +186,15 @@ def _read_rsv_file(fobject, sep): def _read_jsonl_file(fobject): import json - rows:list[str] = fobject.readlines() + + rows: list[str] = fobject.readlines() table = [json.loads(row) for row in rows] return table def _read_csv_file(fobject): import csv + reader = csv.reader(fobject, dialect="excel") table = [list(row) for row in reader] return table diff --git a/test/test_cli.py b/test/test_cli.py index 01624482..154f1a2b 100644 --- a/test/test_cli.py +++ b/test/test_cli.py @@ -8,12 +8,14 @@ import tempfile from unittest.mock import patch -from common import assert_equal from tabulate.cli import _main +from common import assert_equal + class _UnclosableStringIO(io.StringIO): """StringIO that ignores close() so getvalue() works after a 'with' block.""" + def close(self): pass # _main does `with sys.stdout as out:`, which would close a plain StringIO @@ -22,12 +24,15 @@ def run_main_in_process(args, input_text=None): """Call _main() in-process, capturing stdout. Returns the captured output.""" stdin = io.StringIO(input_text) if input_text is not None else sys.stdin stdout = _UnclosableStringIO() - with patch("sys.argv", ["tabulate"] + args), \ - patch("sys.stdin", stdin), \ - contextlib.redirect_stdout(stdout): + with ( + patch("sys.argv", ["tabulate"] + args), + patch("sys.stdin", stdin), + contextlib.redirect_stdout(stdout), + ): _main() return stdout.getvalue() + SAMPLE_SIMPLE_FORMAT = "\n".join( [ "----- ------ -------------", @@ -281,7 +286,7 @@ def test_module_jsonl_from_stdin(): SAMPLE_CSV_FORMAT = "\n".join( [ "-- ----- ----------------- ----------------", - "id name email \"favorite\" fruit", + 'id name email "favorite" fruit', "1 Alice alice@example.com apple, kiwi", "2 Bob bob@example.com banana,", " orange,", @@ -291,6 +296,7 @@ def test_module_jsonl_from_stdin(): ] ) + def test_module_csv_from_stdin(): """Command line utility: python -m tabulate with CSV input from stdin""" cmd = [sys.executable, "-m", "tabulate", "-r", "csv"] @@ -304,9 +310,13 @@ def test_module_csv_from_stdin(): def test_module_jsonl_remapped_headers(): """Command line utility: --headers with key:header remapping for JSONL input""" cmd = [ - sys.executable, "-m", "tabulate", - "-r", "jsonl", - "--headers", "id:ID,name:First Name,email:Email", + sys.executable, + "-m", + "tabulate", + "-r", + "jsonl", + "--headers", + "id:ID,name:First Name,email:Email", ] out = run_and_capture_stdout(cmd, input=SAMPLE_INPUT_JSONL) expected = SAMPLE_REMAPPED_HEADERS @@ -320,6 +330,7 @@ def test_module_jsonl_remapped_headers(): # that coverage.py can instrument the code in tabulate/cli.py. # --------------------------------------------------------------------------- + def test_inprocess_stdin_to_stdout(): """In-process: read RSV from stdin, print to stdout""" out = run_main_in_process([], input_text=sample_input()) @@ -390,6 +401,7 @@ def test_inprocess_csv_from_stdin(): def test_inprocess_invalid_option(): """In-process: unrecognised option exits with code 2""" import pytest + with pytest.raises(SystemExit) as exc_info: run_main_in_process(["--no-such-option"], input_text="a b\n1 2\n") assert exc_info.value.code == 2 @@ -398,6 +410,7 @@ def test_inprocess_invalid_option(): def test_inprocess_help_option(): """In-process: --help / -h exits with code 0""" import pytest + for opt in ["-h", "--help"]: with pytest.raises(SystemExit) as exc_info: run_main_in_process([opt], input_text="") @@ -407,6 +420,7 @@ def test_inprocess_help_option(): def test_inprocess_invalid_format(): """In-process: unknown --format value exits with code 3""" import pytest + with pytest.raises(SystemExit) as exc_info: run_main_in_process(["-f", "nosuchformat"], input_text="a b\n1 2\n") assert exc_info.value.code == 3 @@ -415,6 +429,7 @@ def test_inprocess_invalid_format(): def test_inprocess_invalid_fileformat(): """In-process: unknown --read value exits with code 3""" import pytest + with pytest.raises(SystemExit) as exc_info: run_main_in_process(["-r", "xml"], input_text="") assert exc_info.value.code == 3 @@ -424,9 +439,7 @@ def test_inprocess_int_option(): """In-process: -I / --int option""" jsonl_ints = '{"n": 1000000}\n{"n": 2000000}\n' for opt in ["-I", "--int"]: - out = run_main_in_process( - ["-r", "jsonl", opt, "_"], input_text=jsonl_ints - ) + out = run_main_in_process(["-r", "jsonl", opt, "_"], input_text=jsonl_ints) assert "1_000_000" in out @@ -441,9 +454,7 @@ def test_inprocess_colalign_option(): def test_inprocess_rsv_custom_headers(): """In-process: --headers with custom column names for RSV input""" - out = run_main_in_process( - ["--headers", "Planet,Radius,Mass"], input_text=sample_input() - ) + out = run_main_in_process(["--headers", "Planet,Radius,Mass"], input_text=sample_input()) assert_equal(out.splitlines(), SAMPLE_SIMPLE_FORMAT_WITH_HEADERS.splitlines()) From 2f7f69d6f8c82363d6e6053746dba4b836057721 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 5 Mar 2026 16:35:16 +0100 Subject: [PATCH 199/204] Apply ruff/pyupgrade rule UP007 Use `X | Y` for type annotations --- tabulate/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 9ee72fe6..1cb052b6 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -14,7 +14,7 @@ import re import sys import textwrap -from typing import Callable, Union +from typing import Callable import warnings try: @@ -2529,7 +2529,7 @@ def _build_row( padded_cells: list[list], colwidths: list[int], colaligns: list[str], - rowfmt: Union[DataRow, Callable], + rowfmt: DataRow | Callable, ) -> str: "Return a string which represents a row of data cells." if not rowfmt: From 63c74acd805c35b864f5d49d23120ec8c6381a9c Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 5 Mar 2026 09:05:34 +0100 Subject: [PATCH 200/204] Apply ruff/pyupgrade rule UP018 Unnecessary `int` call (rewrite as a literal) --- test/test_regression.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_regression.py b/test/test_regression.py index 051bf031..98eefba3 100644 --- a/test/test_regression.py +++ b/test/test_regression.py @@ -341,7 +341,7 @@ def test_multiline_with_wide_characters(): def test_align_long_integers(): "Regression: long integers should be aligned as integers (issue #61)" - table = [[int(1)], [int(234)]] + table = [[1], [234]] result = tabulate(table, tablefmt="plain") expected = "\n".join([" 1", "234"]) assert_equal(expected, result) From 4c39df9755109ddfe73ef4fd4acd17d9bd8ef2e7 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 5 Mar 2026 09:11:28 +0100 Subject: [PATCH 201/204] Apply ruff/pyupgrade rule UP031 Use format specifiers instead of percent format --- benchmark/benchmark.py | 8 ++++---- tabulate/__init__.py | 10 +++++----- test/common.py | 8 ++++---- test/test_api.py | 2 +- test/test_input.py | 2 +- 5 files changed, 15 insertions(+), 15 deletions(-) diff --git a/benchmark/benchmark.py b/benchmark/benchmark.py index d405f5c7..f632a04b 100644 --- a/benchmark/benchmark.py +++ b/benchmark/benchmark.py @@ -55,13 +55,13 @@ def run_tabulate(table, widechars=False): methods = [ ("join with tabs and newlines", "join_table(table)"), ("csv to StringIO", "csv_table(table)"), - ("tabulate (%s)" % tabulate.__version__, "run_tabulate(table)"), + (f"tabulate ({tabulate.__version__})", "run_tabulate(table)"), ( - "tabulate (%s, WIDE_CHARS_MODE)" % tabulate.__version__, + f"tabulate ({tabulate.__version__}, WIDE_CHARS_MODE)", "run_tabulate(table, widechars=True)", ), - ("PrettyTable (%s)" % prettytable.__version__, "run_prettytable(table)"), - ("texttable (%s)" % texttable.__version__, "run_texttable(table)"), + (f"PrettyTable ({prettytable.__version__})", "run_prettytable(table)"), + (f"texttable ({texttable.__version__})", "run_texttable(table)"), ] diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 1cb052b6..13c06b21 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1046,7 +1046,7 @@ def _padleft(width, s): True """ - fmt = "{0:>%ds}" % width + fmt = f"{{0:>{width}s}}" return fmt.format(s) @@ -1057,7 +1057,7 @@ def _padright(width, s): True """ - fmt = "{0:<%ds}" % width + fmt = f"{{0:<{width}s}}" return fmt.format(s) @@ -1068,7 +1068,7 @@ def _padboth(width, s): True """ - fmt = "{0:^%ds}" % width + fmt = f"{{0:^{width}s}}" return fmt.format(s) @@ -2805,7 +2805,7 @@ def _wrap_chunks(self, chunks): """ lines = [] if self.width <= 0: - raise ValueError("invalid width %r (must be > 0)" % self.width) + raise ValueError(f"invalid width {self.width!r} (must be > 0)") if self.max_lines is not None: if self.max_lines > 1: indent = self.subsequent_indent @@ -2962,7 +2962,7 @@ def _main(): colalign = value.split() elif opt in ["-f", "--format"]: if value not in tabulate_formats: - print("%s is not a supported table format" % value) + print(f"{value} is not a supported table format") print(usage) sys.exit(3) tablefmt = value diff --git a/test/common.py b/test/common.py index 6afb4be0..fc994003 100644 --- a/test/common.py +++ b/test/common.py @@ -5,15 +5,15 @@ def assert_equal(expected, result): - print("Expected:\n%r\n" % expected) - print("Got:\n%r\n" % result) + print(f"Expected:\n{expected!r}\n") + print(f"Got:\n{result!r}\n") assert expected == result def assert_in(result, expected_set): for i, expected in enumerate(expected_set, start=1): - print("Expected %d:\n%s\n" % (i, expected)) - print("Got:\n%s\n" % result) + print(f"Expected {i}:\n{expected}\n") + print(f"Got:\n{result}\n") assert result in expected_set diff --git a/test/test_api.py b/test/test_api.py index 3e0963a2..cb59836e 100644 --- a/test/test_api.py +++ b/test/test_api.py @@ -14,7 +14,7 @@ def test_tabulate_formats(): "API: tabulate_formats is a list of strings" supported = tabulate_formats - print("tabulate_formats = %r" % supported) + print(f"tabulate_formats = {supported!r}") assert type(supported) is list for fmt in supported: assert type(fmt) is str diff --git a/test/test_input.py b/test/test_input.py index 908d8d7e..3cc32374 100644 --- a/test/test_input.py +++ b/test/test_input.py @@ -96,7 +96,7 @@ def test_dict_like(): expected1 = "\n".join([" a b", "--- ---", " 0 101", " 1 102", " 2 103", " 104"]) expected2 = "\n".join([" b a", "--- ---", "101 0", "102 1", "103 2", "104"]) result = tabulate(dd, "keys") - print("Keys' order: %s" % dd.keys()) + print(f"Keys' order: {dd.keys()}") assert_in(result, [expected1, expected2]) From 5f877749b6c9a7de90efaea63644f13d6b6d7dab Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 5 Mar 2026 16:36:13 +0100 Subject: [PATCH 202/204] Apply ruff/pyupgrade rule UP035 Import from `collections.abc` instead --- tabulate/__init__.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 13c06b21..449f78c8 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1,7 +1,7 @@ """Pretty-print tabular data.""" from collections import namedtuple -from collections.abc import Iterable, Sized +from collections.abc import Callable, Iterable, Sized import dataclasses from dataclasses import dataclass from decimal import Decimal @@ -14,7 +14,6 @@ import re import sys import textwrap -from typing import Callable import warnings try: From 2070736ffe87cae8941e905974e28c539f32d7e3 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 5 Mar 2026 09:12:38 +0100 Subject: [PATCH 203/204] Enforce ruff/pyupgrade rules (UP) --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index fb782b8b..6a564771 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -56,7 +56,7 @@ line-length = 99 exclude = ["tabulate/_version.py"] [tool.ruff.lint] -extend-select = ["W", "C4", "ISC", "I", "C90"] +extend-select = ["W", "C4", "ISC", "I", "C90", "UP"] ignore = ["E721", "C901"] [tool.ruff.lint.mccabe] From 3681fa565d4001d2d23e168e15d207afe9e19c1a Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Tue, 10 Mar 2026 22:16:44 +0100 Subject: [PATCH 204/204] Enforce ruff/flake8-bugbear rules (B) --- pyproject.toml | 4 ++-- tabulate/__init__.py | 8 ++++---- test/test_regression.py | 8 ++++---- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 6a564771..99325f37 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -56,8 +56,8 @@ line-length = 99 exclude = ["tabulate/_version.py"] [tool.ruff.lint] -extend-select = ["W", "C4", "ISC", "I", "C90", "UP"] -ignore = ["E721", "C901"] +extend-select = ["W", "B", "C4", "ISC", "I", "C90", "UP"] +ignore = ["B905", "E721", "C901"] [tool.ruff.lint.mccabe] max-complexity = 22 diff --git a/tabulate/__init__.py b/tabulate/__init__.py index 449f78c8..d45b246b 100644 --- a/tabulate/__init__.py +++ b/tabulate/__init__.py @@ -1478,8 +1478,8 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"): keys = tabular_data.keys() try: rows = list(izip_longest(*tabular_data.values())) # columns have to be transposed - except TypeError: # not iterable - raise TypeError(err_msg) + except TypeError as e: # not iterable + raise TypeError(err_msg) from e elif hasattr(tabular_data, "index"): # values is a property, has .index => it's likely a pandas.DataFrame (pandas 0.11.0) @@ -1502,8 +1502,8 @@ def _normalize_tabular_data(tabular_data, headers, showindex="default"): else: # it's a usual iterable of iterables, or a NumPy array, or an iterable of dataclasses try: rows = list(tabular_data) - except TypeError: # not iterable - raise TypeError(err_msg) + except TypeError as e: # not iterable + raise TypeError(err_msg) from e if headers == "keys" and not rows: # an empty table (issue #81) diff --git a/test/test_regression.py b/test/test_regression.py index 98eefba3..95556769 100644 --- a/test/test_regression.py +++ b/test/test_regression.py @@ -97,7 +97,7 @@ def mk_iter_of_iters(): def mk_iter(): yield from range(3) - for r in range(3): + for _ in range(3): yield mk_iter() def mk_headers(): @@ -357,7 +357,7 @@ def test_numpy_array_as_headers(): expected = "foo bar" assert_equal(expected, result) except ImportError: - raise skip("") + raise skip("") from None def test_boolean_columns(): @@ -477,7 +477,7 @@ def test_numpy_array_as_showindex(): try: import numpy as np except ImportError: - raise skip("") + raise skip("") from None table = [["a"], ["b"], ["c"]] # np.array([...]) == "default" returns an element-wise boolean array whose @@ -548,7 +548,7 @@ def test_numpy_int64_as_integer(): ) assert_equal(expected, result) except ImportError: - raise skip("") + raise skip("") from None def test_empty_table_with_colalign():