python-tabulate icon indicating copy to clipboard operation
python-tabulate copied to clipboard

Improve the error messages around colalign

Open alexwlchan opened this issue 4 years ago • 2 comments

Two changes:

  • If the user passes more entries in colalign than there are columns, quietly drop the extra alignment parameters. Closes #84 and #89.

    My original suggestion was to have a better error message here, but the library can do something sensible here – drop those extra arguments. In particular, the example of the empty table in #89 made me think dropping this error was better than throwing an error.

  • If the user passes a non tuple/list as the colalign argument, throw an error. This is the underlying issue in https://github.com/astanin/python-tabulate/issues/89#issuecomment-742673598, I think. It's definitely not going to do what the user expects, because the alignments are assigned character-by-character.

I added tests to cover these issues, plus a couple of other examples from the tickets that I wanted to check I hadn't broken.

alexwlchan avatar Feb 20 '21 19:02 alexwlchan

I appreciate better error reporting, but it would probably be more in the spirit of the library to handle a single colalign parameter as the one to be applied to all columns.

Something like this:

>>> print(tabulate([[1, 2], [345, 67890]], colalign="center", tablefmt="grid"))
+-----+-------+
|  1  |   2   |
+-----+-------+
| 345 | 67890 |
+-----+-------+

Related: #182

astanin avatar Jun 22 '22 13:06 astanin

I think it would be preferable not to confuse colalign (column-wise alignment) with with a global setting when only one string is given. Also, colalign can be many more things other than tupleor list. Thus, I think that throwing an error the way you do is a bit restrictive. Instead, I would only suggest warning the user and suggesting correct use case. Also, by adding a colglobalalign, we add the possibility to define a global setting, while specifically overridding this global setting for specific column with colalign. This idea is implemented in #219.

Example or warning when colalign or headersalign is a str:

>>> print(tabulate.tabulate([["a", "b", "c"],["aaa", "bbb", "ccc"]], colalign="center"))
Warning in `tabulate`: As a string, `colalign` is interpreted as ['c', 'e', 'n', 't', 'e', 'r']. Did you mean `colglobalalign = "center"` or `colalign = ("center",)`?
---  ---  ---
a    b    c
aaa  bbb  ccc
---  ---  ---

and the suggested corrections:

>>> print(tabulate.tabulate([["a", "b", "c"],["aaa", "bbb", "ccc"]], colglobalalign="center"))
---  ---  ---
 a    b    c
aaa  bbb  ccc
---  ---  ---
>>> print(tabulate.tabulate([["a", "b", "c"],["aaa", "bbb", "ccc"]], colalign=("center",)))
---  ---  ---
 a   b    c
aaa  bbb  ccc
---  ---  ---

eliegoudout avatar Nov 26 '22 16:11 eliegoudout

Closing as stale.

alexwlchan avatar Jun 03 '24 11:06 alexwlchan