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: ExtraOption

A pre-configured option that is adding a --table-format flag 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 the render_table() and print_table() context methods pick it up as their default format. ctx.meta is 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_data is a 2-dimensional iterable of iterables for rows and cells values,

  • headers is a list of string to be used as column headers,

  • **kwargs are any extra keyword arguments supported by the underlying table formatting function.

init_formatter(ctx, param, table_format)[source]

Save the resolved table_format in the context’s shared meta.

The render_table() and print_table() context methods read it back at call time.

Return type:

None

click_extra.table_options.column_sort_key(header_defs, sort_columns=None, cell_key=None)[source]

Build a row sort key from the sort_columns a table actually carries.

header_defs describes the rendered columns: ColumnSpec instances, with sortable=False for columns that cannot be sorted on. The requested sort_columns the 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 None when the table carries none of the requested columns, signalling that rows should keep their original order. This is what lets one --sort-by selection 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.

Return type:

Callable[[Sequence[str | None]], tuple] | None

class click_extra.table_options.ColumnsType(choices=())[source]

Bases: MultiChoice

MultiChoice over 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 COLUMNS instead of the generic MULTI.

Initialize the type.

Parameters:
  • choices (Sequence[str]) – the accepted values. When non-empty, convert() rejects unknown tokens with fail. 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 of choices exactly. By default tokens match case-insensitively, as with EnumChoice and ThemeChoice, and the returned tuple holds the canonical (original-case) values from choices.

name: str = 'columns'

the descriptive name of this type

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: ExtraOption

A --columns option 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 (like click_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 a click.UsageError. Without columns=, 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 --columns at all.

columns: tuple[ColumnSpec, ...]

Column registry this option advertises and validates against (may be empty).

init_columns(ctx, param, columns)[source]

Store the selected column IDs on the context for later projection.

convert() validates the IDs against the registry before this callback runs, so this only threads the parsed selection onto the context.

Return type:

None

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: ExtraOption

A --sort-by option 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 in ctx.meta[click_extra.context.TABLE_SORT_KEY], which ctx.print_table picks up so that table output is automatically sorted, without changing its (table_data, headers) call contract. The option accepts multiple=True, so users can repeat --sort-by to define a multi-column sort priority.

Column definitions are ColumnSpec instances, passed positionally or via the columns= keyword. A column marked sortable=False keeps its place in the layout without being offered as a choice. Passing a ColumnSpec registry via columns= lets the same tuple drive both ColumnsOption (--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-by declared 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 by print_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 at print_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 under ctx.meta[click_extra.context.TABLE_SORT_KEY], where ctx.print_table picks 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.meta is shared with every subcommand), resolved per table by print_table() from the column IDs its headers carry.

Return type:

None