CustomGroup

class gratools.CustomGroup(*args, **kwargs)[source]

Bases: Group

Custom Group class that applies global context settings, prepends a header to its own help message, and ensures that all subcommands added via its command decorator use CustomCommand by default.

Attributes Summary

SHOW_SUBCOMMAND_ALIASES

allow_extra_args

the default for the Context.allow_extra_args flag.

allow_interspersed_args

the default for the Context.allow_interspersed_args flag.

command_class

If set, this is used by the group's command() decorator as the default Command class.

group_class

If set, this is used by the group's group() decorator as the default Group class.

ignore_unknown_options

the default for the Context.ignore_unknown_options flag.

Methods Summary

__call__(*args, **kwargs)

Alias for main().

add_command(cmd[, name, section, ...])

Add a subcommand to this Group.

add_multiple_commands(commands)

add_section(section)

Add a Section to this group.

collect_usage_pieces(ctx)

Returns all the pieces that go into the usage line and returns it as a list of strings.

command(*args, **kwargs)

Overrides the default command decorator registration.

format_aliases(ctx, formatter)

format_commands(ctx, formatter)

Extra format methods for multi methods that adds all the commands after the options.

format_constraints(ctx, formatter)

format_epilog(ctx, formatter)

Writes the epilog into the formatter if it exists.

format_help(ctx, formatter)

Writes the help into the formatter if it exists.

format_help_text(ctx, formatter)

Writes the help text to the formatter if it exists.

format_options(ctx, formatter)

Writes all the options into the formatter if they exist.

format_params(ctx, formatter)

format_subcommand_aliases(aliases, theme)

format_subcommand_name(ctx, name, cmd)

Used to format the name of the subcommands.

format_usage(ctx, formatter)

Writes the usage line into the formatter.

get_argument_help_record(arg, ctx)

get_arguments_help_section(ctx)

get_command(ctx, cmd_name)

Given a context and a command name, this returns a Command object if it exists or returns None.

get_default_option_group(ctx[, ...])

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

get_help(ctx)

Overrides the default help generation for the group to prepend a custom header.

get_help_option(ctx)

Returns the help option object.

get_help_option_names(ctx)

Returns the names for the help option.

get_normalized_epilog()

get_param_by_name(name)

get_params(ctx)

get_params_by_name(names)

get_short_help_str([limit])

Gets short help for the command or makes it by shortening the long help string.

get_ungrouped_options(ctx)

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".

get_usage(ctx)

Formats the usage line into a string and returns it.

group([name, cls, aliases, section])

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

handle_bad_command_name(bad_name, ...)

This method is called when a command name cannot be resolved.

invoke(ctx)

Given a context, this invokes the attached callback (if it exists) in the right way.

list_commands(ctx)

Returns a list of subcommand names in the order they should appear.

list_sections(ctx[, include_default_section])

Return the list of all sections in the "correct order".

main([args, prog_name, complete_var, ...])

This is the way to invoke a script with all the bells and whistles as a command line application.

make_commands_help_section(ctx, section)

make_context(info_name, args[, parent])

This function when given an info name and arguments will kick off the parsing and create a new Context.

make_option_group_help_section(group, ctx)

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

make_parser(ctx)

Creates the underlying option parser for this command.

must_align_option_groups(ctx[, default])

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

must_align_sections(ctx[, default])

must_show_constraints(ctx)

must_show_subcommand_aliases(ctx)

parse_args(ctx, args)

resolve_command(ctx, args)

resolve_command_name(ctx, name)

Map a string supposed to be a command name or an alias to a normalized command name.

result_callback([replace])

Adds a result callback to the command.

section(title, *commands, **attrs)

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

shell_complete(ctx, incomplete)

Return a list of completions for the incomplete value.

to_info_dict(ctx)

Attributes Documentation

SHOW_SUBCOMMAND_ALIASES: bool = False
allow_extra_args = True

the default for the Context.allow_extra_args flag.

allow_interspersed_args = False

the default for the Context.allow_interspersed_args flag.

command_class: type[Command] | None = None

If set, this is used by the group’s command() decorator as the default Command class. This is useful to make all subcommands use a custom command class.

Added in version 8.0.

group_class: type[Group] | type[type] | None = None

If set, this is used by the group’s group() decorator as the default Group class. This is useful to make all subgroups use a custom group class.

If set to the special value type (literally group_class = type), this group’s class will be used as the default class. This makes a custom group class continue to make custom groups.

Added in version 8.0.

ignore_unknown_options = False

the default for the Context.ignore_unknown_options flag.

Methods Documentation

__call__(*args, **kwargs)

Alias for main().

Parameters:
Return type:

Any

add_command(cmd, name=None, section=None, fallback_to_default_section=True)

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 (Command)

  • name (str | None)

  • section (Section | None) – 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

add_multiple_commands(commands)
Parameters:

commands (Mapping[str, Command] | Sequence[Command])

Return type:

None

add_section(section)

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

See also

section()

Parameters:

section (Section)

Return type:

None

collect_usage_pieces(ctx)

Returns all the pieces that go into the usage line and returns it as a list of strings.

Parameters:

ctx (Context)

Return type:

list[str]

command(*args, **kwargs)[source]

Overrides the default command decorator registration.

This ensures that any command registered using this group’s command method will automatically use CustomCommand as its class, thereby inheriting the custom help formatting and header.

Parameters:
  • *args – Positional arguments for the command decorator.

  • **kwargs – Keyword arguments for the command decorator.

Returns:

Callable – The decorator that registers the command.

format_aliases(ctx, formatter)
Parameters:
  • ctx (Context)

  • formatter (HelpFormatter)

Return type:

None

format_commands(ctx, formatter)

Extra format methods for multi methods that adds all the commands after the options.

Parameters:
  • ctx (Context)

  • formatter (HelpFormatter)

Return type:

None

format_constraints(ctx, formatter)
Parameters:
  • ctx (Context)

  • formatter (HelpFormatter)

Return type:

None

format_epilog(ctx, formatter)

Writes the epilog into the formatter if it exists.

Parameters:
  • ctx (Context)

  • formatter (HelpFormatter)

Return type:

None

format_help(ctx, formatter)

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:
  • ctx (Context)

  • formatter (HelpFormatter)

Return type:

None

format_help_text(ctx, formatter)

Writes the help text to the formatter if it exists.

Parameters:
  • ctx (Context)

  • formatter (HelpFormatter)

Return type:

None

format_options(ctx, formatter)

Writes all the options into the formatter if they exist.

Parameters:
  • ctx (Context)

  • formatter (HelpFormatter)

Return type:

None

format_params(ctx, formatter)
Parameters:
  • ctx (Context)

  • formatter (HelpFormatter)

Return type:

None

static format_subcommand_aliases(aliases, theme)
Parameters:
Return type:

str

format_subcommand_name(ctx, name, cmd)

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:
  • ctx (Context)

  • name (str)

  • cmd (Command)

Return type:

str

format_usage(ctx, formatter)

Writes the usage line into the formatter.

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

Parameters:
  • ctx (Context)

  • formatter (HelpFormatter)

Return type:

None

get_argument_help_record(arg, ctx)
Parameters:
  • arg (Argument)

  • ctx (Context)

Return type:

Tuple[str, str]

get_arguments_help_section(ctx)
Parameters:

ctx (Context)

Return type:

HelpSection | None

get_command(ctx, cmd_name)

Given a context and a command name, this returns a Command object if it exists or returns None.

Parameters:
  • ctx (Context)

  • cmd_name (str)

Return type:

Command | None

get_default_option_group(ctx, is_the_only_visible_option_group=False)

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

Added in version 0.8.0.

Parameters:
  • ctx (Context)

  • is_the_only_visible_option_group (bool)

Return type:

OptionGroup

get_help(ctx)[source]

Overrides the default help generation for the group to prepend a custom header.

Parameters:

ctx (click.Context) – The current Click context.

Returns:

str – The formatted help text for the group, including the prepended header.

Return type:

str

get_help_option(ctx)

Returns the help option object.

Skipped if add_help_option is False.

Changed in version 8.1.8: The help option is now cached to avoid creating it multiple times.

Parameters:

ctx (Context)

Return type:

Option | None

get_help_option_names(ctx)

Returns the names for the help option.

Parameters:

ctx (Context)

Return type:

list[str]

get_normalized_epilog()
Return type:

str

get_param_by_name(name)
Parameters:

name (str)

Return type:

Parameter

get_params(ctx)
Parameters:

ctx (Context)

Return type:

list[Parameter]

get_params_by_name(names)
Parameters:

names (Iterable[str])

Return type:

Sequence[Parameter]

get_short_help_str(limit=45)

Gets short help for the command or makes it by shortening the long help string.

Parameters:

limit (int)

Return type:

str

get_ungrouped_options(ctx)

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 (Context)

Return type:

Sequence[Option]

get_usage(ctx)

Formats the usage line into a string and returns it.

Calls format_usage() internally.

Parameters:

ctx (Context)

Return type:

str

group(name=None, *, cls=None, aliases=None, section=None, **kwargs)

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.

Parameters:
  • name (None)

  • cls (Type[G] | None)

  • aliases (Iterable[str] | None)

  • section (Section | None)

  • kwargs (Any)

Return type:

Callable[[Callable[[…], Any]], Group | G]

handle_bad_command_name(bad_name, valid_names, error)

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 (UsageError) – the original error coming from Click.

Returns:

the original error or a new one.

Return type:

UsageError

invoke(ctx)

Given a context, this invokes the attached callback (if it exists) in the right way.

Parameters:

ctx (Context)

Return type:

Any

list_commands(ctx)

Returns a list of subcommand names in the order they should appear.

Parameters:

ctx (Context)

Return type:

list[str]

list_sections(ctx, include_default_section=True)

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:
  • ctx (Context)

  • include_default_section (bool)

Return type:

List[Section]

main(args=None, prog_name=None, complete_var=None, standalone_mode=True, windows_expand_args=True, **extra)

This is the way to invoke a script with all the bells and whistles as a command line application. This will always terminate the application after a call. If this is not wanted, SystemExit needs to be caught.

This method is also available by directly calling the instance of a Command.

Parameters:
  • args (Sequence[str] | None) – the arguments that should be used for parsing. If not provided, sys.argv[1:] is used.

  • prog_name (str | None) – the program name that should be used. By default the program name is constructed by taking the file name from sys.argv[0].

  • complete_var (str | None) – the environment variable that controls the bash completion support. The default is "_<prog_name>_COMPLETE" with prog_name in uppercase.

  • standalone_mode (bool) – the default behavior is to invoke the script in standalone mode. Click will then handle exceptions and convert them into error messages and the function will never return but shut down the interpreter. If this is set to False they will be propagated to the caller and the return value of this function is the return value of invoke().

  • windows_expand_args (bool) – Expand glob patterns, user dir, and env vars in command line args on Windows.

  • extra (Any) – extra keyword arguments are forwarded to the context constructor. See Context for more information.

Return type:

Any

Changed in version 8.0.1: Added the windows_expand_args parameter to allow disabling command line arg expansion on Windows.

Changed in version 8.0: When taking arguments from sys.argv on Windows, glob patterns, user dir, and env vars are expanded.

Changed in version 3.0: Added the standalone_mode parameter.

make_commands_help_section(ctx, section)
Parameters:
  • ctx (Context)

  • section (Section)

Return type:

HelpSection | None

make_context(info_name, args, parent=None, **extra)

This function when given an info name and arguments will kick off the parsing and create a new Context. It does not invoke the actual command callback though.

To quickly customize the context class used without overriding this method, set the context_class attribute.

Parameters:
  • info_name (str | None) – the info name for this invocation. Generally this is the most descriptive name for the script or command. For the toplevel script it’s usually the name of the script, for commands below it’s the name of the command.

  • args (list[str]) – the arguments to parse as list of strings.

  • parent (Context | None) – the parent context if available.

  • extra (Any) – extra keyword arguments forwarded to the context constructor.

Return type:

Context

Changed in version 8.0: Added the context_class attribute.

make_option_group_help_section(group, ctx)

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

Added in version 0.8.0.

Parameters:
  • group (OptionGroup)

  • ctx (Context)

Return type:

HelpSection

make_parser(ctx)

Creates the underlying option parser for this command.

Parameters:

ctx (Context)

Return type:

_OptionParser

must_align_option_groups(ctx, default=True)

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

Added in version 0.8.0.

Parameters:
  • ctx (Context | None)

  • default (bool)

Return type:

bool

must_align_sections(ctx, default=True)
Parameters:
  • ctx (Context | None)

  • default (bool)

Return type:

bool

must_show_constraints(ctx)
Parameters:

ctx (Context)

Return type:

bool

must_show_subcommand_aliases(ctx)
Parameters:

ctx (Context)

Return type:

bool

parse_args(ctx, args)
Parameters:
Return type:

List[str]

resolve_command(ctx, args)
Parameters:
Return type:

Tuple[str | None, Command | None, List[str]]

resolve_command_name(ctx, name)

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:
  • ctx (Context)

  • name (str)

Return type:

str | None

result_callback(replace=False)

Adds a result callback to the command. By default if a result callback is already registered this will chain them but this can be disabled with the replace parameter. The result callback is invoked with the return value of the subcommand (or the list of return values from all subcommands if chaining is enabled) as well as the parameters as they would be passed to the main callback.

Example:

@click.group()
@click.option('-i', '--input', default=23)
def cli(input):
    return 42

@cli.result_callback()
def process_result(result, input):
    return result + input
Parameters:

replace (bool) – if set to True an already existing result callback will be removed.

Return type:

Callable[[F], F]

Changed in version 8.0: Renamed from resultcallback.

Added in version 3.0.

section(title, *commands, **attrs)

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

Parameters:
  • title (str)

  • commands (Command)

  • attrs (Any)

Return type:

Section

shell_complete(ctx, incomplete)

Return a list of completions for the incomplete value. Looks at the names of options, subcommands, and chained multi-commands.

Parameters:
  • ctx (Context) – Invocation context for this command.

  • incomplete (str) – Value being completed. May be empty.

Return type:

list[CompletionItem]

Added in version 8.0.

to_info_dict(ctx)
Parameters:

ctx (Context)

Return type:

dict[str, Any]