Skip to content

API reference

Maurice Lam edited this page May 24, 2019 · 25 revisions

@command

A decorator to add command line parsing functionality to the function. The returned function is the same as the original one, but with the execute function added to it. Arguments are added according to the parameters of the wrapped function.

  • Positional parameters, which are any parameter before * or *args in the argument list, are interpreted as positional arguments in the parser. These arguments can be required if the default values are omitted (def func(arg), or optional if a default value is provided (def func(arg=None)).

  • Variadic parameters, which are parameters in the form *args, are interpreted as a list argument which will take all the remaining position arguments when parsing from command line. A special case is when the argument is named _REMAINDER_, or if Argument(remainder=True) is specified. In which case, this argument will be a sequence capturing all remaining arguments, including optional ones (e.g. --foo).

  • Keyword parameters, which are any parameter after * or *args in the argument list, are interpreted as optional arguments, or sometimes known as flags. By default the argument name is taken as the flag name, with any trailing underscores (_) stripped out. For example, if the parameter name is foo, the flag name is --foo.

    The action of the flag varies by the type of the default value. If the default value is False, the action will be argparse's store_true, which means the parameter's value will be True if --foo is specified, or False otherwise. Similarly, if the default value is True, the parameter value will be True unless --nofoo is specified. If the default value is not a bool, optional argument value will be assigned to the parameter. For example, --foo bar will set the value of foo to bar.

@command
def main(arg1, *, flag1=False):
    # Do stuff

@command.delegator

@command.delegator works the same way as a @command, but when --help or tab-completion is invoked, instead of running its own help or completion methods immediately, it will first try to delegate to a subcommand, so that a command like git branch --help will show the help page of git branch, not git itself.

When implementing a delegator, the implementation must either call .execute() on another command, or raise NoMatchingDelegate exception. Any other side-effects, like printing to the terminal or writing to any files, are undesired.

Also see the subcommands function which will is a convenience function to create delegating commands based on key-value pairs.

NoMatchingDelegate

An exception that should be raised when implementing a @command.delegator when a matching delegator could not be found.

Argument

subcommands

HashbangCommand

Clone this wiki locally