Tableยถ
Click Extra provides a way to render tables in the terminal.
Tip
The selected --table-format value and the --sort-by priority list are published on ctx.meta as TABLE_FORMAT and SORT_BY. See the available keys table to read them from your own callbacks.
Here is how to use the standalone table rendering option decorator:
import click
from click_extra import pass_context, table_format_option, style, Color
@click.command
@table_format_option
@pass_context
def table_command(ctx):
headers = ("Day", "Temperature")
data = (
(1, 42.9),
("2", None),
(style("Friday", fg=Color.blue), style("Hot ๐ฅต", fg=Color.red, bold=True)),
)
ctx.print_table(data, headers)
The selected format feeds the ready-to-use print_table() method carried by the context object. The contextโs meta is shared along the command chain, so a --table-format declared on a group reaches ctx.print_table in every subcommand. On a plain click or cloup command (whose context lacks the click-extra methods), the option injects an equivalent bound print_table attribute instead.
The help screen names the value FORMAT rather than spelling out all fifty table formats, which would otherwise take over the screen:
$ table --help
Usage: table [OPTIONS]
Options:
--table-format FORMAT Rendering style of tables.
--help Show this message and exit.
The formats are all listed in the catalog below. A wrong one names them too, and so do --help-format man, markdown and json, which have room the help screen does not.
So you can use the --table-format option to change the table format:
$ table --table-format fancy-outline
โโโโโโโโโโคโโโโโโโโโโโโโโ
โ Day โ Temperature โ
โโโโโโโโโโชโโโโโโโโโโโโโโก
โ 1 โ 42.9 โ
โ 2 โ โ
โ Friday โ Hot ๐ฅต โ
โโโโโโโโโโงโโโโโโโโโโโโโโ
$ table --table-format asciidoc
[cols="<8,<13",options="header"]
|====
| Day | Temperature
| 1 | 42.9
| 2 |
| Friday | Hot ๐ฅต
|====
Tip
This example has been selected so you can see how print_table() handles:
Mixed data types (integers, floats,
None, strings)ANSI color codes (added with the
click_extra.style()function)Unicode characters (like the emojis)
Hint
Thereโs another method called render_table() carried by the context alongside print_table().
It works the same way, but instead of printing the table to the console, it returns the rendered table as a string.
Table formatsยถ
Table formats are aggregated from these sources:
Pythonโs
csvmodule from the standard libraryPythonโs
jsonmodule from the standard libraryhjson(requires the[hjson]extra)tomlrt(requires the[toml]extra)Pythonโs
xmlpackage from the standard libraryPyYAML(requires the[yaml]extra)
Theyโre divided in 2 categories:
Formats that produce plain text output (like ASCII tables, grid tables, etc.) and are often composed of Unicode box-drawing characters, to be displayed in a terminal.
Formats that produce markup language output (like HTML, Markdown, LaTeX, etc.) and are expected to be rendered by a supporting viewer. This category also includes CSV, TSV, and structured serialization formats (HJSON, JSON, JSON5, JSONC, TOML, XML, YAML), which are plain text but meant to be processed by other tools.
Tip
The default rounded-outline format draws its borders with Unicode box-drawing characters (โ, โญ, โ, โฆ) and aligns columns with padding. A screen reader announces those separators and the padding gaps as noise, and the column alignment is lost entirely once whitespace is collapsed.
For a screen-reader-friendly rendering, use --table-format plain: it keeps the tabular layout with no borders. For output that another program will parse, use a machine-readable format like csv. The --accessible flag bundles --table-format plain with --no-color in a single switch.
Format ID |
Description |
Implementation |
Markup |
|---|---|---|---|
|
Compact table with single-space column separators and no borders |
Click Extra |
โ |
|
|
โ |
|
|
Grid table using colons in the header separator to mark column alignment, per Pandocโs grid tables |
|
โ |
|
|
โ |
|
|
CSV with Excel dialect |
|
โ |
|
CSV with Excel tab dialect |
|
โ |
|
CSV with Unix dialect |
|
โ |
|
Double-line grid table |
|
โ |
|
Double-line outline table |
|
โ |
|
Grid with Unicode box-drawing characters |
|
โ |
|
Outline with Unicode box-drawing characters |
|
โ |
|
|
โ |
|
|
Grid table with ASCII characters, also supported by Pandoc and reStructuredText |
|
โ |
|
Heavy-line grid table |
|
โ |
|
Heavy-line outline table |
|
โ |
|
HJSON array of objects |
โ |
|
|
|
โ |
|
|
|
โ |
|
|
JSON array of objects |
|
โ |
|
Alias for |
|
โ |
|
Alias for |
|
โ |
|
|
โ |
|
|
|
โ |
|
|
|
โ |
|
|
LaTeX table without escaping |
|
โ |
|
|
โ |
|
|
Mixed-line grid table |
|
โ |
|
Mixed-line outline table |
|
โ |
|
|
โ |
|
|
|
โ |
|
|
Simple outline table |
|
โ |
|
|
โ |
|
|
Plain text, no formatting |
|
โ |
|
Presto SQL output style |
|
โ |
|
Pretty ASCII table |
|
โ |
|
PostgreSQL output style |
|
โ |
|
Rounded grid table |
|
โ |
|
Rounded outline table |
|
โ |
|
|
โ |
|
|
Simple table with spaces, also supported by Pandoc |
|
โ |
|
Simple grid table |
|
โ |
|
Simple outline table |
|
โ |
|
|
โ |
|
|
TOML array of tables |
โ |
|
|
|
โ |
|
|
HTML table without escaping |
|
โ |
|
Vertical table layout |
Click Extra |
โ |
|
XML document |
|
โ |
|
YAML sequence of mappings |
โ |
|
|
|
โ |
Colors and stylesยถ
Cells and headers can carry ANSI styles, produced by click_extra.style() or a theme. What happens to these codes depends on the format family:
Plain-text formats keep them raw. The final
echo()call then honors the global colorization settings, so styles show on a capable terminal and are stripped when piped or under--no-color.Markup formats able to express styles natively translate them to the formatโs own styling markup. This is the default: pass
--no-color(or setNO_COLOR) to get plain markup instead.All other markup formats strip them from cell values before rendering, to avoid leaking escape sequences into structured content. Force
--colorto keep the raw ANSI codes anyway.
The formats translating ANSI codes to native styling, and the markup they produce:
Format ID |
Native styling markup |
|---|---|
|
Inline-CSS |
|
|
|
|
|
Inline-CSS |
|
|
Every other markup format keeps stripping ANSI codes. The verdict, format by format:
Format ID |
Why ANSI codes are stripped |
|---|---|
|
No portable inline styling: color roles need a custom stylesheet, and |
|
Data interchange formats, with no concept of styling |
|
GitHub sanitizes inline |
|
Structured serialization formats meant for programmatic consumption: styling is presentation, not data |
|
MoinMoin wiki markup has no standard inline color syntax, and embedded HTML is disabled by default |
|
Org-mode has emphasis markers but no inline color markup |
|
reStructuredText needs custom roles backed by a stylesheet for inline color; there is no standard inline syntax |
|
Undocumented by JetBrains, and scheduled for removal in python-tabulate |
Here is the translation at work: the blue Friday and bold red Hot ๐ฅต cells of the example command come out as self-contained HTML:
$ table --table-format unsafehtml
<table>
<thead>
<tr><th>Day </th><th>Temperature</th></tr>
</thead>
<tbody>
<tr><td>1 </td><td>42.9 </td></tr>
<tr><td>2 </td><td> </td></tr>
<tr><td><span style="color: blue">Friday</span></td><td><span style="color: red; font-weight: bold">Hot ๐ฅต</span> </td></tr>
</tbody>
</table>
While the same cells are stripped down to plain text in a format without styling support:
$ table --table-format github
| Day | Temperature |
| :----- | :---------- |
| 1 | 42.9 |
| 2 | |
| Friday | Hot ๐ฅต |
Hint
The translation maps each ANSI attribute to its closest equivalent, and drops those the target cannot express (like blink in CSS, or backgrounds in Jira markup). Colors keep their terminal semantics: a white cell on a white page renders invisible, as it would on a white terminal. The underlying converters are also available as standalone functions: see ansi_to_html() and friends.
Tip
Use the built-in demo subcommands to verify how ANSI codes are handled by each format:
$ uvx click-extra --table-format unsafehtml styles
$ uvx click-extra --table-format json colors
The first command renders the whole style matrix as a colored HTML page you can redirect to a file and open in a browser.
$ table --table-format aligned
Day Temperature
1 42.9
2
Friday Hot ๐ฅต
$ table --table-format asciidoc
[cols="<8,<13",options="header"]
|====
| Day | Temperature
| 1 | 42.9
| 2 |
| Friday | Hot ๐ฅต
|====
$ table --table-format colon-grid
+--------+-------------+
| Day | Temperature |
+:=======+:============+
| 1 | 42.9 |
+--------+-------------+
| 2 | |
+--------+-------------+
| Friday | Hot ๐ฅต |
+--------+-------------+
$ table --table-format csv
Day,Temperature
1,42.9
2,
Friday,Hot ๐ฅต
$ table --table-format csv-excel
Day,Temperature
1,42.9
2,
Friday,Hot ๐ฅต
$ table --table-format csv-excel-tab
Day Temperature
1 42.9
2
Friday Hot ๐ฅต
$ table --table-format csv-unix
"Day","Temperature"
"1","42.9"
"2",""
"Friday","Hot ๐ฅต"
$ table --table-format double-grid
โโโโโโโโโโฆโโโโโโโโโโโโโโ
โ Day โ Temperature โ
โ โโโโโโโโโฌโโโโโโโโโโโโโโฃ
โ 1 โ 42.9 โ
โ โโโโโโโโโฌโโโโโโโโโโโโโโฃ
โ 2 โ โ
โ โโโโโโโโโฌโโโโโโโโโโโโโโฃ
โ Friday โ Hot ๐ฅต โ
โโโโโโโโโโฉโโโโโโโโโโโโโโ
$ table --table-format double-outline
โโโโโโโโโโฆโโโโโโโโโโโโโโ
โ Day โ Temperature โ
โ โโโโโโโโโฌโโโโโโโโโโโโโโฃ
โ 1 โ 42.9 โ
โ 2 โ โ
โ Friday โ Hot ๐ฅต โ
โโโโโโโโโโฉโโโโโโโโโโโโโโ
$ table --table-format fancy-grid
โโโโโโโโโโคโโโโโโโโโโโโโโ
โ Day โ Temperature โ
โโโโโโโโโโชโโโโโโโโโโโโโโก
โ 1 โ 42.9 โ
โโโโโโโโโโผโโโโโโโโโโโโโโค
โ 2 โ โ
โโโโโโโโโโผโโโโโโโโโโโโโโค
โ Friday โ Hot ๐ฅต โ
โโโโโโโโโโงโโโโโโโโโโโโโโ
$ table --table-format fancy-outline
โโโโโโโโโโคโโโโโโโโโโโโโโ
โ Day โ Temperature โ
โโโโโโโโโโชโโโโโโโโโโโโโโก
โ 1 โ 42.9 โ
โ 2 โ โ
โ Friday โ Hot ๐ฅต โ
โโโโโโโโโโงโโโโโโโโโโโโโโ
$ table --table-format github
| Day | Temperature |
| :----- | :---------- |
| 1 | 42.9 |
| 2 | |
| Friday | Hot ๐ฅต |
$ table --table-format grid
+--------+-------------+
| Day | Temperature |
+========+=============+
| 1 | 42.9 |
+--------+-------------+
| 2 | |
+--------+-------------+
| Friday | Hot ๐ฅต |
+--------+-------------+
$ table --table-format heavy-grid
โโโโโโโโโโณโโโโโโโโโโโโโโ
โ Day โ Temperature โ
โฃโโโโโโโโโโโโโโโโโโโโโโโซ
โ 1 โ 42.9 โ
โฃโโโโโโโโโโโโโโโโโโโโโโโซ
โ 2 โ โ
โฃโโโโโโโโโโโโโโโโโโโโโโโซ
โ Friday โ Hot ๐ฅต โ
โโโโโโโโโโปโโโโโโโโโโโโโโ
$ table --table-format heavy-outline
โโโโโโโโโโณโโโโโโโโโโโโโโ
โ Day โ Temperature โ
โฃโโโโโโโโโโโโโโโโโโโโโโโซ
โ 1 โ 42.9 โ
โ 2 โ โ
โ Friday โ Hot ๐ฅต โ
โโโโโโโโโโปโโโโโโโโโโโโโโ
$ table --table-format hjson
[
{
Day: 1
Temperature: 42.9
}
{
Day: "2"
Temperature: null
}
{
Day: Friday
Temperature: Hot ๐ฅต
}
]
$ table --table-format html
<table>
<thead>
<tr><th>Day </th><th>Temperature</th></tr>
</thead>
<tbody>
<tr><td>1 </td><td>42.9 </td></tr>
<tr><td>2 </td><td> </td></tr>
<tr><td><span style="color: blue">Friday</span></td><td><span style="color: red; font-weight: bold">Hot ๐ฅต</span> </td></tr>
</tbody>
</table>
$ table --table-format jira
|| Day || Temperature ||
| 1 | 42.9 |
| 2 | |
| {color:blue}Friday{color} | {color:red}*Hot ๐ฅต*{color} |
$ table --table-format json
[
{
"Day": 1,
"Temperature": 42.9
},
{
"Day": "2",
"Temperature": null
},
{
"Day": "Friday",
"Temperature": "Hot ๐ฅต"
}
]
$ table --table-format json5
[
{
"Day": 1,
"Temperature": 42.9
},
{
"Day": "2",
"Temperature": null
},
{
"Day": "Friday",
"Temperature": "Hot ๐ฅต"
}
]
$ table --table-format jsonc
[
{
"Day": 1,
"Temperature": 42.9
},
{
"Day": "2",
"Temperature": null
},
{
"Day": "Friday",
"Temperature": "Hot ๐ฅต"
}
]
$ table --table-format latex
\begin{tabular}{ll}
\hline
Day & Temperature \\
\hline
1 & 42.9 \\
2 & \\
\textcolor{blue}{Friday} & \textcolor{red}{\textbf{Hot ๐ฅต}} \\
\hline
\end{tabular}
$ table --table-format latex-booktabs
\begin{tabular}{ll}
\toprule
Day & Temperature \\
\midrule
1 & 42.9 \\
2 & \\
\textcolor{blue}{Friday} & \textcolor{red}{\textbf{Hot ๐ฅต}} \\
\bottomrule
\end{tabular}
$ table --table-format latex-longtable
\begin{longtable}{ll}
\hline
Day & Temperature \\
\hline
\endhead
1 & 42.9 \\
2 & \\
\textcolor{blue}{Friday} & \textcolor{red}{\textbf{Hot ๐ฅต}} \\
\hline
\end{longtable}
$ table --table-format latex-raw
\begin{tabular}{ll}
\hline
Day & Temperature \\
\hline
1 & 42.9 \\
2 & \\
\textcolor{blue}{Friday} & \textcolor{red}{\textbf{Hot ๐ฅต}} \\
\hline
\end{tabular}
$ table --table-format mediawiki
{| class="wikitable" style="text-align: left;"
|+ <!-- caption -->
|-
! Day !! Temperature
|-
| 1 || 42.9
|-
| 2 ||
|-
| <span style="color: blue">Friday</span> || <span style="color: red; font-weight: bold">Hot ๐ฅต</span>
|}
$ table --table-format mixed-grid
โโโโโโโโโโฏโโโโโโโโโโโโโโ
โ Day โ Temperature โ
โโโโโโโโโโฟโโโโโโโโโโโโโโฅ
โ 1 โ 42.9 โ
โโโโโโโโโโผโโโโโโโโโโโโโโค
โ 2 โ โ
โโโโโโโโโโผโโโโโโโโโโโโโโค
โ Friday โ Hot ๐ฅต โ
โโโโโโโโโโทโโโโโโโโโโโโโโ
$ table --table-format mixed-outline
โโโโโโโโโโฏโโโโโโโโโโโโโโ
โ Day โ Temperature โ
โโโโโโโโโโฟโโโโโโโโโโโโโโฅ
โ 1 โ 42.9 โ
โ 2 โ โ
โ Friday โ Hot ๐ฅต โ
โโโโโโโโโโทโโโโโโโโโโโโโโ
$ table --table-format moinmoin
|| ''' Day ''' || ''' Temperature ''' ||
|| 1 || 42.9 ||
|| 2 || ||
|| Friday || Hot ๐ฅต ||
$ table --table-format orgtbl
| Day | Temperature |
|--------+-------------|
| 1 | 42.9 |
| 2 | |
| Friday | Hot ๐ฅต |
$ table --table-format outline
+--------+-------------+
| Day | Temperature |
+========+=============+
| 1 | 42.9 |
| 2 | |
| Friday | Hot ๐ฅต |
+--------+-------------+
$ table --table-format pipe
| Day | Temperature |
| :----- | :---------- |
| 1 | 42.9 |
| 2 | |
| Friday | Hot ๐ฅต |
$ table --table-format plain
Day Temperature
1 42.9
2
Friday Hot ๐ฅต
$ table --table-format presto
Day | Temperature
--------+-------------
1 | 42.9
2 |
Friday | Hot ๐ฅต
$ table --table-format pretty
+--------+-------------+
| Day | Temperature |
+--------+-------------+
| 1 | 42.9 |
| 2 | |
| Friday | Hot ๐ฅต |
+--------+-------------+
$ table --table-format psql
+--------+-------------+
| Day | Temperature |
|--------+-------------|
| 1 | 42.9 |
| 2 | |
| Friday | Hot ๐ฅต |
+--------+-------------+
$ table --table-format rounded-grid
โญโโโโโโโโโฌโโโโโโโโโโโโโโฎ
โ Day โ Temperature โ
โโโโโโโโโโผโโโโโโโโโโโโโโค
โ 1 โ 42.9 โ
โโโโโโโโโโผโโโโโโโโโโโโโโค
โ 2 โ โ
โโโโโโโโโโผโโโโโโโโโโโโโโค
โ Friday โ Hot ๐ฅต โ
โฐโโโโโโโโโดโโโโโโโโโโโโโโฏ
$ table --table-format rounded-outline
โญโโโโโโโโโฌโโโโโโโโโโโโโโฎ
โ Day โ Temperature โ
โโโโโโโโโโผโโโโโโโโโโโโโโค
โ 1 โ 42.9 โ
โ 2 โ โ
โ Friday โ Hot ๐ฅต โ
โฐโโโโโโโโโดโโโโโโโโโโโโโโฏ
$ table --table-format rst
====== ===========
Day Temperature
====== ===========
1 42.9
2
Friday Hot ๐ฅต
====== ===========
$ table --table-format simple
Day Temperature
------ -----------
1 42.9
2
Friday Hot ๐ฅต
$ table --table-format simple-grid
โโโโโโโโโโฌโโโโโโโโโโโโโโ
โ Day โ Temperature โ
โโโโโโโโโโผโโโโโโโโโโโโโโค
โ 1 โ 42.9 โ
โโโโโโโโโโผโโโโโโโโโโโโโโค
โ 2 โ โ
โโโโโโโโโโผโโโโโโโโโโโโโโค
โ Friday โ Hot ๐ฅต โ
โโโโโโโโโโดโโโโโโโโโโโโโโ
$ table --table-format simple-outline
โโโโโโโโโโฌโโโโโโโโโโโโโโ
โ Day โ Temperature โ
โโโโโโโโโโผโโโโโโโโโโโโโโค
โ 1 โ 42.9 โ
โ 2 โ โ
โ Friday โ Hot ๐ฅต โ
โโโโโโโโโโดโโโโโโโโโโโโโโ
$ table --table-format textile
|_. Day |_. Temperature |
|<. 1 |<. 42.9 |
|<. 2 |<. |
|<. %{color: blue}Friday% |<. %{color: red; font-weight: bold}Hot ๐ฅต% |
$ table --table-format toml
[[record]]
Day = 1
Temperature = 42.9
[[record]]
Day = "2"
[[record]]
Day = "Friday"
Temperature = "Hot ๐ฅต"
$ table --table-format tsv
Day Temperature
1 42.9
2
Friday Hot ๐ฅต
$ table --table-format unsafehtml
<table>
<thead>
<tr><th>Day </th><th>Temperature</th></tr>
</thead>
<tbody>
<tr><td>1 </td><td>42.9 </td></tr>
<tr><td>2 </td><td> </td></tr>
<tr><td><span style="color: blue">Friday</span></td><td><span style="color: red; font-weight: bold">Hot ๐ฅต</span> </td></tr>
</tbody>
</table>
$ table --table-format vertical
***************************[ 1. row ]***************************
Day | 1
Temperature | 42.9
***************************[ 2. row ]***************************
Day | 2
Temperature |
***************************[ 3. row ]***************************
Day | Friday
Temperature | Hot ๐ฅต
$ table --table-format xml
<records>
<record>
<Day>1</Day>
<Temperature>42.9</Temperature>
</record>
<record>
<Day>2</Day>
</record>
<record>
<Day>Friday</Day>
<Temperature>Hot ๐ฅต</Temperature>
</record>
</records>
$ table --table-format yaml
- Day: 1
Temperature: 42.9
- Day: '2'
Temperature: null
- Day: Friday
Temperature: Hot ๐ฅต
$ table --table-format youtrack
|| Day || Temperature ||
| 1 | 42.9 |
| 2 | |
| Friday | Hot ๐ฅต |
Two-axis tablesยถ
When both the rows and the columns list values, like temperatures by city and month, the top-left cell can name both axes. corner_header() builds that cell:
from click_extra import command, corner_header, pass_context
@command
@pass_context
def climate(ctx):
"""Print average high temperatures, in ยฐC."""
headers = (corner_header("City", "Month"), "Jan", "Apr", "Jul", "Oct")
data = (
("Paris", 7, 16, 25, 16),
("Oslo", 0, 10, 22, 10),
)
ctx.print_table(data, headers)
$ climate
โญโโโโโโโโโโโโโโโโโโโฌโโโโโโฌโโโโโโฌโโโโโโฌโโโโโโฎ
โ City โด \ Month โ โ Jan โ Apr โ Jul โ Oct โ
โโโโโโโโโโโโโโโโโโโโผโโโโโโผโโโโโโผโโโโโโผโโโโโโค
โ Paris โ 7 โ 16 โ 25 โ 16 โ
โ Oslo โ 0 โ 10 โ 22 โ 10 โ
โฐโโโโโโโโโโโโโโโโโโโดโโโโโโดโโโโโโดโโโโโโดโโโโโโฏ
The rows read downward from City, and the columns rightward from Month. The matrix directive labels its compatibility tables the same way.
In a Sphinx build, the click_extra.sphinx extension keeps the first column of a table with such a label on one line. On a narrow screen, the table scrolls sideways instead of wrapping its row labels. Any table gets it when its top-left cell holds the โด arrow. It also highlights the row and the column under the pointer: see Crosshair on two-axis tables. A cell holding โ
, โ or โ alone, like those of a compatibility matrix, is tinted green, red or grey.
Column widthsยถ
A long cell stretches its column until the table runs off the terminal. max_column_widths caps it, wrapping the overflow onto extra lines while keeping it a single cell. Pass one entry per column, None leaving a column unbounded:
from click_extra import command, pass_context
@command
@pass_context
def forecast(ctx):
"""Report the weather of a few cities."""
headers = ("City", "Forecast")
data = (
("Paris", "Overcast in the morning, with a light drizzle after midday."),
("Oslo", "Clear, turning colder overnight."),
)
ctx.print_table(data, headers, max_column_widths=[None, 30])
$ forecast
โญโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ City โ Forecast โ
โโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Paris โ Overcast in the morning, with โ
โ โ a light drizzle after midday. โ
โ Oslo โ Clear, turning colder โ
โ โ overnight. โ
โฐโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
A single value stands in for the whole table (max_column_widths=30 caps every column), and a list shorter than the table leaves its trailing columns unbounded.
Widths on column definitionsยถ
A width can also be declared on the ColumnSpec describing the column, which applies without passing any argument:
from click_extra import command, pass_context
from click_extra.columns import ColumnSpec
COLUMNS = (
ColumnSpec(id="city", label="City"),
ColumnSpec(id="forecast", label="Forecast", max_width=30),
)
@command
@pass_context
def declared_forecast(ctx):
"""Cap a column from its own definition."""
data = (
("Paris", "Overcast in the morning, with a light drizzle after midday."),
("Oslo", "Clear, turning colder overnight."),
)
ctx.print_table(data, COLUMNS)
$ declared-forecast
โญโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ City โ Forecast โ
โโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Paris โ Overcast in the morning, with โ
โ โ a light drizzle after midday. โ
โ Oslo โ Clear, turning colder โ
โ โ overnight. โ
โฐโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
Declaring it here rather than in a positional list keeps the width attached to its column, so it survives a columns_option projection that drops or reorders columns, where a positional list would shift onto the wrong columns. An explicit max_column_widths argument overrides it.
Auto widthยถ
"auto" hands a column whatever the terminal has left, once the decoration of the format and the width of the other columns are paid for. Several auto columns share that remainder: a column whose content fits in an even share keeps its natural width, and the others split the rest of its share. No auto column is ever resolved below MIN_COLUMN_WIDTH:
from click_extra import command, pass_context
@command(context_settings={"terminal_width": 60})
@pass_context
def narrow_forecast(ctx):
"""Fit the forecast to a 60-column terminal."""
headers = ("City", "Forecast")
data = (
("Paris", "Overcast in the morning, with a light drizzle after midday."),
("Oslo", "Clear, turning colder overnight."),
)
ctx.print_table(data, headers, max_column_widths=[None, "auto"])
$ narrow-forecast
โญโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ City โ Forecast โ
โโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Paris โ Overcast in the morning, with a light drizzle โ
โ โ after midday. โ
โ Oslo โ Clear, turning colder overnight. โ
โฐโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
A table spans the whole terminal. max_content_width caps the help screens only, at 80 columns by default, to keep their prose readable. The terminal_width context setting overrides the terminal, as in the example above, and so does the 80-column width that CliRunner forces while a command runs.
Formats honoring widthsยถ
Wrapping a cell over several lines only makes sense for a format laying out text. Widths are silently dropped by every other one, the same way styling degrades per format: a width forced into a CSV field or a JSON string would change the data instead of its presentation, and one forced into Markdown would turn the continuation lines into extra rows.
from click_extra.table import TableFormat
# Text layouts wrap.
assert TableFormat.ROUNDED_OUTLINE.is_wrappable
assert TableFormat.VERTICAL.is_wrappable
# Data interchange and serialization never do.
assert not TableFormat.CSV.is_wrappable
assert not TableFormat.JSON.is_wrappable
# Nor do markups whose continuation lines would read as extra rows.
assert not TableFormat.GITHUB.is_wrappable
WRAPPABLE_FORMATS holds the full registry, and documents the verdict format by format.
Get table formatยถ
You can get the ID of the current table format from the context:
import click
from click_extra import echo, pass_context, table_format_option
@click.command
@table_format_option
@pass_context
def vanilla_command(ctx):
format_id = ctx.meta["click_extra.table_format"]
echo(f"Table format: {format_id}")
data = ((1, 87), (2, 80), (3, 79))
headers = ("day", "temperature")
ctx.print_table(data, headers)
$ vanilla --table-format fancy-outline
Table format: fancy-outline
โโโโโโโคโโโโโโโโโโโโโโ
โ day โ temperature โ
โโโโโโโชโโโโโโโโโโโโโโก
โ 1 โ 87 โ
โ 2 โ 80 โ
โ 3 โ 79 โ
โโโโโโโงโโโโโโโโโโโโโโ
Data serializationยถ
print_data() and serialize_data() handle arbitrary data structures (nested dicts, lists, scalars), unlike print_table() which expects tabular rows and headers. They support the structured serialization formats: JSON, HJSON, YAML, TOML, and XML.
from click_extra import command, pass_context, table_format_option
from click_extra.table import print_data
@command
@table_format_option
@pass_context
def data_command(ctx):
"""Serialize nested data."""
data = {
"city": "Paris",
"population": 2161000,
"landmarks": ["Eiffel Tower", "Louvre", "Notre-Dame"],
}
table_format = ctx.meta["click_extra.table_format"]
print_data(data, table_format)
$ data --table-format json
{
"city": "Paris",
"population": 2161000,
"landmarks": [
"Eiffel Tower",
"Louvre",
"Notre-Dame"
]
}
$ data --table-format yaml
city: Paris
landmarks:
- Eiffel Tower
- Louvre
- Notre-Dame
population: 2161000
serialize_data() returns the serialized string instead of printing it:
Sorted tablesยถ
The @sort_by_option decorator adds a --sort-by CLI option whose choices are derived from column definitions. Column definitions are ColumnSpec instances. A column marked sortable=False is displayed but not offered as a sort choice.
The option can be repeated to define a multi-column sort priority: --sort-by name --sort-by age sorts by name first, then breaks ties by age.
When active, SortByOption publishes the derived sort key on the context, where ctx.print_table picks it up.
from click_extra import command, pass_context, sort_by_option
from click_extra.columns import ColumnSpec
@command
@sort_by_option(
ColumnSpec("fruit", "Fruit"),
ColumnSpec("count", "Count"),
ColumnSpec("notes", "Notes", sortable=False),
)
@pass_context
def inventory(ctx):
"""Sortable fruit inventory."""
headers = ("Fruit", "Count", "Notes")
data = [
["Cherry", "50", "seasonal"],
["Apple", "120", ""],
["Banana", "80", "organic"],
]
ctx.print_table(data, headers)
$ inventory --help
Usage: inventory [OPTIONS]
Sortable fruit inventory.
Options:
--sort-by [fruit|count] Sort table by this column. Repeat to set
priority. [default: fruit]
-h, --help Show this message and exit.
Configuration options:
--config LOCATION Location of the configuration file. Supports
local path with glob patterns or remote URL.
[default: ~/.config/inventory/]
--no-config Ignore all configuration files and only use
command line parameters and environment
variables.
--validate-config LOCATION Validate the configuration file and exit.
--export-config FORMAT Export the configuration in the selected format
to <stdout>, then exit.
Output options:
--accessible Accessibility mode: disable colors and render
tables in a borderless, screen-reader-friendly
format.
--color [auto|always|never] Colorize the output. A bare --color is the same
as --color=always. [default: auto]
--no-color Disable colorization (alias of --color=never).
--progress / --no-progress Show progress indicators during long operations.
Disabled for non-interactive output (pipes, dumb
terminals, CI) and by --accessible. [default:
progress]
--theme [auto|dark|dracula|light|manpage|monokai|nord|solarized-dark]
Color theme used for help screens. [default:
dark]
--table-format FORMAT Rendering style of tables. [default: rounded-
outline]
Logging options:
--verbosity LEVEL Either CRITICAL, ERROR, WARNING, INFO, DEBUG.
[default: WARNING]
-v, --verbose Increase the default WARNING verbosity by one
level for each additional repetition of the
option. [default: 0]
-q, --quiet Decrease the default WARNING verbosity by one
level for each additional repetition of the
option. [default: 0]
--debug Shorthand for --verbosity DEBUG.
Introspection options:
--time / --no-time Measure and print elapsed execution time.
[default: no-time]
--params Show all CLI parameters, their provenance,
defaults and value, then exit.
--tree Show the tree of nested subcommands and exit.
--man Read the command's manual page and exit.
--help-format [carapace|json|json-full|man|markdown|markdown-full]
Render the command in the given format and exit.
--version Show the version and exit.
$ inventory --table-format rounded-outline --sort-by fruit
โญโโโโโโโโโฌโโโโโโโโฌโโโโโโโโโโโฎ
โ Fruit โ Count โ Notes โ
โโโโโโโโโโผโโโโโโโโผโโโโโโโโโโโค
โ Apple โ 120 โ โ
โ Banana โ 80 โ organic โ
โ Cherry โ 50 โ seasonal โ
โฐโโโโโโโโโดโโโโโโโโดโโโโโโโโโโโฏ
$ inventory --table-format rounded-outline --sort-by count
โญโโโโโโโโโฌโโโโโโโโฌโโโโโโโโโโโฎ
โ Fruit โ Count โ Notes โ
โโโโโโโโโโผโโโโโโโโผโโโโโโโโโโโค
โ Apple โ 120 โ โ
โ Cherry โ 50 โ seasonal โ
โ Banana โ 80 โ organic โ
โฐโโโโโโโโโดโโโโโโโโดโโโโโโโโโโโฏ
Repeating --sort-by sets multi-column priority. Here, rows are sorted by count first, then ties broken by fruit name:
$ inventory --table-format rounded-outline --sort-by count --sort-by fruit
โญโโโโโโโโโฌโโโโโโโโฌโโโโโโโโโโโฎ
โ Fruit โ Count โ Notes โ
โโโโโโโโโโผโโโโโโโโผโโโโโโโโโโโค
โ Apple โ 120 โ โ
โ Cherry โ 50 โ seasonal โ
โ Banana โ 80 โ organic โ
โฐโโโโโโโโโดโโโโโโโโดโโโโโโโโโโโฏ
To keep --sort-by and --columns in sync, pass the same ColumnSpec registry to both via columns=. A single source of truth then drives column selection, column order and sort choices:
from click_extra import columns_option, command, pass_context, sort_by_option
from click_extra.columns import ColumnSpec
COLUMNS = (
ColumnSpec("fruit", "Fruit"),
ColumnSpec("count", "Count"),
)
@command
@columns_option(columns=COLUMNS)
@sort_by_option(columns=COLUMNS)
@pass_context
def stock(ctx):
"""Fruit stock, sortable and column-selectable from one registry."""
data = [["Cherry", "50"], ["Apple", "120"], ["Banana", "80"]]
ctx.print_table(data, [col.label for col in COLUMNS])
$ stock --help
Usage: stock [OPTIONS]
Fruit stock, sortable and column-selectable from one registry.
Options:
--columns COLUMNS Restrict and reorder table columns, SQL SELECT-
style. Comma-separated list of column IDs.
Default: all columns in canonical order.
--sort-by [fruit|count] Sort table by this column. Repeat to set
priority. [default: fruit]
-h, --help Show this message and exit.
Configuration options:
--config LOCATION Location of the configuration file. Supports
local path with glob patterns or remote URL.
[default: ~/.config/stock/]
--no-config Ignore all configuration files and only use
command line parameters and environment
variables.
--validate-config LOCATION Validate the configuration file and exit.
--export-config FORMAT Export the configuration in the selected format
to <stdout>, then exit.
Output options:
--accessible Accessibility mode: disable colors and render
tables in a borderless, screen-reader-friendly
format.
--color [auto|always|never] Colorize the output. A bare --color is the same
as --color=always. [default: auto]
--no-color Disable colorization (alias of --color=never).
--progress / --no-progress Show progress indicators during long operations.
Disabled for non-interactive output (pipes, dumb
terminals, CI) and by --accessible. [default:
progress]
--theme [auto|dark|dracula|light|manpage|monokai|nord|solarized-dark]
Color theme used for help screens. [default:
dark]
--table-format FORMAT Rendering style of tables. [default: rounded-
outline]
Logging options:
--verbosity LEVEL Either CRITICAL, ERROR, WARNING, INFO, DEBUG.
[default: WARNING]
-v, --verbose Increase the default WARNING verbosity by one
level for each additional repetition of the
option. [default: 0]
-q, --quiet Decrease the default WARNING verbosity by one
level for each additional repetition of the
option. [default: 0]
--debug Shorthand for --verbosity DEBUG.
Introspection options:
--time / --no-time Measure and print elapsed execution time.
[default: no-time]
--params Show all CLI parameters, their provenance,
defaults and value, then exit.
--tree Show the tree of nested subcommands and exit.
--man Read the command's manual page and exit.
--help-format [carapace|json|json-full|man|markdown|markdown-full]
Render the command in the given format and exit.
--version Show the version and exit.
$ stock --table-format rounded-outline --sort-by fruit
โญโโโโโโโโโฌโโโโโโโโฎ
โ Fruit โ Count โ
โโโโโโโโโโผโโโโโโโโค
โ Apple โ 120 โ
โ Banana โ 80 โ
โ Cherry โ 50 โ
โฐโโโโโโโโโดโโโโโโโโฏ
One --sort-by across subcommandsยถ
A CLI whose subcommands render different tables can still share a single --sort-by, declared once on the group. Pass bare column IDs instead of column definitions: they declare a field vocabulary untied to any single table layout, so no sort key is published at declaration time.
Each table then declares which field its columns carry, by passing ColumnSpec instances as print_table() headers, and plain labels for the columns carrying no field. The selection is resolved per table: rows sort by the selected fields the table carries (in selection order, remaining columns breaking ties left to right), and keep their original order when the table carries none of them.
from click_extra import group, sort_by_option
from click_extra.columns import ColumnSpec
from click_extra.table import TableFormat, print_table
@group
@sort_by_option("fruit", "price", default=())
def cli():
"""Subcommands render heterogeneous tables, sorted from one option."""
@cli.command()
def fruits():
"""Table carrying the `fruit` field."""
print_table(
[["Cherry", "50"], ["Apple", "120"], ["Banana", "80"]],
[ColumnSpec("fruit", "Fruit"), "Count"],
table_format=TableFormat.ROUNDED_OUTLINE,
)
@cli.command()
def cities():
"""Table carrying none of the vocabulary fields."""
print_table(
[["Paris", "2M"], ["London", "9M"]],
[ColumnSpec("city", "City"), "Population"],
table_format=TableFormat.ROUNDED_OUTLINE,
)
The fruits table carries the selected field, so its rows sort by it:
$ cli --sort-by fruit fruits
โญโโโโโโโโโฌโโโโโโโโฎ
โ Fruit โ Count โ
โโโโโโโโโโผโโโโโโโโค
โ Apple โ 120 โ
โ Banana โ 80 โ
โ Cherry โ 50 โ
โฐโโโโโโโโโดโโโโโโโโฏ
The cities table carries none of the vocabulary fields, so the same selection leaves its rows untouched:
$ cli --sort-by fruit cities
โญโโโโโโโโโฌโโโโโโโโโโโโโฎ
โ City โ Population โ
โโโโโโโโโโผโโโโโโโโโโโโโค
โ Paris โ 2M โ
โ London โ 9M โ
โฐโโโโโโโโโดโโโโโโโโโโโโโฏ
The default=() in the declaration above means bare invocations keep the original row order. Leave default unset to derive the first vocabulary field as the default sort, like the single-table mode does.
For programmatic use without a CLI option, render_table() accepts a sort_key callable:
from click_extra import command, echo
from click_extra.table import render_table, TableFormat
@command
def sorted_demo():
"""Render a table sorted alphabetically."""
data = [["Cherry", "50"], ["Apple", "120"], ["Banana", "80"]]
output = render_table(
data,
headers=["Fruit", "Count"],
table_format=TableFormat.ROUNDED_OUTLINE,
sort_key=lambda row: row[0],
)
echo(output)
$ sorted-demo
โญโโโโโโโโโฌโโโโโโโโฎ
โ Fruit โ Count โ
โโโโโโโโโโผโโโโโโโโค
โ Apple โ 120 โ
โ Banana โ 80 โ
โ Cherry โ 50 โ
โฐโโโโโโโโโดโโโโโโโโฏ