click_extra.table_options module¶
classDiagram
ExtraOption <|-- ColumnsOption
ExtraOption <|-- SortByOption
ExtraOption <|-- TableFormatOption
MultiChoice <|-- ColumnsType
Options to pick a table’s format, sort its rows and select its columns.
--table-format, --sort-by and --columns publish their choice on the
context, where the renderers of click_extra.table read it.
- class click_extra.table_options.TableFormatOption(param_decls=None, *, type=EnumChoice('aligned', 'asciidoc', 'colon-grid', 'csv', 'csv-excel', 'csv-excel-tab', 'csv-unix', 'double-grid', 'double-outline', 'fancy-grid', 'fancy-outline', 'github', 'grid', 'heavy-grid', 'heavy-outline', 'hjson', 'html', 'jira', 'json', 'json5', 'jsonc', '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', 'toml', 'tsv', 'unsafehtml', 'vertical', 'xml', 'yaml', 'youtrack'), metavar='FORMAT', default=TableFormat.ROUNDED_OUTLINE, expose_value=False, is_eager=True, help='Rendering style of tables.', **kwargs)[source]¶
Bases:
ExtraOptionA pre-configured option that is adding a
--table-formatflag to select the rendering style of a table.The selected table format ID is made available in the context in
ctx.meta[click_extra.context.TABLE_FORMAT], where therender_table()andprint_table()context methods pick it up as their default format.ctx.metais shared along the context chain, so declaring this option on a group makes the selected format reach every subcommand:ctx.render_table(table_data, headers, **kwargs): renders and returns the table as a string,ctx.print_table(table_data, headers, **kwargs): renders and prints the table to the console.
Where:
table_datais a 2-dimensional iterable of iterables for rows and cells values,headersis a list of string to be used as column headers,**kwargsare any extra keyword arguments supported by the underlying table formatting function.
- init_formatter(ctx, param, table_format)[source]¶
Save the resolved
table_formatin the context’s sharedmeta.The
render_table()andprint_table()context methods read it back at call time.- Return type:
- click_extra.table_options.column_sort_key(header_defs, sort_columns=None, cell_key=None)[source]¶
Build a row sort key from the
sort_columnsa table actually carries.header_defsdescribes the rendered columns:ColumnSpecinstances, withsortable=Falsefor columns that cannot be sorted on. The requestedsort_columnsthe table carries drive the comparison first, de-duplicated and in request order; the remaining columns follow in their natural left-to-right order for tie-breaking.Returns
Nonewhen the table carries none of the requested columns, signalling that rows should keep their original order. This is what lets one--sort-byselection apply across subcommands rendering heterogeneous tables: each table sorts by the requested fields it knows, and a table knowing none of them is left untouched.
- class click_extra.table_options.ColumnsType(choices=())[source]¶
Bases:
MultiChoiceMultiChoiceover the IDs of table columns.Pins the comma separator and case-sensitive matching (column IDs are snake_case identifiers, not free-form strings), and renames the metavar fallback to
COLUMNSinstead of the genericMULTI.Initialize the type.
- Parameters:
choices (
Sequence[str]) – the accepted values. When non-empty,convert()rejects unknown tokens withfail. When empty, the type behaves as a pure separator-aware parser and leaves validation to the consumer.separator – the token boundary. Use any single character; this also drives the metavar rendering (
[a<sep>b<sep>c]).case_sensitive – when
True, a token must match one ofchoicesexactly. By default tokens match case-insensitively, as withEnumChoiceandThemeChoice, and the returned tuple holds the canonical (original-case) values fromchoices.
- class click_extra.table_options.ColumnsOption(param_decls=None, *, columns=None, type=None, metavar='COLUMNS', default=(), expose_value=False, is_eager=True, help='Restrict and reorder table columns, SQL SELECT-style. Comma-separated list of column IDs. Default: all columns in canonical order.', **kwargs)[source]¶
Bases:
ExtraOptionA
--columnsoption that lets users restrict and reorder table columns.Accepts a comma-separated list of column IDs, SQL-
SELECT-style:$ my-cli --columns id,spec,value --params
The selection is stored in
ctx.meta[click_extra.context.COLUMNS]and consumed by table-rendering callbacks (likeclick_extra.show_params.ShowParamsOption) to project rows + headers before rendering.Pass
columns=at construction time with the column registry the option should advertise: the help text then lists the accepted IDs and the default selection, and the callback validates the user input against that registry so unknown IDs fail fast with aclick.UsageError. Withoutcolumns=, the option stays generic: it parses any IDs and leaves validation to the downstream consumer.Empty / unset means render every column in canonical order: the default behavior, indistinguishable from not passing
--columnsat all.- columns: tuple[ColumnSpec, ...]¶
Column registry this option advertises and validates against (may be empty).
- class click_extra.table_options.SortByOption(*header_defs, param_decls=None, columns=None, default=None, expose_value=False, cell_key=None, help='Sort table by this column. Repeat to set priority.', **kwargs)[source]¶
Bases:
ExtraOptionA
--sort-byoption whose choices are derived from column definitions.Stores the selected column IDs in
ctx.meta[click_extra.context.SORT_BY]and publishes the derived row sort key inctx.meta[click_extra.context.TABLE_SORT_KEY], whichctx.print_tablepicks up so that table output is automatically sorted, without changing its(table_data, headers)call contract. The option acceptsmultiple=True, so users can repeat--sort-byto define a multi-column sort priority.Column definitions are
ColumnSpecinstances, passed positionally or via thecolumns=keyword. A column markedsortable=Falsekeeps its place in the layout without being offered as a choice. Passing aColumnSpecregistry viacolumns=lets the same tuple drive bothColumnsOption(--columns) and--sort-by, so the two options stay in sync from a single source of truth.COLUMNS = ( ColumnSpec("package_id", "Package ID"), ColumnSpec("package_name", "Name"), ColumnSpec("manager_id", "Manager"), ) @command @table_format_option @columns_option(columns=COLUMNS) @sort_by_option(columns=COLUMNS) @pass_context def my_cmd(ctx): ctx.print_table(rows, [col.label for col in COLUMNS])
Definitions may instead be bare column ID strings, declaring a field vocabulary untied to any single table layout. This fits a
--sort-bydeclared once on a group whose subcommands render heterogeneous tables: no sort key is published since no layout is known up front. The selection is resolved per table byprint_table(), from the column IDs its headers carry: each table sorts by the selected fields it knows (remaining columns breaking ties left to right) and keeps its original row order when it knows none.@group @sort_by_option("package_id", "package_name", "manager_id") def my_cli(): pass @my_cli.command def installed(): print_table( rows, [ ColumnSpec("package_id", "Package ID"), ColumnSpec("manager_id", "Manager"), ], ) @my_cli.command def managers(): print_table(rows, [ColumnSpec("manager_id", "Manager"), "Path"])
- field_vocabulary¶
Whether definitions are bare column IDs, untied to any table layout.
In this mode
init_sort()only publishes the selection on the context: the sort is resolved per table atprint_table()time.
- init_sort(ctx, param, sort_columns)[source]¶
Publish the row sort key on the context’s shared
meta.Builds the sort key from this option’s column definitions and the selected
sort_columns, then stores it underctx.meta[click_extra.context.TABLE_SORT_KEY], wherectx.print_tablepicks it up. The call contract is the same sorted or not:ctx.print_table(table_data, headers).In field-vocabulary mode no table layout is known at declaration time, so no key is published: only the selection lands on the context (
ctx.metais shared with every subcommand), resolved per table byprint_table()from the column IDs its headers carry.- Return type: