Skip to content

Arger

Function

A function's signature is used to generate parser arguments.

1. Positional Arguments:

Positional parameters become mandatory arguments.

2. Optional Arguments:

All keyword arguments (those with a default value) in the function become flags/optionals.

3. Type Annotations:

They are used to determine the type and action of the arguments. The function will be dispatched with values converted to their respective types. Note: Use the arger.Argument class as an annotation if you want to pass values to parser.add_argument.

For example:

from argparse import Action
from enum import Enum
from typing import Annotated, Literal

import arger

# The following function parameters are added to the parser using type hints.
# All positional parameters are converted to arguments,
# while the keyword arguments become flags.


class Num(Enum):
    ONE = 1
    TWO = 2


class ActionSubCls(Action):
    """Custom action."""

    def __call__(self, parser, namespace, value, option_string=None):
        setattr(namespace, self.dest, value)


def function(
    # -> add_argument(dest='a', type=str)
    a_st: str,
    # -> add_argument(dest='a', type=int)
    a_in: int,
    # : One or more
    # -> add_argument(dest='a', type=int, nargs='+')
    a_tp: tuple[int, ...],
    # : Consumes 2 positional arguments
    # -> add_argument(dest='a', type=int, nargs='2')
    a_tp_int: tuple[int, int],
    # : Zero or more
    # -> add_argument(dest="a", type=int, nargs="*")
    a_ls: list[int],
    # : Zero or one positional
    # -> add_argument(dest="a", type=int, nargs="?")
    a_opt: int | None,
    # : Accepts a str from the CLI and returns it as an Enum.
    # -> add_argument(dest="a", choices=list(Num), type=lambda x: Num[x])
    a_en: Num,
    # : Accepts a str from the CLI and returns the same
    # -> add_argument(dest="a_lt", choices=["one", "two"], type=str)
    a_lt: Literal["one", "two"],
    # : Custom arguments to the `Argument` can be delegated with `Annotated`
    # -> add_argument(dest="a", metavar="INT", type=int, action=ActionSubCls)
    a_cs: Annotated[
        int,
        arger.Argument(metavar="INT", action=ActionSubCls),
    ],
    # Any optionals are converted to flags with default values.
    # -> add_argument("--kwarg", "-k", dest="kwarg", type=int, default=0)
    kwarg: int = 0,
): ...

4. Docstring (ReST or GoogleDoc)

  • The top part of the docstring becomes the usage message for the command.
  • Parameter docstrings become help messages for the arguments/options of the command.
  • The rest of the docstring is passed as epilog to the parser.
  • ReST/GoogleDoc/NumpyDoc formats are supported.
  • Custom flags can be defined in the docstring itself.
Args:
    name: [short option and/or long option] help text
    variable_name: -v --verbose the help_text for the variable
    variable_name: -v the help_text no long option
    variable_name: --verbose the help_text no short option