cloup

Top-level package for cloup.

Classes

HelpTheme([invoked_command, command_help, …])

A collection of styles for several elements of the help page.

Style([fg, bg, bold, dim, underline, …])

Wraps click.style() for a better integration with HelpTheme.

Color()

Colors accepted by Style and click.style().

HelpFormatter([indent_increment, width, …])

A custom help formatter.

HelpSection(heading, definitions[, help, …])

A container for a help section data.

Context(*ctx_args[, align_option_groups, …])

A custom context for Cloup.

Argument(*args[, help])

A click.Argument with help text.

Option(*args[, group])

A click.Option with an extra field group of type OptionGroup.

OptionGroup(title[, help, constraint, hidden])

Contains the information of an option group and identifies it.

OptionGroupMixin(*args[, align_option_groups])

Implements support for:

Section(title[, commands, is_sorted])

A group of (sub)commands to show in the same help section of a MultiCommand.

SectionMixin(*args[, commands, sections, …])

Adds to a click.MultiCommand the possibility of organizing its subcommands into multiple help sections.

Command(*args[, aliases, formatter_settings])

A click.Command supporting option groups and constraints.

Group(*args[, show_subcommand_aliases])

A click.Group that allows to organize its subcommands in multiple help sections and whose subcommands are, by default, of type cloup.Command.

ConstraintMixin(*args[, constraints, …])

Provides support for constraints.

Functions

argument(*param_decls[, cls])

option(*param_decls[, cls, group])

Attach an Option to the command.

option_group(title, *args, **kwargs)

Return a decorator that annotates a function with an option group.

command([name, aliases, cls])

Return a decorator that creates a new command using the decorated function as callback.

group([name, cls])

Return a decorator that instantiates a Group (or a subclass of it) using the decorated function as callback.

constrained_params(constr, *param_adders)

Return a decorator that adds the given parameters and applies a constraint to them. Equivalent to::.

constraint(constr, params)

Register a constraint on a list of parameters specified by (destination) name (e.g.

dir_path(*[, path_type, exists, writable, …])

Shortcut for click.Path with file_okay=False, path_type=pathlib.Path.

file_path(*[, path_type, exists, writable, …])

Shortcut for click.Path with dir_okay=False, path_type=pathlib.Path.

path(*[, path_type, exists, file_okay, …])

Shortcut for click.Path with path_type=pathlib.Path.

Contents

class cloup.HelpTheme[source]

A collection of styles for several elements of the help page.

A “style” is just a function or a callable that takes a string and returns a styled version of it. This means you can use your favorite styling/color library (like rich, colorful etc). Nonetheless, given that Click has some basic styling functionality built-in, Cloup provides the Style class, which is a wrapper of the click.style function.

Parameters
  • invoked_command (Callable[[str], str]) – Style of the invoked command name (in Usage).

  • command_help (Callable[[str], str]) – Style of the invoked command description (below Usage).

  • heading (Callable[[str], str]) – Style of help section headings.

  • constraint (Callable[[str], str]) – Style of an option group constraint description.

  • section_help (Callable[[str], str]) – Style of the help text of a section (the optional paragraph below the heading).

  • col1 (Callable[[str], str]) – Style of the first column of a definition list (options and command names).

  • col2 (Callable[[str], str]) – Style of the second column of a definition list (help text).

  • epilog (Callable[[str], str]) – Style of the epilog.

  • alias (Callable[[str], str]) – Style of subcommand aliases in a definition lists.

  • alias_secondary (Optional[Callable[[str], str]]) – Style of separator and eventual parenthesis/brackets in subcommand alias lists. If not provided, the alias style will be used.

Return type

None

invoked_command :IStyle

Style of the invoked command name (in Usage).

command_help :IStyle

Style of the invoked command description (below Usage).

heading :IStyle

Style of help section headings.

constraint :IStyle

Style of an option group constraint description.

section_help :IStyle

Style of the help text of a section (the optional paragraph below the heading).

col1 :IStyle

Style of the first column of a definition list (options and command names).

col2 :IStyle

Style of the second column of a definition list (help text).

alias :IStyle

Style of subcommand aliases in a definition lists.

alias_secondary :Optional[IStyle]

Style of separator and eventual parenthesis/brackets in subcommand alias lists. If not provided, the alias style will be used.

epilog :IStyle

Style of the epilog.

with_(self, invoked_command=None, command_help=None, heading=None, constraint=None, section_help=None, col1=None, col2=None, alias=None, alias_secondary=MISSING, epilog=None)[source]
Parameters
  • invoked_command (Optional[IStyle]) –

  • command_help (Optional[IStyle]) –

  • heading (Optional[IStyle]) –

  • constraint (Optional[IStyle]) –

  • section_help (Optional[IStyle]) –

  • col1 (Optional[IStyle]) –

  • col2 (Optional[IStyle]) –

  • alias (Optional[IStyle]) –

  • alias_secondary (cloup.typing.Possibly[Optional[IStyle]]) –

  • epilog (Optional[IStyle]) –

Return type

HelpTheme

static dark()[source]

A theme assuming a dark terminal background color.

Return type

HelpTheme

static light()[source]

A theme assuming a light terminal background color.

Return type

HelpTheme

class cloup.Style[source]

Wraps click.style() for a better integration with HelpTheme.

Available colors are defined as static constants in Color.

Arguments are set to None by default. Passing False to boolean args or Color.reset as color causes a reset code to be inserted.

With respect to click.style(), this class:

  • has an argument less, reset, which is always True

  • add the text_transform.

Warning

The arguments overline, italic and strikethrough are only supported in Click 8 and will be ignored if you are using Click 7.

Parameters
  • fg (Optional[str]) – foreground color

  • bg (Optional[str]) – background color

  • bold (Optional[bool]) –

  • dim (Optional[bool]) –

  • underline (Optional[bool]) –

  • overline (Optional[bool]) –

  • italic (Optional[bool]) –

  • blink (Optional[bool]) –

  • reverse (Optional[bool]) –

  • strikethrough (Optional[bool]) –

  • text_transform (Optional[Callable[[str], str]]) – a generic string transformation; useful to apply functions like str.upper

Return type

None

New in version 0.8.0.

fg :Optional[str]
bg :Optional[str]
bold :Optional[bool]
dim :Optional[bool]
underline :Optional[bool]
overline :Optional[bool]
italic :Optional[bool]
reverse :Optional[bool]
strikethrough :Optional[bool]
text_transform :Optional[IStyle]
__call__(self, text)[source]
Parameters

text (str) –

Return type

str

class cloup.Color[source]

Bases: cloup._util.FrozenSpace

Colors accepted by Style and click.style().

Return type

None

black = black
red = red
green = green
yellow = yellow
blue = blue
magenta = magenta
cyan = cyan
white = white
reset = reset
bright_black = bright_black
bright_red = bright_red
bright_green = bright_green
bright_yellow = bright_yellow
bright_blue = bright_blue
bright_magenta = bright_magenta
bright_cyan = bright_cyan
bright_white = bright_white
class cloup.HelpFormatter(indent_increment=2, width=None, max_width=None, col1_max_width=30, col2_min_width=35, col_spacing=2, row_sep=None, theme=HelpTheme())[source]

Bases: click.HelpFormatter

A custom help formatter. Features include:

  • more attributes for controlling the output of the formatter

  • a col1_width parameter in write_dl() that allows Cloup to align multiple definition lists without resorting to hacks

  • a “linear layout” for definition lists that kicks in when the available terminal width is not enough for the standard 2-column layout (see argument col2_min_width)

  • the first column width, when not explicitly given in write_dl is computed excluding the rows that exceed col1_max_width (called col_max in write_dl for compatibility with Click).

Changed in version 0.9.0: the row_sep parameter now:

  • is set to None by default and row_sep="" corresponds to an empty line between rows

  • must not ends with \n; the formatter writes a newline just after it (when it’s not None), so a newline at the end is always enforced

  • accepts instances of SepGenerator and RowSepPolicy.

New in version 0.8.0.

Parameters
  • indent_increment (int) – width of each indentation increment.

  • width (Optional[int]) – content line width, excluding the newline character; by default it’s initialized to min(terminal_width - 1, max_width) where max_width is another argument.

  • max_width (Optional[int]) – maximum content line width (equivalent to Context.max_content_width). Used to compute width when it is not provided, ignored otherwise.

  • col1_max_width (int) – the maximum width of the first column of a definition list; as in Click, if the text of a row exceeds this threshold, the 2nd column is printed on a new line.

  • col2_min_width (int) – the minimum width for the second column of a definition list; if the available space is less than this value, the formatter switches from the standard 2-column layout to the “linear layout” (that this decision is taken for each definition list). If you want to always use the linear layout, you can set this argument to a very high number (or math.inf). If you never want it (not recommended), you can set this argument to zero.

  • col_spacing (int) – the number of spaces between the column boundaries of a definition list.

  • row_sep (Union[None, str, SepGenerator, RowSepPolicy]) – an “extra” separator to insert between the rows of a definition list (in addition to the normal newline between definitions). If you want an empty line between rows, pass row_sep="". Read Row separators for more.

  • theme (cloup.styling.HelpTheme) – an HelpTheme instance specifying how to style the various elements of the help page.

static settings(width=MISSING, max_width=MISSING, indent_increment=MISSING, col1_max_width=MISSING, col2_min_width=MISSING, col_spacing=MISSING, row_sep=MISSING, theme=MISSING)[source]

A utility method for creating a formatter_settings dictionary to pass as context settings or command attribute. This method exists for one only reason: it enables auto-complete for formatter options, thus improving the developer experience.

Parameters are described in HelpFormatter.

Parameters
Return type

Dict[str, Any]

property available_width(self)
Return type

int

write(self, *strings)[source]

Writes a unicode string into the internal buffer.

Parameters

strings (str) –

Return type

None

write_usage(self, prog, args='', prefix=None)[source]

Writes a usage line into the buffer.

Parameters
  • prog (str) – the program name.

  • args (str) – whitespace separated list of arguments.

  • prefix (Optional[str]) – The prefix for the first line. Defaults to "Usage: ".

Return type

None

write_aliases(self, aliases)[source]
Parameters

aliases (Sequence[str]) –

Return type

None

write_command_help_text(self, cmd)[source]
Parameters

cmd (click.Command) –

Return type

None

write_heading(self, heading, newline=True)[source]

Writes a heading into the buffer.

Parameters
  • heading (str) –

  • newline (bool) –

Return type

None

write_many_sections(self, sections, aligned=True)[source]
Parameters
Return type

None

write_aligned_sections(self, sections)[source]

Write multiple aligned definition lists.

Parameters

sections (Sequence[HelpSection]) –

Return type

None

write_section(self, s, col1_width=None)[source]
Parameters
Return type

None

write_text(self, text, style=identity)[source]

Writes re-indented text into the buffer. This rewraps and preserves paragraphs.

Parameters
  • text (str) –

  • style (cloup.styling.IStyle) –

Return type

None

compute_col1_width(self, rows, max_width)[source]
Parameters
  • rows (Iterable[Definition]) –

  • max_width (int) –

Return type

int

write_dl(self, rows, col_max=None, col_spacing=None, col1_width=None)[source]

Write a definition list into the buffer. This is how options and commands are usually formatted.

If there’s enough space, definition lists are rendered as a 2-column pseudo-table: if the first column text of a row doesn’t fit in the provided/computed col1_width, the 2nd column is printed on the following line.

If the available space for the 2nd column is below self.col2_min_width, the 2nd “column” is always printed below the 1st, indented with a minimum of 3 spaces (or one indent_increment if that’s greater than 3).

Parameters
  • rows (Sequence[Definition]) – a list of two item tuples for the terms and values.

  • col_max (Optional[int]) – the maximum width for the 1st column of a definition list; this argument is here to not break compatibility with Click; if provided, it overrides the attribute self.col1_max_width.

  • col_spacing (Optional[int]) – number of spaces between the first and second column; this argument is here to not break compatibility with Click; if provided, it overrides self.col_spacing.

  • col1_width (Optional[int]) – the width to use for the first column; if not provided, it’s computed as the length of the longest string under self.col1_max_width; useful when you need to align multiple definition lists.

Return type

None

write_tabular_dl(self, rows, col1_width, col_spacing, col2_width)[source]

Format a definition list as a 2-column “pseudo-table”. If the first column of a row exceeds col1_width, the 2nd column is written on the subsequent line. This is the standard way of formatting definition lists and it’s the default if there’s enough space.

Parameters
  • rows (Sequence[Definition]) –

  • col1_width (int) –

  • col_spacing (int) –

  • col2_width (int) –

Return type

None

write_linear_dl(self, dl)[source]

Format a definition list as a “linear list”. This is the default when the available width for the definitions (2nd column) is below self.col2_min_width.

Parameters

dl (Sequence[Definition]) –

Return type

None

write_epilog(self, epilog)[source]
Parameters

epilog (str) –

Return type

None

__repr__(self)[source]

Return repr(self).

Return type

str

class cloup.HelpSection[source]

A container for a help section data.

Parameters
  • heading (str) –

  • definitions (Sequence[Tuple[str, Union[str, Callable[[int], str]]]]) –

  • help (Optional[str]) –

  • constraint (Optional[str]) –

Return type

None

heading :str

Help section title.

definitions :Sequence[Definition]

Rows with 2 columns each. The 2nd element of each row can also be a function taking an integer (the available width for the 2nd column) and returning a string.

help :Optional[str]

(Optional) long description of the section.

constraint :Optional[str]

(Optional) option group constraint description.

class cloup.Context(*ctx_args, align_option_groups=None, align_sections=None, show_subcommand_aliases=None, show_constraints=None, check_constraints_consistency=None, formatter_settings={}, **ctx_kwargs)[source]

Bases: click.Context

A custom context for Cloup.

Look up click.Context for the list of all arguments.

New in version 0.9.0: added the check_constraints_consistency parameter.

New in version 0.8.0.

Parameters
  • ctx_args (Any) – arguments forwarded to click.Context.

  • align_option_groups (Optional[bool]) – if True, align the definition lists of all option groups of a command. You can override this by setting the corresponding argument of Command (but you probably shouldn’t: be consistent).

  • align_sections (Optional[bool]) – if True, align the definition lists of all subcommands of a group. You can override this by setting the corresponding argument of Group (but you probably shouldn’t: be consistent).

  • show_subcommand_aliases (Optional[bool]) – whether to show the aliases of subcommands in the help of a cloup.Group.

  • show_constraints (Optional[bool]) – whether to include a “Constraint” section in the command help (if at least one constraint is defined).

  • check_constraints_consistency (Optional[bool]) – enable additional checks for constraints which detects mistakes of the developer (see cloup.Constraint.check_consistency()).

  • formatter_settings (Dict[str, Any]) – keyword arguments forwarded to HelpFormatter in make_formatter. This args are merged with those of the (eventual) parent context and then merged again (being overridden) by those of the command. Tip: use the static method HelpFormatter.settings() to create this dictionary, so that you can be guided by your IDE.

  • ctx_kwargs (Any) – keyword arguments forwarded to click.Context.

formatter_class :Type[cloup.formatting.HelpFormatter]
get_formatter_settings(self)[source]
Return type

Dict[str, Any]

make_formatter(self)[source]

Creates the HelpFormatter for the help and usage output.

To quickly customize the formatter class used without overriding this method, set the formatter_class attribute.

Changed in version 8.0: Added the formatter_class attribute.

Return type

cloup.formatting.HelpFormatter

static settings(auto_envvar_prefix=MISSING, default_map=MISSING, terminal_width=MISSING, max_content_width=MISSING, resilient_parsing=MISSING, allow_extra_args=MISSING, allow_interspersed_args=MISSING, ignore_unknown_options=MISSING, help_option_names=MISSING, token_normalize_func=MISSING, color=MISSING, show_default=MISSING, align_option_groups=MISSING, align_sections=MISSING, show_subcommand_aliases=MISSING, show_constraints=MISSING, check_constraints_consistency=MISSING, formatter_settings=MISSING)[source]

Utility method for creating a context_settings dictionary.

Parameters
  • auto_envvar_prefix (cloup.typing.Possibly[str]) – the prefix to use for automatic environment variables. If this is None then reading from environment variables is disabled. This does not affect manually set environment variables which are always read.

  • default_map (cloup.typing.Possibly[Dict[str, Any]]) – a dictionary (like object) with default values for parameters.

  • terminal_width (cloup.typing.Possibly[int]) – the width of the terminal. The default is inherited from parent context. If no context defines the terminal width then auto-detection will be applied.

  • max_content_width (cloup.typing.Possibly[int]) – the maximum width for content rendered by Click (this currently only affects help pages). This defaults to 80 characters if not overridden. In other words: even if the terminal is larger than that, Click will not format things wider than 80 characters by default. In addition to that, formatters might add some safety mapping on the right.

  • resilient_parsing (cloup.typing.Possibly[bool]) – if this flag is enabled then Click will parse without any interactivity or callback invocation. Default values will also be ignored. This is useful for implementing things such as completion support.

  • allow_extra_args (cloup.typing.Possibly[bool]) – if this is set to True then extra arguments at the end will not raise an error and will be kept on the context. The default is to inherit from the command.

  • allow_interspersed_args (cloup.typing.Possibly[bool]) – if this is set to False then options and arguments cannot be mixed. The default is to inherit from the command.

  • ignore_unknown_options (cloup.typing.Possibly[bool]) – instructs click to ignore options it does not know and keeps them for later processing.

  • help_option_names (cloup.typing.Possibly[List[str]]) – optionally a list of strings that define how the default help parameter is named. The default is ['--help'].

  • token_normalize_func (cloup.typing.Possibly[Callable[[str], str]]) – an optional function that is used to normalize tokens (options, choices, etc.). This for instance can be used to implement case-insensitive behavior.

  • color (cloup.typing.Possibly[bool]) – controls if the terminal supports ANSI colors or not. The default is auto-detection. This is only needed if ANSI codes are used in texts that Click prints which is by default not the case. This for instance would affect help output.

  • show_default (cloup.typing.Possibly[bool]) – Show defaults for all options. If not set, defaults to the value from a parent context. Overrides an option’s show_default argument.

  • align_option_groups (cloup.typing.Possibly[bool]) – if True, align the definition lists of all option groups of a command. You can override this by setting the corresponding argument of Command (but you probably shouldn’t: be consistent).

  • align_sections (cloup.typing.Possibly[bool]) – if True, align the definition lists of all subcommands of a group. You can override this by setting the corresponding argument of Group (but you probably shouldn’t: be consistent).

  • show_subcommand_aliases (cloup.typing.Possibly[bool]) – whether to show the aliases of subcommands in the help of a cloup.Group.

  • show_constraints (cloup.typing.Possibly[bool]) – whether to include a “Constraint” section in the command help (if at least one constraint is defined).

  • check_constraints_consistency (cloup.typing.Possibly[bool]) – enable additional checks for constraints which detects mistakes of the developer (see cloup.Constraint.check_consistency()).

  • formatter_settings (cloup.typing.Possibly[Dict[str, Any]]) – keyword arguments forwarded to HelpFormatter in make_formatter. This args are merged with those of the (eventual) parent context and then merged again (being overridden) by those of the command. Tip: use the static method HelpFormatter.settings() to create this dictionary, so that you can be guided by your IDE.

Return type

Dict[str, Any]

class cloup.Argument(*args, help=None, **attrs)[source]

Bases: click.Argument

A click.Argument with help text.

get_help_record(self, ctx)[source]
class cloup.Option(*args, group=None, **attrs)[source]

Bases: click.Option

A click.Option with an extra field group of type OptionGroup.

cloup.argument(*param_decls, cls=None, **attrs)[source]
cloup.option(*param_decls, cls=None, group=None, **attrs)[source]

Attach an Option to the command. Refer to click.Option and click.Parameter for more info about the accepted parameters.

In your IDE, you won’t see arguments relating to shell completion, because they are different in Click 7 and 8 (both supported by Cloup):

  • in Click 7, it’s autocompletion

  • in Click 8, it’s shell_complete.

These arguments have different semantics, refer to Click’s docs.

class cloup.OptionGroup(title, help=None, constraint=None, hidden=False)[source]

Contains the information of an option group and identifies it. Note that, as far as the clients of this library are concerned, an OptionGroups acts as a “marker” for options, not as a container for related options. When you call @optgroup.option(...) you are not adding an option to a container, you are just adding an option marked with this option group.

New in version 0.8.0: The hidden parameter.

Parameters
property options(self)
Return type

Sequence[click.Option]

get_help_records(self, ctx)[source]
Parameters

ctx (click.Context) –

Return type

List[Tuple[str, str]]

option(self, *param_decls, **attrs)[source]

Refer to cloup.option().

Parameters
  • param_decls (str) –

  • attrs (Any) –

Return type

Callable[[cloup.typing.F], cloup.typing.F]

__iter__(self)[source]
Return type

Iterator[click.Option]

__getitem__(self, i)[source]
Parameters

i (int) –

Return type

click.Option

__len__(self)[source]
Return type

int

__repr__(self)[source]

Return repr(self).

Return type

str

__str__(self)[source]

Return str(self).

Return type

str

class cloup.OptionGroupMixin(*args, align_option_groups=None, **kwargs)[source]

Implements support for:

  • option groups

  • the “Positional arguments” help section; this section is shown only if at least one of your arguments has non-empty help.

Important

In order to check the constraints defined on the option groups, a command must inherits from cloup.ConstraintMixin too!

New in version 0.14.0: added the “Positional arguments” help section.

Changed in version 0.8.0: this mixin now relies on cloup.HelpFormatter to align help sections. If a click.HelpFormatter is used with a TypeError is raised.

Changed in version 0.8.0: removed format_option_group. Added get_default_option_group and make_option_group_help_section.

New in version 0.5.0.

Parameters
  • align_option_groups (Optional[bool]) – whether to align the columns of all option groups’ help sections. This is also available as a context setting having a lower priority than this attribute. Given that this setting should be consistent across all you commands, you should probably use the context setting only.

  • args (Any) – positional arguments forwarded to the next class in the MRO

  • kwargs (Any) – keyword arguments forwarded to the next class in the MRO

Return type

None

option_groups

List of all option groups, except the “default option group”.

ungrouped_options

List of options not explicitly assigned to an user-defined option group. These options will be included in the “default option group”. Note: this list does not include options added automatically by Click based on context settings, like the --help option; use the get_ungrouped_options() method if you need the real full list (which needs a Context object).

get_ungrouped_options(self, ctx)[source]

Return options not explicitly assigned to an option group (eventually including the --help option), i.e. options that will be part of the “default option group”.

Parameters

ctx (click.Context) –

Return type

Sequence[click.Option]

get_argument_help_record(self, arg, ctx)[source]
Parameters
Return type

Tuple[str, str]

get_arguments_help_section(self, ctx)[source]
Parameters

ctx (click.Context) –

Return type

Optional[cloup.formatting.HelpSection]

make_option_group_help_section(self, group, ctx)[source]

Return a HelpSection for an OptionGroup, i.e. an object containing the title, the optional description and the options’ definitions for this option group.

New in version 0.8.0.

Parameters
Return type

cloup.formatting.HelpSection

must_align_option_groups(self, ctx, default=True)[source]

Return True if the help sections of all options groups should have their columns aligned.

New in version 0.8.0.

Parameters
Return type

bool

get_default_option_group(self, ctx, is_the_only_visible_option_group=False)[source]

Return an OptionGroup instance for the options not explicitly assigned to an option group, eventually including the --help option.

New in version 0.8.0.

Parameters
Return type

OptionGroup

format_params(self, ctx, formatter)[source]
Parameters
Return type

None

cloup.option_group(title: str, help: str, *options: cloup.typing.Decorator, constraint: Optional[cloup.constraints.Constraint] = None, hidden: bool = False)Callable[[cloup.typing.F], cloup.typing.F][source]
cloup.option_group(title: str, *options: cloup.typing.Decorator, help: Optional[str] = None, constraint: Optional[cloup.constraints.Constraint] = None, hidden: bool = False)Callable[[cloup.typing.F], cloup.typing.F]

Return a decorator that annotates a function with an option group.

The help argument is an optional description and can be provided either as keyword argument or as 2nd positional argument after the name of the group:

# help as keyword argument
@option_group(name, *options, help=None, ...)

# help as 2nd positional argument
@option_group(name, help, *options, ...)

Changed in version 0.9.0: in order to support the decorator cloup.constrained_params(), @option_group now allows each input decorators to add multiple options.

Parameters
  • title (str) – title of the help section describing the option group.

  • help – an optional description shown below the name; can be provided as keyword argument or 2nd positional argument.

  • options – an arbitrary number of decorators like click.option, which attach one or multiple options to the decorated command function.

  • constraint – an optional instance of Constraint (see Constraints for more info); a description of the constraint will be shown between squared brackets aside the option group title (or below it if too long).

  • hidden – if True, the option group and all its options are hidden from the help page (all contained options will have their hidden attribute set to True).

  • args (Any) –

  • kwargs (Any) –

Return type

Callable[[F], F]

class cloup.Section(title, commands=(), is_sorted=False)[source]

A group of (sub)commands to show in the same help section of a MultiCommand. You can use sections with any Command that inherits from SectionMixin.

Changed in version 0.6.0: removed the deprecated old name GroupSection.

Changed in version 0.5.0: introduced the new name Section and deprecated the old GroupSection.

Parameters
  • title (str) –

  • commands (Union[Iterable[click.core.Command], Dict[str, click.core.Command]]) – sequence of commands or dict of commands keyed by name

  • is_sorted (bool) – if True, list_commands() returns the commands in lexicographic order

classmethod sorted(cls, title, commands=())[source]
Parameters
  • title (str) –

  • commands (Subcommands) –

Return type

Section

add_command(self, cmd, name=None)[source]
Parameters
Return type

None

list_commands(self)[source]
Return type

List[Tuple[str, click.Command]]

__len__(self)[source]
Return type

int

__repr__(self)[source]

Return repr(self).

Return type

str

class cloup.SectionMixin(*args, commands=None, sections=(), align_sections=None, **kwargs)[source]

Adds to a click.MultiCommand the possibility of organizing its subcommands into multiple help sections.

Sections can be specified in the following ways:

  1. passing a list of Section objects to the constructor setting the argument sections

  2. using add_section() to add a single section

  3. using add_command() with the argument section set

Commands not assigned to any user-defined section are added to the “default section”, whose title is “Commands” or “Other commands” depending on whether it is the only section or not. The default section is the last shown section in the help and its commands are listed in lexicographic order.

Changed in version 0.8.0: this mixin now relies on cloup.HelpFormatter to align help sections. If a click.HelpFormatter is used with a TypeError is raised.

Changed in version 0.8.0: removed format_section. Added make_commands_help_section.

New in version 0.5.0.

Parameters
  • align_sections (Optional[bool]) – whether to align the columns of all subcommands’ help sections. This is also available as a context setting having a lower priority than this attribute. Given that this setting should be consistent across all you commands, you should probably use the context setting only.

  • args (Any) – positional arguments forwarded to the next class in the MRO

  • kwargs (Any) – keyword arguments forwarded to the next class in the MRO

  • commands (Optional[Dict[str, click.core.Command]]) –

  • sections (Iterable[cloup._sections.Section]) –

add_section(self, section)[source]

Add a Section to this group. You can add the same section object a single time.

Parameters

section (Section) –

Return type

None

section(self, title, *commands, **attrs)[source]

Create a new Section, adds it to this group and returns it.

Parameters
Return type

Section

add_command(self, cmd, name=None, section=None, fallback_to_default_section=True)[source]

Add a subcommand to this Group.

Implementation note: fallback_to_default_section looks not very clean but, even if it’s not immediate to see (it wasn’t for me), I chose it over apparently cleaner options.

Parameters
  • cmd (click.Command) –

  • name (Optional[str]) –

  • section (Optional[Section]) – a Section instance. The command must not be in the section already.

  • fallback_to_default_section (bool) – if section is None and this option is enabled, the command is added to the “default section”. If disabled, the command is not added to any section unless section is provided. This is useful for internal code and subclasses. Don’t disable it unless you know what you are doing.

Return type

None

list_sections(self, ctx, include_default_section=True)[source]

Return the list of all sections in the “correct order”.

If include_default_section=True and the default section is non-empty, it will be included at the end of the list.

Parameters
Return type

List[Section]

format_subcommand_name(self, ctx, name, cmd)[source]

Used to format the name of the subcommands. This method is useful when you combine this extension with other click extensions that override format_commands(). Most of these, like click-default-group, just add something to the name of the subcommands, which is exactly what this method allows you to do without overriding bigger methods.

Parameters
Return type

str

make_commands_help_section(self, ctx, section)[source]
Parameters
Return type

Optional[cloup.formatting.HelpSection]

must_align_sections(self, ctx, default=True)[source]
Parameters
Return type

bool

format_commands(self, ctx, formatter)[source]
Parameters
Return type

None

class cloup.Command(*args, aliases=None, formatter_settings=None, **kwargs)[source]

Bases: cloup.constraints.ConstraintMixin, cloup._option_groups.OptionGroupMixin, click.Command

A click.Command supporting option groups and constraints.

Refer to superclasses for the documentation of all accepted parameters:

Besides other things, this class also:

  • adds a formatter_settings instance attribute.

Refer to click.Command for the documentation of all parameters.

New in version 0.8.0.

Parameters
  • constraints – sequence of constraints bound to specific groups of parameters. Note that constraints applied to option groups are collected from the option groups themselves, so they don’t need to be included in this argument.

  • show_constraints – whether to include a “Constraint” section in the command help. This is also available as a context setting having a lower priority than this attribute.

  • args (Any) – positional arguments forwarded to the next class in the MRO

  • kwargs (Any) – keyword arguments forwarded to the next class in the MRO

  • aliases (Optional[Iterable[str]]) –

  • formatter_settings (Optional[Dict[str, Any]]) –

context_class :Type[cloup._context.Context]
get_normalized_epilog(self)[source]
Return type

str

format_epilog(self, ctx, formatter)[source]

Writes the epilog into the formatter if it exists.

Parameters
Return type

None

format_help_text(self, ctx, formatter)[source]

Writes the help text to the formatter if it exists.

Parameters
Return type

None

format_aliases(self, ctx, formatter)[source]
Parameters
Return type

None

format_help(self, ctx, formatter)[source]

Writes the help into the formatter if it exists.

This is a low-level method called by get_help().

This calls the following methods:

Parameters
Return type

None

class cloup.Group(*args, show_subcommand_aliases=None, **kwargs)[source]

Bases: cloup._sections.SectionMixin, Command, click.Group

A click.Group that allows to organize its subcommands in multiple help sections and whose subcommands are, by default, of type cloup.Command.

Refer to superclasses for the documentation of all accepted parameters:

Apart from superclasses arguments, the following is the only additional parameter:

show_subcommand_aliases: Optional[bool] = None

whether to show subcommand aliases; aliases are shown by default and can be disabled using this argument or the homonym context setting.

Changed in version 0.14.0: this class now supports option groups and constraints.

New in version 0.10.0: the “command aliases” feature, including the show_subcommand_aliases parameter/attribute.

Changed in version 0.8.0: this class now inherits from cloup.BaseCommand.

Parameters
  • align_sections – whether to align the columns of all subcommands’ help sections. This is also available as a context setting having a lower priority than this attribute. Given that this setting should be consistent across all you commands, you should probably use the context setting only.

  • args (Any) – positional arguments forwarded to the next class in the MRO

  • kwargs (Any) – keyword arguments forwarded to the next class in the MRO

  • show_subcommand_aliases (Optional[bool]) –

SHOW_SUBCOMMAND_ALIASES :bool = False
show_subcommand_aliases

Whether to show subcommand aliases.

alias2name :Dict[str, str]

Dictionary mapping each alias to a command name.

add_command(self, cmd, name=None, section=None, fallback_to_default_section=True)[source]

Add a subcommand to this Group.

Implementation note: fallback_to_default_section looks not very clean but, even if it’s not immediate to see (it wasn’t for me), I chose it over apparently cleaner options.

Parameters
  • cmd (click.Command) –

  • name (Optional[str]) –

  • section (Optional[cloup._sections.Section]) – a Section instance. The command must not be in the section already.

  • fallback_to_default_section (bool) – if section is None and this option is enabled, the command is added to the “default section”. If disabled, the command is not added to any section unless section is provided. This is useful for internal code and subclasses. Don’t disable it unless you know what you are doing.

Return type

None

resolve_command_name(self, ctx, name)[source]

Map a string supposed to be a command name or an alias to a normalized command name. If no match is found, it returns None.

Parameters
Return type

Optional[str]

resolve_command(self, ctx, args)[source]
Parameters
Return type

Tuple[Optional[str], Optional[click.Command], List[str]]

handle_bad_command_name(self, bad_name, valid_names, error)[source]

This method is called when a command name cannot be resolved. Useful to implement the “Did you mean <x>?” feature.

Parameters
  • bad_name (str) – the command name that could not be resolved.

  • valid_names (List[str]) – the list of valid command names, including aliases.

  • error (click.UsageError) – the original error coming from Click.

Returns

the original error or a new one.

Return type

click.UsageError

must_show_subcommand_aliases(self, ctx)[source]
Parameters

ctx (click.Context) –

Return type

bool

format_subcommand_name(self, ctx, name, cmd)[source]

Used to format the name of the subcommands. This method is useful when you combine this extension with other click extensions that override format_commands(). Most of these, like click-default-group, just add something to the name of the subcommands, which is exactly what this method allows you to do without overriding bigger methods.

Parameters
Return type

str

static format_subcommand_aliases(aliases, theme)[source]
Parameters
Return type

str

command(self, name: Optional[str] = None, *, aliases: Optional[Iterable[str]] = None, cls: None = None, section: Optional[cloup._sections.Section] = None, context_settings: Optional[Dict[str, Any]] = None, formatter_settings: Optional[Dict[str, Any]] = None, help: Optional[str] = None, epilog: Optional[str] = None, short_help: Optional[str] = None, options_metavar: Optional[str] = '[OPTIONS]', add_help_option: bool = True, no_args_is_help: bool = False, hidden: bool = False, deprecated: bool = False, align_option_groups: Optional[bool] = None, show_constraints: Optional[bool] = None, params: Optional[List[click.Parameter]] = None)Callable[[cloup.typing.AnyCallable], click.Command][source]
command(self, name: Optional[str] = None, *, aliases: Optional[Iterable[str]] = None, cls: Type[C], section: Optional[cloup._sections.Section] = None, context_settings: Optional[Dict[str, Any]] = None, help: Optional[str] = None, epilog: Optional[str] = None, short_help: Optional[str] = None, options_metavar: Optional[str] = '[OPTIONS]', add_help_option: bool = True, no_args_is_help: bool = False, hidden: bool = False, deprecated: bool = False, params: Optional[List[click.Parameter]] = None, **kwargs: Any)Callable[[cloup.typing.AnyCallable], C]

Return a decorator that creates a new subcommand of this Group using the decorated function as callback.

It takes the same arguments of command() plus:

section: Optional[Section]

if provided, put the subcommand in this section.

Changed in version 0.10.0: all arguments but name are now keyword-only.

group(self, name: Optional[str] = None, *, aliases: Optional[Iterable[str]] = None, cls: None = None, section: Optional[cloup._sections.Section] = None, sections: Iterable[cloup._sections.Section] = (), align_sections: Optional[bool] = None, invoke_without_command: bool = False, no_args_is_help: bool = False, context_settings: Optional[Dict[str, Any]] = None, formatter_settings: Dict[str, Any] = {}, help: Optional[str] = None, epilog: Optional[str] = None, short_help: Optional[str] = None, options_metavar: Optional[str] = '[OPTIONS]', subcommand_metavar: Optional[str] = None, add_help_option: bool = True, chain: bool = False, hidden: bool = False, deprecated: bool = False)Callable[[cloup.typing.AnyCallable], click.Group][source]
group(self, name: Optional[str] = None, *, aliases: Optional[Iterable[str]] = None, cls: Optional[Type[G]] = None, section: Optional[cloup._sections.Section] = None, invoke_without_command: bool = False, no_args_is_help: bool = False, context_settings: Optional[Dict[str, Any]] = None, help: Optional[str] = None, epilog: Optional[str] = None, short_help: Optional[str] = None, options_metavar: Optional[str] = '[OPTIONS]', subcommand_metavar: Optional[str] = None, add_help_option: bool = True, chain: bool = False, hidden: bool = False, deprecated: bool = False, params: Optional[List[click.Parameter]] = None, **kwargs: Any)Callable[[cloup.typing.AnyCallable], G]

Return a decorator that creates a new subcommand of this Group using the decorated function as callback.

It takes the same argument of group() plus:

section: Optional[Section]

if provided, put the subcommand in this section.

Changed in version 0.10.0: all arguments but name are now keyword-only.

cloup.command(name: Optional[str] = None, *, aliases: Optional[Iterable[str]] = None, cls: None = None, context_settings: Optional[Dict[str, Any]] = None, formatter_settings: Optional[Dict[str, Any]] = None, help: Optional[str] = None, short_help: Optional[str] = None, epilog: Optional[str] = None, options_metavar: Optional[str] = '[OPTIONS]', add_help_option: bool = True, no_args_is_help: bool = False, hidden: bool = False, deprecated: bool = False, align_option_groups: Optional[bool] = None, show_constraints: Optional[bool] = None, params: Optional[List[click.Parameter]] = None)Callable[[cloup.typing.AnyCallable], Command][source]
cloup.command(name: Optional[str] = None, *, aliases: Optional[Iterable[str]] = None, cls: Type[C], context_settings: Optional[Dict[str, Any]] = None, help: Optional[str] = None, short_help: Optional[str] = None, epilog: Optional[str] = None, options_metavar: Optional[str] = '[OPTIONS]', add_help_option: bool = True, no_args_is_help: bool = False, hidden: bool = False, deprecated: bool = False, params: Optional[List[click.Parameter]] = None, **kwargs: Any)Callable[[cloup.typing.AnyCallable], C]

Return a decorator that creates a new command using the decorated function as callback.

The only differences with respect to click.command are:

  • the default command class is cloup.Command

  • supports constraints, provided that cls inherits from ConstraintMixin like cloup.Command (the default)

  • this function has detailed type hints and uses generics for the cls argument and return type.

Note that the following arguments are about Cloup-specific features and are not supported by all click.Command, so if you provide a custom cls make sure you don’t set these:

  • formatter_settings

  • align_option_groups (cls needs to inherit from OptionGroupMixin)

  • show_constraints (cls needs to inherit ConstraintMixin).

Changed in version 0.10.0: this function is now generic: the return type depends on what you provide as cls argument.

Changed in version 0.9.0: all arguments but name are now keyword-only arguments.

Parameters
  • name (Optional[str]) – the name of the command to use unless a group overrides it.

  • aliases (Optional[Iterable[str]]) – alternative names for this command. If cls is not a Cloup command class, aliases will be stored in the instantiated command by monkey-patching and aliases won’t be documented in the help page of the command.

  • cls (Optional[Type[C]]) – the command class to instantiate.

  • context_settings – an optional dictionary with defaults that are passed to the context object.

  • formatter_settings – arguments for the formatter; you can use HelpFormatter.settings() to build this dictionary.

  • help – the help string to use for this command.

  • epilog – like the help string but it’s printed at the end of the help page after everything else.

  • short_help – the short help to use for this command. This is shown on the command listing of the parent command.

  • options_metavar – metavar for options shown in the command’s usage string.

  • add_help_option – by default each command registers a --help option. This can be disabled by this parameter.

  • no_args_is_help – this controls what happens if no arguments are provided. This option is disabled by default. If enabled this will add --help as argument if no arguments are passed

  • hidden – hide this command from help outputs.

  • deprecated – issues a message indicating that the command is deprecated.

  • align_option_groups – whether to align the columns of all option groups’ help sections. This is also available as a context setting having a lower priority than this attribute. Given that this setting should be consistent across all you commands, you should probably use the context setting only.

  • show_constraints – whether to include a “Constraint” section in the command help. This is also available as a context setting having a lower priority than this attribute.

  • params(click >= 8.1.0) a list of parameters (Argument and Option instances). Params added with @option and @argument are appended to the end of the list if given.

  • kwargs (Any) – any other argument accepted by the instantiated command class (cls).

Return type

Callable[[Callable[[..], Any]], Union[cloup._commands.Command, C]]

cloup.group(name: Optional[str] = None, *, cls: None = None, aliases: Optional[Iterable[str]] = None, sections: Iterable[cloup._sections.Section] = (), align_sections: Optional[bool] = None, invoke_without_command: bool = False, no_args_is_help: bool = False, context_settings: Optional[Dict[str, Any]] = None, formatter_settings: Dict[str, Any] = {}, help: Optional[str] = None, short_help: Optional[str] = None, epilog: Optional[str] = None, options_metavar: Optional[str] = '[OPTIONS]', subcommand_metavar: Optional[str] = None, add_help_option: bool = True, chain: bool = False, hidden: bool = False, deprecated: bool = False, params: Optional[List[click.Parameter]] = None)Callable[[cloup.typing.AnyCallable], Group][source]
cloup.group(name: Optional[str] = None, *, cls: Type[G], aliases: Optional[Iterable[str]] = None, invoke_without_command: bool = False, no_args_is_help: bool = False, context_settings: Optional[Dict[str, Any]] = None, help: Optional[str] = None, short_help: Optional[str] = None, epilog: Optional[str] = None, options_metavar: Optional[str] = '[OPTIONS]', subcommand_metavar: Optional[str] = None, add_help_option: bool = True, chain: bool = False, hidden: bool = False, deprecated: bool = False, params: Optional[List[click.Parameter]] = None, **kwargs: Any)Callable[[cloup.typing.AnyCallable], G]

Return a decorator that instantiates a Group (or a subclass of it) using the decorated function as callback.

Changed in version 0.10.0: the cls argument can now be any click.Group (previously had to be a cloup.Group) and the type of the instantiated command matches it (previously, the type was cloup.Group even if cls was a subclass of it).

Changed in version 0.9.0: all arguments but name are now keyword-only arguments.

Parameters
  • name (Optional[str]) – the name of the command to use unless a group overrides it.

  • cls (Optional[Type[G]]) – the click.Group (sub)class to instantiate. This is cloup.Group by default. Note that some of the arguments are only supported by cloup.Group.

  • sections – a list of Section objects containing the subcommands of this Group. This argument is only supported by commands inheriting from cloup.SectionMixin.

  • align_sections – whether to align the columns of all subcommands’ help sections. This is also available as a context setting having a lower priority than this attribute. Given that this setting should be consistent across all you commands, you should probably use the context setting only.

  • context_settings – an optional dictionary with defaults that are passed to the context object.

  • formatter_settings – arguments for the formatter; you can use HelpFormatter.settings() to build this dictionary.

  • help – the help string to use for this command.

  • short_help – the short help to use for this command. This is shown on the command listing of the parent command.

  • epilog – like the help string but it’s printed at the end of the help page after everything else.

  • options_metavar – metavar for options shown in the command’s usage string.

  • add_help_option – by default each command registers a --help option. This can be disabled by this parameter.

  • hidden – hide this command from help outputs.

  • deprecated – issues a message indicating that the command is deprecated.

  • invoke_without_command – this controls how the multi command itself is invoked. By default it’s only invoked if a subcommand is provided.

  • no_args_is_help – this controls what happens if no arguments are provided. This option is enabled by default if invoke_without_command is disabled or disabled if it’s enabled. If enabled this will add --help as argument if no arguments are passed.

  • subcommand_metavar – string used in the command’s usage string to indicate the subcommand place.

  • chain – if this is set to True, chaining of multiple subcommands is enabled. This restricts the form of commands in that they cannot have optional arguments but it allows multiple commands to be chained together.

  • params(click >= 8.1.0) a list of parameters (Argument and Option instances). Params added with @option and @argument are appended to the end of the list if given.

  • kwargs (Any) – any other argument accepted by the instantiated command class.

Return type

Callable[[Callable[[..], Any]], click.core.Group]

class cloup.ConstraintMixin(*args, constraints=(), show_constraints=None, **kwargs)[source]

Provides support for constraints.

Parameters
  • constraints (Sequence[Union[cloup.constraints._support.BoundConstraintSpec, cloup.constraints._support.BoundConstraint]]) – sequence of constraints bound to specific groups of parameters. Note that constraints applied to option groups are collected from the option groups themselves, so they don’t need to be included in this argument.

  • show_constraints (Optional[bool]) – whether to include a “Constraint” section in the command help. This is also available as a context setting having a lower priority than this attribute.

  • args (Any) – positional arguments forwarded to the next class in the MRO

  • kwargs (Any) – keyword arguments forwarded to the next class in the MRO

optgroup_constraints

Constraints applied to OptionGroup instances.

param_constraints :Tuple[BoundConstraint, Ellipsis]

Constraints registered using @constraint (or equivalent method).

all_constraints

All constraints applied to parameter/option groups of this command.

parse_args(self, ctx, args)[source]
Parameters
Return type

List[str]

get_param_by_name(self, name)[source]
Parameters

name (str) –

Return type

click.Parameter

get_params_by_name(self, names)[source]
Parameters

names (Iterable[str]) –

Return type

Sequence[click.Parameter]

format_constraints(self, ctx, formatter)[source]
Parameters
Return type

None

must_show_constraints(self, ctx)[source]
Parameters

ctx (click.Context) –

Return type

bool

cloup.constrained_params(constr, *param_adders)[source]

Return a decorator that adds the given parameters and applies a constraint to them. Equivalent to:

@param_adders[0]
...
@param_adders[-1]
@constraint(constr, <param names>)

This decorator saves you to manually (re)type the parameter names. It can also be used inside @option_group.

Instead of using this decorator, you can also call the constraint itself:

@constr(*param_adders)

but remember that:

  • Python 3.9 is the first that allows arbitrary expressions on the right of @;

  • using a long conditional/composite constraint as decorator may be less readable.

In these cases, you may consider using @constrained_params.

New in version 0.9.0.

Parameters
  • constr (cloup.constraints._core.Constraint) – an instance of Constraint

  • param_adders (Callable[[Callable[[..], Any]], Callable[[..], Any]]) – function decorators, each attaching a single parameter to the decorated function.

Return type

Callable[[F], F]

cloup.constraint(constr, params)[source]

Register a constraint on a list of parameters specified by (destination) name (e.g. the default name of --input-file is input_file).

Parameters
Return type

Callable[[F], F]

cloup.dir_path(path_type=pathlib.Path, exists=False, writable=False, readable=True, resolve_path=False, allow_dash=False)[source]

Shortcut for click.Path with file_okay=False, path_type=pathlib.Path.

Parameters
  • path_type (type) –

  • exists (bool) –

  • writable (bool) –

  • readable (bool) –

  • resolve_path (bool) –

  • allow_dash (bool) –

Return type

click.types.Path

cloup.file_path(path_type=pathlib.Path, exists=False, writable=False, readable=True, resolve_path=False, allow_dash=False)[source]

Shortcut for click.Path with dir_okay=False, path_type=pathlib.Path.

Parameters
  • path_type (type) –

  • exists (bool) –

  • writable (bool) –

  • readable (bool) –

  • resolve_path (bool) –

  • allow_dash (bool) –

Return type

click.types.Path

cloup.path(path_type=pathlib.Path, exists=False, file_okay=True, dir_okay=True, writable=False, readable=True, resolve_path=False, allow_dash=False)[source]

Shortcut for click.Path with path_type=pathlib.Path.

Parameters
  • path_type (type) –

  • exists (bool) –

  • file_okay (bool) –

  • dir_okay (bool) –

  • writable (bool) –

  • readable (bool) –

  • resolve_path (bool) –

  • allow_dash (bool) –

Return type

click.types.Path