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],
Parse arguments and invoke the CLI command.
When called with a function, wraps it in a
Command(forwarding any extrakwargs) 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 toNone.The function to expose as a CLI command. When
None, the global main command registered via@clig.commandis used instead.
args(Sequence[str] | None, optional): Defaults toNone.The argument list to parse. When
None, defaults tosys.argv[1:].
**kwargs(Unpack[RunArguments], variadic):Additional keyword arguments forwarded to
Commandwhenfuncis provided. Has no effect whenfuncisNone. SeeCommandandRunArgumentsfor 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],
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 anArgumentMetaDataobject consumed bycligwhen 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 flagscligwould have generated automatically. Passing no flags leaves flag generation to themake_flagsetting and the command-levelmake_flagsoption.
make_flag(bool | None, optional): Defaults toNone.Whether to promote this specific argument to an optional flag. Overrides the command-level
make_flagssetting for this argument only.Nonedefers to the command-level default.
group(ArgumentGroup | MutuallyExclusiveGroup | None, optional): Defaults toNone.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.
Noneplaces the argument at the top level.
helpmodifier(Callable[[str], str] | None | None, optional): Defaults toNone.A callable applied to this argument’s help string only, taking precedence over the command-level
opthelpmodifier,poshelpmodifier, andhelpmodifiersettings.Nonefalls 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 toadd_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],
Register a function as the main CLI command.
Decorator that wraps a function in a
Commandand 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.commandmay only be applied once per program.Parameters¶
func(Function = Callable[..., Any] | None, optional): Defaults toNone.The function to register as the main command. When
None, the decorator is called with parentheses andfuncis supplied by the outer decorator machinery.
**kwargs(Unpack[CompleteCommandArguments], variadic):Keyword arguments forwarded to
Command(e.g.prog,description,epilog,make_flags). SeeCommandandCompleteCommandArgumentsfor 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],
Register a function as a subcommand of an existing command.
Decorator that attaches a function to a parent
Commandas a named subcommand. Can be used with or without parentheses. The parent may be specified as aCommandinstance, 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 toNone.The function to register as a subcommand. When
None, the decorator is called with parentheses andfuncis supplied by the outer decorator machinery.
parent(Command | Callable | str | None, optional): Defaults toNone.The command under which this subcommand will be nested. Accepts a
Commandinstance, the function that was decorated with@clig.commandor@clig.subcommand, or a plain string matching the subcommand name. WhenNone, defaults to the global main command registered viaclig.command().
**kwargs(Unpack[CompleteCommandArguments], variadic):Keyword arguments forwarded to
Command.add_subcommand(e.g.prog,description,epilog,make_flags). SeeCommandandCompleteCommandArgumentsfor 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,
Formatter prepared to wrap text.
Parameters¶
text(str):The text to format.
width(int | None, optional): Defaults toNone.The width to wrap the text.
space(int, optional): Defaults to24.The space used to indent all text.
dedent(bool, optional): Defaults toFalse.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 ofargparse.ArgumentParser, described inhttps://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
ArgumentParserobjects 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/--helpoption to the parser. Defaults toTrue. 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,cligauto-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 aDocStrenum member or any of theNUMPY_DOCSTRING,SPHINX_DOCSTRING,GOOGLE_DOCSTRING,CLIG_DOCSTRINGmodule-level constants (and their variants).
- default_bool: bool¶
The default value assumed for
bool-annotated parameters when deciding the argparse action. WhenFalse(the default), aboolparameter with no default generates astore_trueaction (flag absent →False, flag present →True). WhenTrue, the action becomesstore_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
--nameprefix). WhenNone(the default),cligdecides per-argument: parameters that have a default value are automatically promoted to flags; those without remain positional. Set toTrueto force every argument to be a flag, orFalseto keep every argument positional regardless of defaults. Per-argumentmake_flagmetadata (usingclig.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). WhenNone(the default) orFalse, only the long flag is used. WhenTrue,cligderives 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
strreplaces the metavar with that string; aSequence[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.Noneleaves the metavar at its argparse default. Acts as a fallback for bothposmetavarmodifierandoptmetavarmodifierwhen those areNone.
- 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 overmetavarmodifierfor positional arguments; whenNone, falls back tometavarmodifier.
- 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 overmetavarmodifierfor optional arguments; whenNone, falls back tometavarmodifier.
- 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.
Noneleaves 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.
Noneleaves 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.
Noneleaves 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
poshelpmodifierandopthelpmodifierwhen those areNone.
- 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 overhelpmodifierfor positional arguments; whenNone, falls back tohelpmodifier.
- 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 overhelpmodifierfor optional arguments; whenNone, falls back tohelpmodifier.
- help_flags: Sequence[str]¶
The flag strings that trigger the help action. Defaults to
("-h", "--help"). When this is non-empty orhelp_msgis set, the built-in argparse help is disabled (add_help=False) and a custom help argument is registered instead using these flags andhelp_msg. Pass an empty sequence together withhelp_msgto keep the default-h/--helpflags while customizing only the message.
- help_msg: str | None¶
The help text shown for the help option itself (the line that describes
-h, --helpin the usage output). Defaults to"show this help message and exit"whenhelp_flagsis provided or this field is set. Setting eitherhelp_flagsorhelp_msgdisables 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. IfTrue, 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
versionaction. Receives the resolved version string (whether auto-detected from the package metadata or supplied directly viaversion) and must return the final string to display when--versionis invoked. Useful for adding a program name prefix, ANSI colours, or extra build metadata (e.g.lambda v: f"my_tool {v}").Noneleaves the version string unchanged. Has no effect whenversionisFalse.
- versionhelp: str | None¶
The help text shown for the version option itself (the line that describes
-v, --versionin 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 ofclig.RunArgumentsand arguments foradd_subparsers()method, prefixed bysubcommands_, described inhttps://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
Noneand 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 ofclig.CommandArgumentsand arguments foradd_parser()method, described inhttps://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
ArgumentParserobjects 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/--helpoption to the parser. Defaults toTrue. 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
Noneand 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,cligauto-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 aDocStrenum member or any of theNUMPY_DOCSTRING,SPHINX_DOCSTRING,GOOGLE_DOCSTRING,CLIG_DOCSTRINGmodule-level constants (and their variants).
- default_bool: bool = False¶
The default value assumed for
bool-annotated parameters when deciding the argparse action. WhenFalse(the default), aboolparameter with no default generates astore_trueaction (flag absent →False, flag present →True). WhenTrue, the action becomesstore_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
--nameprefix). WhenNone(the default),cligdecides per-argument: parameters that have a default value are automatically promoted to flags; those without remain positional. Set toTrueto force every argument to be a flag, orFalseto keep every argument positional regardless of defaults. Per-argumentmake_flagmetadata (usingclig.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). WhenNone(the default) orFalse, only the long flag is used. WhenTrue,cligderives 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
strreplaces the metavar with that string; aSequence[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.Noneleaves the metavar at its argparse default. Acts as a fallback for bothposmetavarmodifierandoptmetavarmodifierwhen those areNone.
- 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 overmetavarmodifierfor positional arguments; whenNone, falls back tometavarmodifier.
- 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 overmetavarmodifierfor optional arguments; whenNone, falls back tometavarmodifier.
- 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.
Noneleaves 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.
Noneleaves 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.
Noneleaves 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
poshelpmodifierandopthelpmodifierwhen those areNone.
- 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 overhelpmodifierfor positional arguments; whenNone, falls back tohelpmodifier.
- 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 overhelpmodifierfor optional arguments; whenNone, falls back tohelpmodifier.
- help_flags: Sequence[str]¶
The flag strings that trigger the help action. Defaults to
("-h", "--help"). When this is non-empty orhelp_msgis set, the built-in argparse help is disabled (add_help=False) and a custom help argument is registered instead using these flags andhelp_msg. Pass an empty sequence together withhelp_msgto keep the default-h/--helpflags while customizing only the message.
- help_msg: str | None = None¶
The help text shown for the help option itself (the line that describes
-h, --helpin the usage output). Defaults to"show this help message and exit"whenhelp_flagsis provided or this field is set. Setting eitherhelp_flagsorhelp_msgdisables 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. IfTrue, 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
versionaction. Receives the resolved version string (whether auto-detected from the package metadata or supplied directly viaversion) and must return the final string to display when--versionis invoked. Useful for adding a program name prefix, ANSI colours, or extra build metadata (e.g.lambda v: f"my_tool {v}").Noneleaves the version string unchanged. Has no effect whenversionisFalse.
- versionhelp: str | None = None¶
The help text shown for the version option itself (the line that describes
-v, --versionin 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
Commandinstance in which this object is included as subcommand. It is not initialized in the constructor, and isNoneby default (when this object is the top level main command).
- parser: ArgumentParser | None = None¶
The internal
argparser.ArgumentParseroriginal object. Used internally. Not initialized in the constructor.
- subcommand(
- func: Callable[[P], T] | None = None,
- parent: Command | Callable | str | None = None,
- **kwargs: Unpack[CompleteCommandArguments],
Add a subcommand and return the input function unchanged. Suitable to use as decorator.
Registers
funcas a subcommand ofparent(defaulting to the callingCommanditself whenparentisNone) vianew_subcommand. Can be used with or without parentheses, and with or without arguments: called directly ascmd.subcommand(func), or as a decorator@cmd.subcommand/@cmd.subcommand(...). Unlikenew_subcommand,add_subcommand, andend_subcommand, the original function is returned unchanged rather than aCommandinstance, 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 toNone.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(...)), andfuncis supplied by the decorator machinery on the next call.
parent(Command | Callable | str | None, optional): Defaults toNone.The command under which the new subcommand will be nested. Accepts a
Commandinstance, a function previously registered as a subcommand, or a string matching a subcommand’s name. WhenNone, defaults to theCommandinstancesubcommandis called on.
**kwargs(Unpack[CompleteCommandArguments], variadic):Keyword arguments forwarded to
new_subcommand(e.g.name,help,aliases,description,epilog,make_flags). SeeCommandandCompleteCommandArgumentsfor the full list of accepted options. Only used whenfuncisNone(i.e. the decorator-with-parentheses form).
Returns¶
Callable[P, T] | Callable[[Callable[P, T]], Callable[P, T]]:The original
funcunchanged, 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],
Add a subcommand and return the caller object. Suitable to add multiple subcommands in a row.
Registers
funcas a subcommand of the callingCommandvianew_subcommand, then returns the callingCommanditself 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 intermediateCommandreferences.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). SeeCommandandCompleteCommandArgumentsfor the full list of accepted options.
Returns¶
Self:The caller object itself, allowing further chained calls.
- end_subcommand(
- func: Callable[[...], Any],
- **kwargs: Unpack[CompleteCommandArguments],
Add a subcommand and return the parent
Commandinstance of the caller object.Registers
funcas a subcommand of the callingCommandvianew_subcommand, then returns the caller’s parentCommandrather 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 ofadd_subcommandandnew_subcommandchains.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). SeeCommandandCompleteCommandArgumentsfor the full list of accepted options.
Raises¶
ValueError:If the caller’s
parentattribute isNone(i.e. it has no parentCommandto return to).
Returns¶
Command:The parent
Commandinstance 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],
Add a subcommand and return the new created subcommand (a new
Commandinstance)Wraps
funcin a newCommand, registers it as a child of the callingCommand, and tracks the chain of nested subparsers needed byargparse. This is the primitive thatsubcommand,add_subcommand, andend_subcommandall delegate to; use it directly when you need a reference to the newly createdCommanditself (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 toNone.The name used to invoke this subcommand on the command line. When
None, derived fromfunc.__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’sdescriptionis used instead, if available.
aliases(Sequence[str] | None, optional): Defaults toNone.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). SeeCommandandCommandArgumentsfor 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 toNone.File to print. If
fileisNone,sys.stdoutis 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 toNone.The argument list to parse. When
None, defaults tosys.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 anArgumentGroupinstance toclig.data(group=...)to register an argument under this group instead of the parser’s top level. The underlyingargparse._ArgumentGroupis created lazily and stored on_argparse_argument_grouponce 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’sconflict_handler.
Class MutuallyExclusiveGroup()¶
- class clig.MutuallyExclusiveGroup¶
Wraps
argparse’s mutually exclusive groups. Pass aMutuallyExclusiveGroupinstance toclig.data(group=...)to register an argument as part of this group. A mutually exclusive group can optionally be nested inside anArgumentGroupviaargument_group; alternatively, supplyingtitle,description,argument_default, orconflict_handlerdirectly will cause anArgumentGroupto be created automatically to hold it (these two ways of specifying a parent group are mutually exclusive with each other). The underlyingargparse._MutuallyExclusiveGroupis created lazily and stored on_argparse_mutually_exclusive_grouponce 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 existingArgumentGroupto nest this mutually exclusive group inside. Cannot be combined withtitle,description,argument_default, orconflict_handler.
- title: str | None = None¶
Title for an automatically created parent
ArgumentGroup. Only valid whenargument_groupis not provided.
- description: str | None = None¶
Description for an automatically created parent
ArgumentGroup. Only valid whenargument_groupis not provided.
- argument_default: Any = None¶
Default value for an automatically created parent
ArgumentGroup. Only valid whenargument_groupis not provided.
- conflict_handler: str | None = None¶
Conflict handling strategy for an automatically created parent
ArgumentGroup. Only valid whenargument_groupis not provided.
Class ArgumentMetaData()¶
- class clig.ArgumentMetaData¶
Per-argument metadata consumed by
cligwhen building the argument parser.Produced by
clig.data()and attached to a parameter via anArg(i.e.Annotated) type hint. Each field mirrors one ofclig.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 flagscligwould have generated automatically. An empty list defers flag generation tomake_flagand the command-levelmake_flagsoption.
- make_flag: bool | None = None¶
Whether to promote this argument to an optional flag. Overrides the command-level
make_flagssetting for this argument only.Nonedefers 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.
Noneplaces 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, andhelpmodifiersettings.Nonefalls 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
Contextinstance is built automatically when a command is run and can be requested by a command function simply by annotating one of its parameters with theContexttype (optionally parameterized, e.g.Context[Namespace]).cligdetects this annotation and injects the live context instead of sourcing the parameter’s value from the parsed arguments. For subcommands, the sameContextobject 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 typeT) produced by parsing the command-line arguments for this invocation.
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'¶