API reference

Reference for the API.


Functions

Available public functions on the module:


Function run()

clig.run(
func: Callable[[...], ReturnType] | None = None,
args: Sequence[str] | None = None,
**kwargs: Unpack[RunArguments],
) ReturnType | None

Parse arguments and invoke the CLI command.

When called with a function, wraps it in a Command (forwarding any extra kwargs) and immediately runs it. When called without a function, runs the command previously registered with @clig.command. Raises an error if neither a function is provided nor a main command has been registered.

Parameters

  • func (Callable[..., ReturnType] | None, optional): Defaults to None.

    The function to expose as a CLI command. When None, the global main command registered via @clig.command is used instead.

  • args (Sequence[str] | None, optional): Defaults to None.

    The argument list to parse. When None, defaults to sys.argv[1:].

  • **kwargs (Unpack[RunArguments], variadic):

    Additional keyword arguments forwarded to Command when func is provided. Has no effect when func is None. See Command and RunArguments for the full list of accepted options.

Returns

ReturnType:

The return value of the wrapped function after parsing and invoking it.


Function data()

clig.data(
*flags: str,
make_flag: bool | None = None,
group: ArgumentGroup | MutuallyExclusiveGroup | None = None,
helpmodifier: Callable[[str], str] | None = None,
**kwargs: Unpack[KeywordArguments],
) ArgumentMetaData

Build per-argument metadata to be used inside an Arg (i.e. Annotated) type hint.

Attach this to a parameter annotation to override clig’s defaults for that specific argument - custom flags, grouping, a local help modifier, or any raw add_argument() keyword. The return value is an ArgumentMetaData object consumed by clig when it builds the parser; it is not meant to be used directly.

Parameters

  • *flags (str, variadic):

    Explicit flag strings for this argument (e.g. "-v", "--verbose"). When provided, these replace any flags clig would have generated automatically. Passing no flags leaves flag generation to the make_flag setting and the command-level make_flags option.

  • make_flag (bool | None, optional): Defaults to None.

    Whether to promote this specific argument to an optional flag. Overrides the command-level make_flags setting for this argument only. None defers to the command-level default.

  • group (ArgumentGroup | MutuallyExclusiveGroup | None, optional): Defaults to None.

    The argument group or mutually exclusive group this argument belongs to. When set, the argument is registered under that group in the parser instead of the top-level parser. None places the argument at the top level.

  • helpmodifier (Callable[[str], str] | None | None, optional): Defaults to None.

    A callable applied to this argument’s help string only, taking precedence over the command-level opthelpmodifier, poshelpmodifier, and helpmodifier settings. None falls back to the command-level modifiers.

  • **kwargs (KeywordArguments):

    Any additional keyword arguments accepted by argparse’s add_argument() method (e.g. action, nargs, const, choices, required, help, metavar, default, type). These are forwarded directly to add_argument().

Returns

ArgumentMetaData:

The metadata passed to an Arg (i.e. Annotated) type hint.


Function command()

clig.command(
func: Callable[[...], Any] | None = None,
**kwargs: Unpack[CompleteCommandArguments],
) Callable[[...], Any]

Register a function as the main CLI command.

Decorator that wraps a function in a Command and stores it as the global main command. Can be used with or without parentheses. Raises an error if a main command has already been registered: @clig.command may only be applied once per program.

Parameters

  • func (Function = Callable[..., Any] | None, optional): Defaults to None.

    The function to register as the main command. When None, the decorator is called with parentheses and func is supplied by the outer decorator machinery.

  • **kwargs (Unpack[CompleteCommandArguments], variadic):

    Keyword arguments forwarded to Command (e.g. prog, description, epilog, make_flags). See Command and CompleteCommandArguments for the full list of accepted options.

Raises

RuntimeError:

If a main command has already been registered via a previous call to clig.command().

Returns

Function = Callable[..., Any]:

The original unwrapped function, so the decorated callable behaves identically to the original outside of CLI invocation.


Function subcommand()

clig.subcommand(
func: Callable[[...], Any] | None = None,
parent: Command | Callable | str | None = None,
**kwargs: Unpack[CompleteCommandArguments],
) Callable[[...], Any]

Register a function as a subcommand of an existing command.

Decorator that attaches a function to a parent Command as a named subcommand. Can be used with or without parentheses. The parent may be specified as a Command instance, the original decorated function, or a string name; when omitted it defaults to the global main command. Raises an error if the main command has not yet been registered.

Parameters

  • func (Function = Callable[..., Any] | None, optional): Defaults to None.

    The function to register as a subcommand. When None, the decorator is called with parentheses and func is supplied by the outer decorator machinery.

  • parent (Command | Callable | str | None, optional): Defaults to None.

    The command under which this subcommand will be nested. Accepts a Command instance, the function that was decorated with @clig.command or @clig.subcommand, or a plain string matching the subcommand name. When None, defaults to the global main command registered via clig.command().

  • **kwargs (Unpack[CompleteCommandArguments], variadic):

    Keyword arguments forwarded to Command.add_subcommand (e.g. prog, description, epilog, make_flags). See Command and CompleteCommandArguments for the full list of accepted options.

Raises

RuntimeError:

If the main command has not been registered yet (i.e. clig.command() has not been called before this decorator is applied).

Returns

Function = Callable[..., Any]:

The original unwrapped function, so the decorated callable behaves identically to the original outside of CLI invocation.


Function wrapperformatter()

clig.wrapperformatter(
text: str,
width: int | None = None,
space: int = 24,
dedent: bool = False,
) str

Formatter prepared to wrap text.

Parameters

  • text (str):

    The text to format.

  • width (int | None, optional): Defaults to None.

    The width to wrap the text.

  • space (int, optional): Defaults to 24.

    The space used to indent all text.

  • dedent (bool, optional): Defaults to False.

    Whether to dedent lines first.

Returns

str:

The text formatted.


Arguments for functions

Descriptions for some arguments available for functions, forwaded to objects factories.


RunArguments()

class clig.RunArguments

Arguments passed to Command. Include the arguments of argparse.ArgumentParser, described in

https://docs.python.org/3/library/argparse.html#argumentparser-objects

prog: str | None

The name of the program. The default is generated from the function name. https://docs.python.org/3/library/argparse.html#prog

usage: str | None

The string describing the program usage. The default is generated from arguments added to parser. https://docs.python.org/3/library/argparse.html#usage

description: str | None

Text to display before the argument help. By default, collected from the docstring when possible. https://docs.python.org/3/library/argparse.html#description

epilog: str | None

Text to display after the argument help. By default, collected from the docstring when possible. https://docs.python.org/3/library/argparse.html#epilog

parents: Sequence[ArgumentParser]

A list of ArgumentParser objects whose arguments should also be included. https://docs.python.org/3/library/argparse.html#parents

formatter_class: type[HelpFormatter]

A class for customizing the help output. Defaults to argparse.RawTextHelpFormatter. https://docs.python.org/3/library/argparse.html#formatter-class

prefix_chars: str

The set of characters that prefix optional arguments. Defaults to "-". https://docs.python.org/3/library/argparse.html#prefix-chars

fromfile_prefix_chars: str | None

The set of characters that prefix files from which additional arguments should be read. Defaults to None. https://docs.python.org/3/library/argparse.html#fromfile-prefix-chars

argument_default: Any

The global default value for arguments. Defaults to None. https://docs.python.org/3/library/argparse.html#argument-default

conflict_handler: str

The strategy for resolving conflicting optionals (usually unnecessary). https://docs.python.org/3/library/argparse.html#conflict-handler

add_help: bool

Add a -h/--help option to the parser. Defaults to True. https://docs.python.org/3/library/argparse.html#add-help

allow_abbrev: bool

Allows long options to be abbreviated if the abbreviation is unambiguous. Defaults to True. https://docs.python.org/3/library/argparse.html#allow-abbrev

exit_on_error: bool

Determines whether or not ArgumentParser exits with error info when an error occurs. Defaults to True. https://docs.python.org/3/library/argparse.html#exit-on-error

docstring_template: str | DocStr | None

The template used to parse parameter descriptions from the function’s docstring. When None, clig auto-detects the format by trying all known templates in order (NumPy, Sphinx, Google, clig-style). Set this explicitly to skip auto-detection and enforce a specific format. Use a DocStr enum member or any of the NUMPY_DOCSTRING, SPHINX_DOCSTRING, GOOGLE_DOCSTRING, CLIG_DOCSTRING module-level constants (and their variants).

default_bool: bool

The default value assumed for bool-annotated parameters when deciding the argparse action. When False (the default), a bool parameter with no default generates a store_true action (flag absent → False, flag present → True). When True, the action becomes store_false (flag absent → True, flag present → False). This setting is overridden per-argument when the parameter already has an explicit default value.

make_flags: bool | None

Whether to turn all positional-like parameters into optional flags (i.e. add a --name prefix). When None (the default), clig decides per-argument: parameters that have a default value are automatically promoted to flags; those without remain positional. Set to True to force every argument to be a flag, or False to keep every argument positional regardless of defaults. Per-argument make_flag metadata (using clig.data()) takes precedence over this setting.

make_shorts: bool | None

Whether to automatically generate a short flag (e.g. -n) alongside every long flag (e.g. --name). When None (the default) or False, only the long flag is used. When True, clig derives the shortest non-conflicting single-character option from the argument name and prepends it to the flag list. Short flags are also added to the help (-h) and version (-v) options when this is enabled.

metavarmodifier: str | Sequence[str] | Callable[[str], str] | None

A modifier applied to the displayed metavar of all arguments (both positional and optional) in the help output. A plain str replaces the metavar with that string; a Sequence[str] is used as a fixed tuple of metavar tokens (for multi-value arguments); a callable receives the argument name and must return the desired metavar string. None leaves the metavar at its argparse default. Acts as a fallback for both posmetavarmodifier and optmetavarmodifier when those are None.

posmetavarmodifier: str | Sequence[str] | Callable[[str], str] | None

A modifier applied to the metavar of positional arguments only. Follows the same rules as metavarmodifier (str, sequence, or callable). When set, takes precedence over metavarmodifier for positional arguments; when None, falls back to metavarmodifier.

optmetavarmodifier: str | Sequence[str] | Callable[[str], str] | None

A modifier applied to the metavar of optional (flagged) arguments only. Follows the same rules as metavarmodifier (str, sequence, or callable). When set, takes precedence over metavarmodifier for optional arguments; when None, falls back to metavarmodifier.

descriptionmodifier: Callable[[str], str] | None

A callable applied to the description string. Receives the current description string (may be an empty string if no description was found) and must return the final string to display. Useful for appending text, wrapping text, or adding ANSI colours uniformly. None leaves the description at its default.

epilogmodifier: Callable[[str], str] | None

A callable applied to the epilog string. Receives the current epilog string (may be an empty string if no epilog was found) and must return the final string to display. Useful for appending text, wrapping text, or adding ANSI colours uniformly. None leaves the epilog at its default.

usagemodifier: Callable[[str], str] | None

A callable applied to the usage string. Receives the current usage string and must return the final string to display. Useful for appending text, wrapping text, or adding ANSI colours uniformly. None leaves the usage at its default.

helpmodifier: Callable[[str], str] | None

A callable applied to the help string of all arguments before it is passed to argparse. Receives the current help string (may be an empty string if no help was found) and must return the final string to display. Useful for appending default values, wrapping text, or adding ANSI colours uniformly. Acts as a fallback for both poshelpmodifier and opthelpmodifier when those are None.

poshelpmodifier: Callable[[str], str] | None

A callable applied to the help string of positional arguments only. Follows the same contract as helpmodifier. When set, takes precedence over helpmodifier for positional arguments; when None, falls back to helpmodifier.

opthelpmodifier: Callable[[str], str] | None

A callable applied to the help string of optional (flagged) arguments only. Follows the same contract as helpmodifier. When set, takes precedence over helpmodifier for optional arguments; when None, falls back to helpmodifier.

help_flags: Sequence[str]

The flag strings that trigger the help action. Defaults to ("-h", "--help"). When this is non-empty or help_msg is set, the built-in argparse help is disabled (add_help=False) and a custom help argument is registered instead using these flags and help_msg. Pass an empty sequence together with help_msg to keep the default -h/--help flags while customizing only the message.

help_msg: str | None

The help text shown for the help option itself (the line that describes -h, --help in the usage output). Defaults to "show this help message and exit" when help_flags is provided or this field is set. Setting either help_flags or help_msg disables the standard argparse help mechanism so that the custom flags and message are used instead.

version: bool | str

Whether to add version information to the command. Defaults to False. If True, tries to find the version from the function’s package. If it is a string, use the string as the version information.

versionmodifier: Callable[[str], str] | None

A callable applied to the version string before it is passed to argparse’s version action. Receives the resolved version string (whether auto-detected from the package metadata or supplied directly via version) and must return the final string to display when --version is invoked. Useful for adding a program name prefix, ANSI colours, or extra build metadata (e.g. lambda v: f"my_tool {v}"). None leaves the version string unchanged. Has no effect when version is False.

versionhelp: str | None

The help text shown for the version option itself (the line that describes -v, --version in the usage output). Defaults to "show program's version number and exit".

keepvariadicprefixchars: bool

Whether to preserve the prefix chars in the variadic keyword argument dictionary, for unspecified arguments passed with flags.


CommandArguments()

class clig.CommandArguments

Arguments passed to Command. Include all arguments of clig.RunArguments and arguments for add_subparsers() method, prefixed by subcommands_, described in

https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_subparsers

subcommands_title: str | None | EllipsisType

Title for the sub-parser group in help output; by default "subcommands" if description is provided, otherwise uses title for positional arguments.

subcommands_description: str | None | EllipsisType

Description for the sub-parser group in help output. By default ..., which means it is not forward to the original method https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_subparsers.

subcommands_prog: str | None

Usage information that will be displayed with subcommand help, by default the name of the program and any positional arguments before the subparser argument.

subcommands_required: bool

Whether or not a subcommand must be provided, by default False (added in 3.7). https://docs.python.org/3/library/argparse.html#required

subcommands_help: str | None

Help for sub-parser group in help output, by default None. https://docs.python.org/3/library/argparse.html#help

subcommands_metavar: str | None

String presenting available subcommands in help; by default it is None and presents subcommands in form {cmd1, cmd2, ..}. https://docs.python.org/3/library/argparse.html#metavar


CompleteCommandArguments()

class clig.CompleteCommandArguments

All arguments passed to Command. Include all arguments of clig.CommandArguments and arguments for add_parser() method, described in

https://docs.python.org/3/library/argparse.html#subcommands

name: str | None

Name of the subcommand, taken by the add_parser() method.

help: str | None | EllipsisType

A help message for the subparser command.

aliases: Sequence[str]

Sequence that allows multiple strings to refer to the same subparser


Classes

Available public classes on the module:


Class Command()

class clig.Command

The base class to create commands from functions.

func: Callable[[...], ReturnType] | None = None

The function that will be turned into a command.

prog: str | None = None

The name of the program. The default is generated from the function name. https://docs.python.org/3/library/argparse.html#prog

usage: str | None = None

The string describing the program usage. The default is generated from arguments added to parser. https://docs.python.org/3/library/argparse.html#usage

description: str | None = None

Text to display before the argument help. By default, collected from the docstring when possible. https://docs.python.org/3/library/argparse.html#description

epilog: str | None = None

Text to display after the argument help. By default, collected from the docstring when possible. https://docs.python.org/3/library/argparse.html#epilog

parents: Sequence[ArgumentParser]

A list of ArgumentParser objects whose arguments should also be included. https://docs.python.org/3/library/argparse.html#parents

formatter_class

alias of RawTextHelpFormatter

prefix_chars: str = '-'

The set of characters that prefix optional arguments. Defaults to "-". https://docs.python.org/3/library/argparse.html#prefix-chars

fromfile_prefix_chars: str | None = None

The set of characters that prefix files from which additional arguments should be read. Defaults to None. https://docs.python.org/3/library/argparse.html#fromfile-prefix-chars

argument_default: Any = None

The global default value for arguments. Defaults to None. https://docs.python.org/3/library/argparse.html#argument-default

conflict_handler: str = 'error'

The strategy for resolving conflicting optionals (usually unnecessary). https://docs.python.org/3/library/argparse.html#conflict-handler

add_help: bool = True

Add a -h/--help option to the parser. Defaults to True. https://docs.python.org/3/library/argparse.html#add-help

allow_abbrev: bool = True

Allows long options to be abbreviated if the abbreviation is unambiguous. Defaults to True. https://docs.python.org/3/library/argparse.html#allow-abbrev

exit_on_error: bool = True

Determines whether or not ArgumentParser exits with error info when an error occurs. Defaults to True. https://docs.python.org/3/library/argparse.html#exit-on-error

subcommands_title: str | None | EllipsisType = Ellipsis

Title for the sub-parser group in help output; by default "subcommands" if description is provided, otherwise uses title for positional arguments.

subcommands_description: str | None | EllipsisType = Ellipsis

Description for the sub-parser group in help output. By default ..., which means it is not forward to the original method https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_subparsers.

subcommands_prog: str | None = None

Usage information that will be displayed with subcommand help, by default the name of the program and any positional arguments before the subparser argument.

subcommands_required: bool = False

Whether or not a subcommand must be provided, by default False (added in 3.7). https://docs.python.org/3/library/argparse.html#required

subcommands_help: str | None = None

Help for sub-parser group in help output, by default None. https://docs.python.org/3/library/argparse.html#help

subcommands_metavar: str | None = None

String presenting available subcommands in help; by default it is None and presents subcommands in form {cmd1, cmd2, ..}. https://docs.python.org/3/library/argparse.html#metavar

name: str | None = None

Name of the subcommand, taken by the add_parser() method.

help: str | None | EllipsisType = Ellipsis

A help message for the subparser command.

aliases: Sequence[str]

Sequence that allows multiple strings to refer to the same subparser

docstring_template: str | DocStr | None = None

The template used to parse parameter descriptions from the function’s docstring. When None, clig auto-detects the format by trying all known templates in order (NumPy, Sphinx, Google, clig-style). Set this explicitly to skip auto-detection and enforce a specific format. Use a DocStr enum member or any of the NUMPY_DOCSTRING, SPHINX_DOCSTRING, GOOGLE_DOCSTRING, CLIG_DOCSTRING module-level constants (and their variants).

default_bool: bool = False

The default value assumed for bool-annotated parameters when deciding the argparse action. When False (the default), a bool parameter with no default generates a store_true action (flag absent → False, flag present → True). When True, the action becomes store_false (flag absent → True, flag present → False). This setting is overridden per-argument when the parameter already has an explicit default value.

make_flags: bool | None = None

Whether to turn all positional-like parameters into optional flags (i.e. add a --name prefix). When None (the default), clig decides per-argument: parameters that have a default value are automatically promoted to flags; those without remain positional. Set to True to force every argument to be a flag, or False to keep every argument positional regardless of defaults. Per-argument make_flag metadata (using clig.data()) takes precedence over this setting.

make_shorts: bool | None = None

Whether to automatically generate a short flag (e.g. -n) alongside every long flag (e.g. --name). When None (the default) or False, only the long flag is used. When True, clig derives the shortest non-conflicting single-character option from the argument name and prepends it to the flag list. Short flags are also added to the help (-h) and version (-v) options when this is enabled.

metavarmodifier: str | Sequence[str] | Callable[[str], str] | None = None

A modifier applied to the displayed metavar of all arguments (both positional and optional) in the help output. A plain str replaces the metavar with that string; a Sequence[str] is used as a fixed tuple of metavar tokens (for multi-value arguments); a callable receives the argument name and must return the desired metavar string. None leaves the metavar at its argparse default. Acts as a fallback for both posmetavarmodifier and optmetavarmodifier when those are None.

posmetavarmodifier: str | Sequence[str] | Callable[[str], str] | None = None

A modifier applied to the metavar of positional arguments only. Follows the same rules as metavarmodifier (str, sequence, or callable). When set, takes precedence over metavarmodifier for positional arguments; when None, falls back to metavarmodifier.

optmetavarmodifier: str | Sequence[str] | Callable[[str], str] | None = None

A modifier applied to the metavar of optional (flagged) arguments only. Follows the same rules as metavarmodifier (str, sequence, or callable). When set, takes precedence over metavarmodifier for optional arguments; when None, falls back to metavarmodifier.

descriptionmodifier: Callable[[str], str] | None = None

A callable applied to the description string. Receives the current description string (may be an empty string if no description was found) and must return the final string to display. Useful for appending text, wrapping text, or adding ANSI colours uniformly. None leaves the description at its default.

epilogmodifier: Callable[[str], str] | None = None

A callable applied to the epilog string. Receives the current epilog string (may be an empty string if no epilog was found) and must return the final string to display. Useful for appending text, wrapping text, or adding ANSI colours uniformly. None leaves the epilog at its default.

usagemodifier: Callable[[str], str] | None = None

A callable applied to the usage string. Receives the current usage string and must return the final string to display. Useful for appending text, wrapping text, or adding ANSI colours uniformly. None leaves the usage at its default.

helpmodifier: Callable[[str], str] | None = None

A callable applied to the help string of all arguments before it is passed to argparse. Receives the current help string (may be an empty string if no help was found) and must return the final string to display. Useful for appending default values, wrapping text, or adding ANSI colours uniformly. Acts as a fallback for both poshelpmodifier and opthelpmodifier when those are None.

poshelpmodifier: Callable[[str], str] | None = None

A callable applied to the help string of positional arguments only. Follows the same contract as helpmodifier. When set, takes precedence over helpmodifier for positional arguments; when None, falls back to helpmodifier.

opthelpmodifier: Callable[[str], str] | None = None

A callable applied to the help string of optional (flagged) arguments only. Follows the same contract as helpmodifier. When set, takes precedence over helpmodifier for optional arguments; when None, falls back to helpmodifier.

help_flags: Sequence[str]

The flag strings that trigger the help action. Defaults to ("-h", "--help"). When this is non-empty or help_msg is set, the built-in argparse help is disabled (add_help=False) and a custom help argument is registered instead using these flags and help_msg. Pass an empty sequence together with help_msg to keep the default -h/--help flags while customizing only the message.

help_msg: str | None = None

The help text shown for the help option itself (the line that describes -h, --help in the usage output). Defaults to "show this help message and exit" when help_flags is provided or this field is set. Setting either help_flags or help_msg disables the standard argparse help mechanism so that the custom flags and message are used instead.

version: bool | str = False

Whether to add version information to the command. Defaults to False. If True, tries to find the version from the function’s package. If it is a string, use the string as the version information.

versionmodifier: Callable[[str], str] | None = None

A callable applied to the version string before it is passed to argparse’s version action. Receives the resolved version string (whether auto-detected from the package metadata or supplied directly via version) and must return the final string to display when --version is invoked. Useful for adding a program name prefix, ANSI colours, or extra build metadata (e.g. lambda v: f"my_tool {v}"). None leaves the version string unchanged. Has no effect when version is False.

versionhelp: str | None = None

The help text shown for the version option itself (the line that describes -v, --version in the usage output). Defaults to "show program's version number and exit".

keepvariadicprefixchars: bool = False

Whether to preserve the prefix chars in the variadic keyword argument dictionary, for unspecified arguments passed with flags.

subcommands: OrderedDict[str, Command]

Command` holding the subcommands registered on this command, in the order they were added. Not initialized in the constructor; populated via add_subcommand(). Empty (OrderedDict()) when this command has no subcommands.

Type:

An ordered mapping of `name

parent: Command | None = None

The parent Command instance in which this object is included as subcommand. It is not initialized in the constructor, and is None by default (when this object is the top level main command).

parser: ArgumentParser | None = None

The internal argparser.ArgumentParser original object. Used internally. Not initialized in the constructor.


subcommand(
func: Callable[[P], T] | None = None,
parent: Command | Callable | str | None = None,
**kwargs: Unpack[CompleteCommandArguments],
) Callable[[P], T] | Callable[[Callable[[P], T]], Callable[[P], T]]

Add a subcommand and return the input function unchanged. Suitable to use as decorator.

Registers func as a subcommand of parent (defaulting to the calling Command itself when parent is None) via new_subcommand. Can be used with or without parentheses, and with or without arguments: called directly as cmd.subcommand(func), or as a decorator @cmd.subcommand / @cmd.subcommand(...). Unlike new_subcommand, add_subcommand, and end_subcommand, the original function is returned unchanged rather than a Command instance, which makes it suitable for decorating functions that must remain callable as-is outside of CLI invocation.

Parameters

  • func (Callable[P, T] | None, optional): Defaults to None.

    The function that will be turned into a new subcommand. When None, the method is being used as a decorator with parentheses (e.g. @cmd.subcommand(...)), and func is supplied by the decorator machinery on the next call.

  • parent (Command | Callable | str | None, optional): Defaults to None.

    The command under which the new subcommand will be nested. Accepts a Command instance, a function previously registered as a subcommand, or a string matching a subcommand’s name. When None, defaults to the Command instance subcommand is called on.

  • **kwargs (Unpack[CompleteCommandArguments], variadic):

    Keyword arguments forwarded to new_subcommand (e.g. name, help, aliases, description, epilog, make_flags). See Command and CompleteCommandArguments for the full list of accepted options. Only used when func is None (i.e. the decorator-with-parentheses form).

Returns

Callable[P, T] | Callable[[Callable[P, T]], Callable[P, T]]:

The original func unchanged, when called directly or as a bare decorator. When used as @cmd.subcommand(...), returns a decorator that itself returns the original function unchanged once applied.


add_subcommand(
func: Callable[[...], Any],
**kwargs: Unpack[CompleteCommandArguments],
) Self

Add a subcommand and return the caller object. Suitable to add multiple subcommands in a row.

Registers func as a subcommand of the calling Command via new_subcommand, then returns the calling Command itself rather than the newly created subcommand. This makes it convenient to chain several calls together (e.g. cmd.add_subcommand(a).add_subcommand(b)) to register multiple sibling subcommands in a row without holding onto intermediate Command references.

Parameters

  • func (Callable[..., Any]):

    The function that will be turned into a new subcommand.

  • **kwargs (Unpack[CompleteCommandArguments], variadic):

    Additional keyword arguments forwarded to new_subcommand (e.g. name, help, aliases, description, epilog, make_flags). See Command and CompleteCommandArguments for the full list of accepted options.

Returns

Self:

The caller object itself, allowing further chained calls.


end_subcommand(
func: Callable[[...], Any],
**kwargs: Unpack[CompleteCommandArguments],
) Command

Add a subcommand and return the parent Command instance of the caller object.

Registers func as a subcommand of the calling Command via new_subcommand, then returns the caller’s parent Command rather than the caller or the new subcommand. This is useful for “closing out” a chain of subcommand registrations and stepping back up one level in the command hierarchy in a single call, mirroring the nesting of add_subcommand and new_subcommand chains.

Parameters

  • func (Callable[..., Any]):

    The function that will be turned into a new subcommand.

  • **kwargs (Unpack[CompleteCommandArguments], variadic):

    Additional keyword arguments forwarded to new_subcommand (e.g. name, help, aliases, description, epilog, make_flags). See Command and CompleteCommandArguments for the full list of accepted options.

Raises

ValueError:

If the caller’s parent attribute is None (i.e. it has no parent Command to return to).

Returns

Command:

The parent Command instance of the caller object.


new_subcommand(
func: Callable[[...], Any],
*,
name: str | None = None,
help: str | None | EllipsisType = Ellipsis,
aliases: Sequence[str] | None = None,
**kwargs: Unpack[CommandArguments],
) Command

Add a subcommand and return the new created subcommand (a new Command instance)

Wraps func in a new Command, registers it as a child of the calling Command, and tracks the chain of nested subparsers needed by argparse. This is the primitive that subcommand, add_subcommand, and end_subcommand all delegate to; use it directly when you need a reference to the newly created Command itself (e.g. to register further nested subcommands on it).

See: https://docs.python.org/3/library/argparse.html#subcommands

Parameters

  • func (Callable[..., Any]):

    The function that will be turned into a new subcommand.

  • name (str | None, optional): Defaults to None.

    The name used to invoke this subcommand on the command line. When None, derived from func.__name__ with underscores replaced by hyphens.

  • help (str | None, optional): Defaults to ... (Ellipsis).

    A short help message for the subcommand, shown next to its name in the parent command’s help listing. When left as ..., the first line of the subcommand’s description is used instead, if available.

  • aliases (Sequence[str] | None, optional): Defaults to None.

    Alternative names that can also be used to invoke this subcommand. Defaults to no aliases.

  • **kwargs (Unpack[CommandArguments], variadic):

    Additional keyword arguments forwarded to the new Command (e.g. description, epilog, make_flags). See Command and CommandArguments for the full list of accepted options.

Returns

Command:

The newly created subcommand, already linked to its parent and registered in self.subcommands.


print_help(file: TextIO | None = None) None

Print the command’s help message, including the program usage and information about the arguments.

Calls the underlying ArgumentParser.print_help() original method.

Parameters

  • file (TextIO | None, optional): Defaults to None.

    File to print. If file is None, sys.stdout is assumed.


run(args: Sequence[str] | None = None) ReturnType

Parse arguments to the Command’s function and invoke it.

Parameters

  • args (Sequence[str] | None, optional): Defaults to None.

    The argument list to parse. When None, defaults to sys.argv[1:].

Returns

ReturnType:

The return value of the wrapped function after parsing and invoking it.



Class ArgumentGroup()

class clig.ArgumentGroup

Wraps argparse’s argument groups. Pass an ArgumentGroup instance to clig.data(group=...) to register an argument under this group instead of the parser’s top level. The underlying argparse._ArgumentGroup is created lazily and stored on _argparse_argument_group once the parser is built.

See: https://docs.python.org/3/library/argparse.html#argument-groups

title: str | None = None

The title displayed above the group’s arguments in the help message. When None, argparse falls back to its default group heading.

description: str | None = None

Additional text displayed below the title and above the group’s arguments in the help message.

argument_default: Any = None

The default value to use for arguments in this group that don’t otherwise specify one.

conflict_handler: str = 'error'

The strategy used to resolve conflicting argument definitions within the group, as accepted by argparse’s conflict_handler.


Class MutuallyExclusiveGroup()

class clig.MutuallyExclusiveGroup

Wraps argparse’s mutually exclusive groups. Pass a MutuallyExclusiveGroup instance to clig.data(group=...) to register an argument as part of this group. A mutually exclusive group can optionally be nested inside an ArgumentGroup via argument_group; alternatively, supplying title, description, argument_default, or conflict_handler directly will cause an ArgumentGroup to be created automatically to hold it (these two ways of specifying a parent group are mutually exclusive with each other). The underlying argparse._MutuallyExclusiveGroup is created lazily and stored on _argparse_mutually_exclusive_group once the parser is built.

See: https://docs.python.org/3/library/argparse.html#mutual-exclusion

required: bool = False

Whether exactly one of the arguments in the group must be provided. When False, none of the arguments are required, but at most one may still be given.

argument_group: ArgumentGroup | None = None

Defaults to None. An existing ArgumentGroup to nest this mutually exclusive group inside. Cannot be combined with title, description, argument_default, or conflict_handler.

title: str | None = None

Title for an automatically created parent ArgumentGroup. Only valid when argument_group is not provided.

description: str | None = None

Description for an automatically created parent ArgumentGroup. Only valid when argument_group is not provided.

argument_default: Any = None

Default value for an automatically created parent ArgumentGroup. Only valid when argument_group is not provided.

conflict_handler: str | None = None

Conflict handling strategy for an automatically created parent ArgumentGroup. Only valid when argument_group is not provided.


Class ArgumentMetaData()

class clig.ArgumentMetaData

Per-argument metadata consumed by clig when building the argument parser.

Produced by clig.data() and attached to a parameter via an Arg (i.e. Annotated) type hint. Each field mirrors one of clig.data()’s parameters and overrides the command-level defaults for that specific argument only.

flags: list[str]

Explicit flag strings for this argument (e.g. ["-v", "--verbose"]). When non-empty, these replace any flags clig would have generated automatically. An empty list defers flag generation to make_flag and the command-level make_flags option.

make_flag: bool | None = None

Whether to promote this argument to an optional flag. Overrides the command-level make_flags setting for this argument only. None defers to the command-level default.

group: ArgumentGroup | MutuallyExclusiveGroup | None = None

The argument group or mutually exclusive group this argument belongs to. When set, the argument is registered under that group instead of the top-level parser. None places the argument at the top level.

helpmodifier: Callable[[str], str] | None = None

A callable applied to this argument’s help string only, taking precedence over the command-level opthelpmodifier, poshelpmodifier, and helpmodifier settings. None falls back to the command-level modifiers.

dictionary: KeywordArguments

Additional keyword arguments forwarded verbatim to argparse’s add_argument() (e.g. action, nargs, const, choices, required, help, metavar, default, type).


Class Context()

class clig.Context

Runtime information about the current CLI invocation, injectable into a command function.

A Context instance is built automatically when a command is run and can be requested by a command function simply by annotating one of its parameters with the Context type (optionally parameterized, e.g. Context[Namespace]). clig detects this annotation and injects the live context instead of sourcing the parameter’s value from the parsed arguments. For subcommands, the same Context object as the top-level command is reused, so state set while parsing the main command remains visible to nested subcommands.

namespace: T

The argparse.Namespace (or generic type T) produced by parsing the command-line arguments for this invocation.

command: Command

The Command instance that is currently being run. For a subcommand invocation, this still refers to the top-level (parent) command.


Class DocStr()

class clig.DocStr

Built-in docstring templates to use in inferring function/argument information.

DESCRIPTION_DOCSTRING = '{{description}}'
DESCRIPTION_EPILOG_DOCSTRING = '\n    {{description}}    \n\n    {{epilog}}\n'
NUMPY_DOCSTRING_WITH_EPILOG = '\n    {{description}}\n\n    {{epilog}}\n\n    Parameters\n    ----------\n    {{parameter_name}} : {{parameter_type}}\n        {{parameter_description}}\n'
NUMPY_DOCSTRING_WITH_EPILOG_NOTYPES = '\n    {{description}}\n\n    {{epilog}}\n\n    Parameters\n    ----------\n    {{parameter_name}}\n        {{parameter_description}}\n'
SPHINX_DOCSTRING_WITH_EPILOG = '\n{{description}}\n\n{{epilog}}\n\n:param {{parameter_name}}: {{parameter_description}}\n:type {{parameter_name}}: {{parameter_type}}\n'
SPHINX_DOCSTRING_WITH_EPILOG_NOTYPES = '\n{{description}}\n\n{{epilog}}\n\n:param {{parameter_name}}: {{parameter_description}}\n'
GOOGLE_DOCSTRING_WITH_EPILOG = '\n{{description}}\n\n{{epilog}}\n\nArgs:\n    {{parameter_name}} ({{parameter_type}}): {{parameter_description}}\n'
GOOGLE_DOCSTRING_WITH_EPILOG_NOTYPES = '\n{{description}}\n\n{{epilog}}\n\nArgs:\n    {{parameter_name}}: {{parameter_description}}\n'
CLIG_DOCSTRING_WITH_EPILOG = '\n{{description}}\n\n{{epilog}}\n\nParameters\n----------\n- `{{parameter_name}}` {{parameter_type}}\n    {{parameter_description}}\n'
NUMPY_DOCSTRING = '\n    {{description}}\n\n    Parameters\n    ----------\n    {{parameter_name}} : {{parameter_type}}\n        {{parameter_description}}\n'
SPHINX_DOCSTRING = '\n{{description}}\n\n:param {{parameter_name}}: {{parameter_description}}\n:type {{parameter_name}}: {{parameter_type}}\n'
GOOGLE_DOCSTRING = '\n{{description}}\n\nArgs:\n    {{parameter_name}} ({{parameter_type}}): {{parameter_description}}\n'
CLIG_DOCSTRING = '\n{{description}}\n\nParameters\n----------\n- `{{parameter_name}}` {{parameter_type}}\n    {{parameter_description}}\n'
CLIG_DOCSTRING_SHORT = '\n{{description}}\n\nParameters\n----------\n- `{{parameter_name}}` {{parameter_type}}: {{parameter_description}}\n'
GOOGLE_DOCSTRING_NOTYPES = '\n{{description}}\n\nArgs:\n    {{parameter_name}}: {{parameter_description}}\n'