Manual Construction

The general intention of the library is that you use the inference system to produce the most natural mapping between the source class definition and the output CLI.

However, there’s nothing preventing the manual construction of the command definition, which allows one to completely decouple the CLI-specific annotations from the class in question, if much more manually.

from dataclasses import dataclass

import cappa
from cappa.annotation import parse_list


@dataclass
class Foo:
    bar: str
    baz: list[int]


command = cappa.Command(
    Foo,
    arguments=[
        cappa.Arg(field_name="bar", parse=str),
        cappa.Arg(field_name="baz", parse=parse_list(int), num_args=-1),
    ],
    help="Short help.",
    description="Long description.",
)


result = cappa.parse(command, argv=["one", "2", "3"])
# result == Foo(bar="one", baz=[2, 3])

There are a number of built-in parser functions used to build up the existing inference system. parse_value the the main entrypoint used by cappa internally, but each of the parser factory functions below make up the component built-in parsers for each type.

For inherent types, like int, float, etc. Their constructor may serve as their own parser.

cappa.annotation.parse_list(of_type)

Create a value parser for a list of given type of_type.

Parameters:

of_type (type[cappa.typing.T])

Return type:

Callable[[Any], list[cappa.typing.T]]

cappa.annotation.parse_literal(*type_args)

Create a value parser for a given literal value.

Parameters:

type_args (cappa.typing.T)

Return type:

Callable[[Any], cappa.typing.T]

cappa.annotation.parse_none()

Create a value parser for None.

cappa.annotation.parse_set(of_type)

Create a value parser for a list of given type of_type.

Parameters:

of_type (type[cappa.typing.T])

Return type:

Callable[[Any], set[cappa.typing.T]]

cappa.annotation.parse_tuple(*type_args)

Create a value parser for a tuple with type-args of given type_args.

Parameters:

type_args (type)

Return type:

Callable[[Any], tuple]

cappa.annotation.parse_union(*type_args)

Create a value parser for a Union with type-args of given type_args.

Parameters:

type_args (type)

Return type:

Callable[[Any], Any]

cappa.annotation.parse_value(annotation, extra_annotations=())

Create a value parser for the given annotation.

Examples

>>> from typing import List, Literal, Tuple
>>> list_parser = parse_value(List[int])
>>> tuple_parser = parse_value(Tuple[int, ...])
>>> literal_parser = parse_literal(Literal["foo"])
Parameters:
  • annotation (type)

  • extra_annotations (Iterable[type])

Return type:

Callable