API

class cappa.Arg

Describe a CLI argument.

Parameters:
  • value_name – Placeholder for the argument’s value in the help message / usage. Defaults to the name of the corresponding class field.

  • short – If True, uses first letter of the name to infer a (ex. -s) short flag. If a string is supplied, that will be used instead. If a string is supplied, it is split on ‘/’ (forward slash), to support multiple options. Additionally accepts a list of strings.

  • long – If True, uses first letter of the name to infer a (ex. –long) long flag. If a string is supplied, that will be used instead. If a string is supplied, it is split on ‘/’ (forward slash), to support multiple options. Additionally accepts a list of strings.

  • count – If True the resultant argmuent will count instances and accept zero arguments.

  • default – An explicit default CLI value. When left unspecified, the default is inferred from the class’ default or the adapter default/default_factory.

  • help – By default, the help text will be inferred from the containing class’ arguments’ section, if it exists. Alternatively, you can directly supply the help text here.

  • parse – An optional function which accepts the raw string argument as input and returns a parsed value type’s instance. This should only be required for complex types that the type system’s built-in parsing cannot handle.

  • group – Optional group names for the argument. This affects how they’re displayed in the backended help text.

  • hidden – Whether the argument should be hidden in help text. Defaults to False.

  • action – Generally automatically inferred from the data type. This allows to override the default.

  • num_args – Generally automatically inferred from the data type. This allows to override the default.

  • choices – Generally automatically inferred from the data type. This allows to override the default.

  • completion – Used to provide custom completions. If specified, should be a function which accepts a partial string value and returns a list of [cappa.Completion](cappa.Completion) objects.

  • required – Defaults to automatically inferring requiredness, based on whether the class’s value has a default. By setting this, you can force a particular value.

  • field_name – The name of the class field to populate with this arg. In most usecases, this field should be left unspecified and automatically inferred.

  • deprecated – If supplied, the argument will be marked as deprecated. If given True, a default message will be generated, otherwise a supplied string will be used as the deprecation message.

action
annotations
choices
classmethod collect(field, type_hint, fallback_help=None, default_short=False, default_long=False)
Parameters:
  • field (cappa.class_inspect.Field)

  • type_hint (type)

  • fallback_help (str | None)

  • default_short (bool)

  • default_long (bool)

Return type:

Arg

completion
count = False
default
deprecated = False
field_name
group
help
hidden = False
long = False
names(*, n=0)
Return type:

list[str]

names_str(delimiter=', ', *, n=0)
Parameters:

delimiter (str)

Return type:

str

normalize(annotation=NoneType, fallback_help=None, action=None, default=missing, field_name=None, default_short=False, default_long=False)
Parameters:
Return type:

Arg

num_args
parse
required
short = False
value_name
class cappa.ArgAction

Arg action typee.

Options:
  • set: Stores the given CLI value directly.

  • store_true: Stores a literal True value, causing options to not attempt to consume additional CLI arguments

  • store_false: Stores a literal False value, causing options to not attempt to consume additional CLI arguments

  • append: Produces a list, and accumulates the given value on top of prior values.

  • count: Increments an integer starting at 0

  • help: Cancels argument parsing and prints the help text

  • version: Cancels argument parsing and prints the CLI version

  • completion: Cancels argument parsing and enters “completion mode”

append = append
completion = completion
count = count
help = help
classmethod is_custom(action)
Parameters:

action (ArgAction | collections.abc.Callable | None)

set = store
store_false = store_false
store_true = store_true
classmethod value_actions()
Return type:

Set[ArgAction]

version = version
class cappa.Command

Register a cappa CLI command/subcomment.

Parameters:
  • cmd_cls – The class representing the command/subcommand

  • name – The name of the command. If omitted, the name of the command will be the name of the cls, converted to dash-case.

  • help – Optional help text. If omitted, the cls docstring will be parsed, and the headline section will be used to document the command itself, and the arguments section will become the default help text for any params/options.

  • description – Optional extended help text. If omitted, the cls docstring will be parsed, and the extended long description section will be used.

  • invoke – Optional command to be called in the event parsing is successful. In the case of subcommands, it will only call the parsed/selected function to invoke. The value can either be a callable object or a string. When the value is a string it will be interpreted as module.submodule.function; the module will be dynamically imported, and the referenced function invoked.

  • hidden – If True, the command will not be included in the help output. This option is only relevant to subcommands.

  • default_short – If True, all arguments will be treated as though annotated with Annotated[T, Arg(short=True)], unless otherwise annotated.

  • default_true – If True, all arguments will be treated as though annotated with Annotated[T, Arg(long=True)], unless otherwise annotated.

  • deprecated – If supplied, the argument will be marked as deprecated. If given True, a default message will be generated, otherwise a supplied string will be used as the deprecation message.

add_meta_actions(help=None, version=None, completion=None)
Parameters:
  • help (cappa.arg.Arg | None)

  • version (cappa.arg.Arg | None)

  • completion (cappa.arg.Arg | None)

arguments
cmd_cls
classmethod collect(command)
Parameters:

command (Command[T])

Return type:

Command[T]

default_long = False
default_short = False
deprecated = False
description
classmethod get(obj)
Parameters:

obj (type[T] | Command[T])

Return type:

Command[T]

help
hidden = False
invoke
map_result(command, prog, parsed_args)
Parameters:
Return type:

T

name
classmethod parse_command(command, *, output, backend, argv=None)
Parameters:
  • command (Command[T])

  • output (cappa.output.Output)

  • backend (Callable)

  • argv (list[str] | None)

Return type:

tuple[Command, Command[T], T]

real_name()
Return type:

str

value_arguments()
class cappa.Completion
help
value
class cappa.Dep

Describes the callable required to fullfill a given dependency.

callable
class cappa.Env(env_var, *env_vars, default=None)

Lazily evaluates environment variables in the order given.

Argument value interpolation will handle and Arg’s default being an Env instance, by evaluating the Env, in the event the parser-level value fell back to the default.

Examples

>>> from cappa import Arg, Env
>>> arg = Arg(default=Env("HOST", "HOSTNAME", default="localhost"))
Parameters:
  • env_var (str)

  • env_vars (str)

  • default (str | None)

default
env_vars
evaluate()
Return type:

str | None

exception cappa.Exit(message=None, *, command=None, code=0, prog=None)

Request to exit from the interpreter.

Parameters:
  • message (list[Displayable] | Displayable | None)

  • command (cappa.command.Command | None)

  • code (str | int | None)

  • prog (str | None)

class cappa.FileMode

Factory for creating file object types.

Instances of FileType are typically passed as type= arguments to the ArgumentParser add_argument() method.

Parameters:
  • mode – The file mode to use to open the file. Passes directly through to builtin open().

  • buffering – The file’s desired buffer size. Passes directly through to builtin open().

  • encoding – The file’s encoding. Passes directly through to builtin open().

  • errors – A string indicating how encoding and decoding errors are to be handled. Passes directly through to builtin open().

  • error_code – The exit code to use when an error occurs. Defaults to 1. Note this is not an open() argument.

buffering
encoding
error_code = 1
errors
mode = r
class cappa.Output

Output sink for CLI std out and error streams.

For simple customization (namely disabling color and overriding the theme), invoke and parse accept color and theme arguments, which internally configure the output_console and error_console fields.

For more involved customization, an Output object can be supplied into either invoke or parse functions as well.

Note, all input arguments to Output are optional.

Parameters:
  • output_console – Output sink, defaults to printing to stdout.

  • error_console – Error sink, defaults to printing to stderr.

  • output_format – Format string through which output_console output will be formatted. The following format string named format arguments can be used in output_format: prog, code, message.

  • error_format – Format string through which output_console error will be formatted. The following format string named format arguments can be used in error_format: prog, code, message, help, short_help.

Examples

>>> output = Output()
>>> output = Output(error_format="{prog}: error: {message}")
color(value=True)

Override the default color setting (None), to an explicit True/False value.

Parameters:

value (bool)

error(message, **context)

Output a message to the error_console.

Additional **context can be supplied into the error_format string template.

Parameters:

message (list[Displayable] | Displayable | Exit | str | None)

error_console
error_format
exit(e, help=None, short_help=None)

Print a cappa.Exit object to the appropriate console.

Parameters:
  • e (Exit)

  • help (list[Displayable] | None)

  • short_help (Displayable | None)

output(message, **context)

Output a message to the output_console.

Additional **context can be supplied into the output_format string template.

Parameters:

message (list[Displayable] | Displayable | Exit | str | None)

output_console
output_format
theme(t)

Override the default Theme, or reset the theme back to default (with None).

Parameters:

t (rich.theme.Theme | None)

write(console, message)
Parameters:
  • console (rich.console.Console)

  • message (rich.text.Text | str | None)

class cappa.Subcommand

Describe a CLI subcommand.

Parameters:
  • name – Defaults to the name of the class, converted to dash case, but can be overridden here.

  • types – Defaults to the class’s annotated types, but can be overridden here.

  • required – Defaults to automatically inferring requiredness, based on whether the class’s value has a default. By setting this, you can force a particular value.

  • hidden – Whether the argument should be hidden in help text. Defaults to False.

available_options()
Return type:

list[cappa.command.Command]

classmethod collect(field, type_hint)
Parameters:
  • field (cappa.class_inspect.Field)

  • type_hint (type)

Return type:

typing_extensions.Self | None

completion(partial)
Parameters:

partial (str)

field_name = Ellipsis
group = (3, 'Subcommands')
hidden = False
map_result(prog, parsed_args)
Parameters:

prog (str)

names()
Return type:

list[str]

names_str(delimiter=', ')
Parameters:

delimiter (str)

Return type:

str

normalize(annotation=NoneType, field_name=None)
Parameters:

field_name (str | None)

Return type:

typing_extensions.Self

options
required
types = Ellipsis
cappa.collect(obj, *, backend=None, version=None, help=True, completion=True)

Retrieve the Command object from a cappa-capable source class.

Parameters:
  • obj (type[T] | cappa.command.Command[T]) – A class which can represent a CLI command chain.

  • backend (Callable | None) – A function used to perform the underlying parsing and return a raw parsed state. This defaults to constructing built-in function using argparse.

  • version (str | cappa.arg.Arg | None) – If a string is supplied, adds a -v/–version flag which returns the given string as the version. If an Arg is supplied, uses the name/short/long/help fields to add a corresponding version argument. Note the name is assumed to be the CLI’s version, e.x. Arg(‘1.2.3’, help=”Prints the version”).

  • help (bool | cappa.arg.Arg) – If True (default to True), adds a -h/–help flag. If an Arg is supplied, uses the short/long/help fields to add a corresponding help argument.

  • completion (bool | cappa.arg.Arg) – Enables completion when using the cappa backend option. If True (default to True), adds a –completion flag. An Arg can be supplied to customize the argument’s behavior.

  • color – Whether to output in color.

Return type:

cappa.command.Command[T]

cappa.command(_cls=None, *, name=None, help=None, description=None, invoke=None, hidden=False, default_short=False, default_long=False, deprecated=False)

Register a cappa CLI command/subcomment.

Parameters:
  • name (str | None) – The name of the command. If omitted, the name of the command will be the name of the cls, converted to dash-case.

  • help (str | None) – Optional help text. If omitted, the cls docstring will be parsed, and the headline section will be used to document the command itself, and the arguments section will become the default help text for any params/options.

  • description (str | None) – Optional extended help text. If omitted, the cls docstring will be parsed, and the extended long description section will be used.

  • invoke (Callable | str | None) – Optional command to be called in the event parsing is successful. In the case of subcommands, it will only call the parsed/selected function to invoke.

  • hidden (bool) – If True, the command will not be included in the help output. This option is only relevant to subcommands.

  • default_short (bool) – If True, all arguments will be treated as though annotated with Annotated[T, Arg(short=True)], unless otherwise annotated.

  • default_long (bool) – If True, all arguments will be treated as though annotated with Annotated[T, Arg(long=True)], unless otherwise annotated.

  • deprecated (bool) – If supplied, the argument will be marked as deprecated. If given True, a default message will be generated, otherwise a supplied string will be used as the deprecation message.

cappa.invoke(obj, *, deps=None, argv=None, backend=None, color=True, version=None, help=True, completion=True, theme=None, output=None)

Parse the command, and invoke the selected async command or subcommand.

In the event that a subcommand is selected, only the selected subcommand function is invoked.

Parameters:
  • obj (type | cappa.command.Command) – A class which can represent a CLI command chain.

  • deps (Sequence[Callable] | Mapping[Callable, cappa.invoke.Dep | Any] | None) – Optional extra depdnencies to load ahead of invoke processing. These deps are evaluated in order and unconditionally.

  • argv (list[str] | None) – Defaults to the process argv. This command is generally only necessary when testing.

  • backend (Callable | None) – A function used to perform the underlying parsing and return a raw parsed state. This defaults to the native cappa parser, but can be changed to the argparse parser at cappa.argparse.backend.

  • color (bool) – Whether to output in color.

  • version (str | cappa.arg.Arg | None) – If a string is supplied, adds a -v/–version flag which returns the given string as the version. If an Arg is supplied, uses the name/short/long/help fields to add a corresponding version argument. Note the name is assumed to be the CLI’s version, e.x. Arg(‘1.2.3’, help=”Prints the version”).

  • help (bool | cappa.arg.Arg) – If True (default to True), adds a -h/–help flag. If an Arg is supplied, uses the short/long/help fields to add a corresponding help argument.

  • completion (bool | cappa.arg.Arg) – Enables completion when using the cappa backend option. If True (default to True), adds a –completion flag. An Arg can be supplied to customize the argument’s behavior.

  • theme (rich.theme.Theme | None) – Optional rich theme to customized output formatting.

  • output (cappa.output.Output | None) – Optional Output instance. A default Output will constructed if one is not provided. Note the color and theme arguments take precedence over manually constructed Output attributes.

async cappa.invoke_async(obj, *, deps=None, argv=None, backend=None, color=True, version=None, help=True, completion=True, theme=None, output=None)

Parse the command, and invoke the selected command or subcommand.

In the event that a subcommand is selected, only the selected subcommand function is invoked.

Parameters:
  • obj (type | cappa.command.Command) – A class which can represent a CLI command chain.

  • deps (Sequence[Callable] | Mapping[Callable, cappa.invoke.Dep | Any] | None) – Optional extra depdnencies to load ahead of invoke processing. These deps are evaluated in order and unconditionally.

  • argv (list[str] | None) – Defaults to the process argv. This command is generally only necessary when testing.

  • backend (Callable | None) – A function used to perform the underlying parsing and return a raw parsed state. This defaults to the native cappa parser, but can be changed to the argparse parser at cappa.argparse.backend.

  • color (bool) – Whether to output in color.

  • version (str | cappa.arg.Arg | None) – If a string is supplied, adds a -v/–version flag which returns the given string as the version. If an Arg is supplied, uses the name/short/long/help fields to add a corresponding version argument. Note the name is assumed to be the CLI’s version, e.x. Arg(‘1.2.3’, help=”Prints the version”).

  • help (bool | cappa.arg.Arg) – If True (default to True), adds a -h/–help flag. If an Arg is supplied, uses the short/long/help fields to add a corresponding help argument.

  • completion (bool | cappa.arg.Arg) – Enables completion when using the cappa backend option. If True (default to True), adds a –completion flag. An Arg can be supplied to customize the argument’s behavior.

  • theme (rich.theme.Theme | None) – Optional rich theme to customized output formatting.

  • output (cappa.output.Output | None) – Optional Output instance. A default Output will constructed if one is not provided. Note the color and theme arguments take precedence over manually constructed Output attributes.

cappa.parse(obj, *, argv=None, backend=None, color=True, version=None, help=True, completion=True, theme=None, output=None)

Parse the command, returning an instance of obj.

In the event that a subcommand is selected, only the selected subcommand function is invoked.

Parameters:
  • obj (type[T] | cappa.command.Command[T]) – A class which can represent a CLI command chain.

  • argv (list[str] | None) – Defaults to the process argv. This command is generally only necessary when testing.

  • backend (Callable | None) – A function used to perform the underlying parsing and return a raw parsed state. This defaults to the native cappa parser, but can be changed to the argparse parser at cappa.argparse.backend.

  • color (bool) – Whether to output in color.

  • version (str | cappa.arg.Arg | None) – If a string is supplied, adds a -v/–version flag which returns the given string as the version. If an Arg is supplied, uses the name/short/long/help fields to add a corresponding version argument. Note the name is assumed to be the CLI’s version, e.x. Arg(‘1.2.3’, help=”Prints the version”).

  • help (bool | cappa.arg.Arg) – If True (default to True), adds a -h/–help flag. If an Arg is supplied, uses the short/long/help fields to add a corresponding help argument.

  • completion (bool | cappa.arg.Arg) – Enables completion when using the cappa backend option. If True (default to True), adds a –completion flag. An Arg can be supplied to customize the argument’s behavior.

  • theme (rich.theme.Theme | None) – Optional rich theme to customized output formatting.

  • output (cappa.output.Output | None) – Optional Output instance. A default Output will constructed if one is not provided. Note the color and theme arguments take precedence over manually constructed Output attributes.

Return type:

T

class cappa.testing.CommandRunner

Object to hold common parse/invoke invocation state, for testing.

Accepts almost identical inputs to that of parse/invoke. The notable deviation is argv.

Whereas the original functions accept argv as a single-argument list; CommandRunner accepts base_args at the class-constructor level, which is concatenated with the CommandRunner.parse or CommandRunner.invoke *args, to arrive a the total set of input args.

Example

Some base CLI object

>>> from dataclasses import dataclass
>>>
>>> import cappa
>>>
>>> @dataclass
... class Obj:
...     first: str
...     second: str = '2'

Create an instance with no arguments means there is no default state

>>> runner = CommandRunner()
>>> runner.parse('one', obj=Obj)
Obj(first='one', second='2')

Or create a runner that always uses the same base CLI object, and default base command

>>> runner = CommandRunner(Obj, base_args=['first'])

Now each test, can customize the behavior to suit the test in question.

>>> runner.parse(color=False)
Obj(first='first', second='2')
>>> runner.parse('two')
Obj(first='first', second='two')
backend
base_args
coalesce_args(*args, **kwargs)
Parameters:
Return type:

dict

color = True
completion = True
deps
help = True
invoke(*args, **kwargs)
Parameters:
async invoke_async(*args, **kwargs)
Parameters:
obj
output
parse(*args, **kwargs)
Parameters:
version
class cappa.testing.RunnerArgs

Available kwargs for parse and invoke function, to match CommandRunner fields.

backend
color
completion
deps
help
obj
output
version
class cappa.parser.RawOption
end = False
classmethod from_str(arg)
Parameters:

arg (str)

Return type:

RawOption

is_long
name
value
class cappa.parser.Value

Abstract base class for generic types.

A generic type is typically declared by inheriting from this class parameterized with one or more type variables. For example, a generic mapping type might be defined as:

class Mapping(Generic[KT, VT]):
    def __getitem__(self, key: KT) -> VT:
        ...
    # Etc.

This class can then be used as follows:

def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
    try:
        return mapping[key]
    except KeyError:
        return default
value