Introduction

argparseDecorator is a tool to ease working with the Python argparse library to build custom command line interpreters.

Instead of setting up the ArgumentParser object by hand and then adding all the required arguments the argparseDecorator supplies a custom decorator to mark functions as a command and to generate the ArgumentParser from the function signature.

Here is a simple example of a command that reverses the input:

>>> from argparsedecorator import *
>>> cli = ArgParseDecorator()

>>> @cli.command
... def reverse(word):
...     print(word[::-1])

With this a command can be executed like this

>>> cli.execute("reverse foobar")
raboof

argparseDecorator makes heavy use (and propably misuse) of type annotations to pass additional information to the ArgumentParser. For example the following command will add up a list of numbers or, if --squared is added to the command, will calculate the sum of the squares.

@cli.command
def add(values: OneOrMore[float], squared: Option = False) -> None:
    if squared:
        values = [x*x for x in values]
    print sum(values)

annotations.OneOrMore [float]’ tells the decorator, that values must have at least one value and that it is accepting only valid numbers (int or float).

Option = False marks squared as an option (starting with --) and that it has the the value True if set on the command line or False (the default) otherwise.

The add command can now be used like this

>>> cli.execute("add 1 2 3 4")
10

>>> cli.execute("add --squared 1 2 3 4")
30

Take a look at the annotations API for all supported annotations and more examples.

The argparseDecorator also uses the docstring of a decorated function to get a description of the command that is used for help and some additional meta information about arguments that can not be easily written as annotations.

@cli.command
def add(values: OneOrMore[float], squared: Option = False) -> None:
    """
    Add up a list of numbers.
    :param values: one or more numbers
    :param squared: when present square each number first
    :alias squared: -sq
    """
    if squared:
        values = [x*x for x in values]
    print sum(values)

Now the help command, which is supplied by the argparseDecorator, will output the following information:

>>> cli.execute("help add")
usage:  add [--squared] values [values ...]

Add up a list of numbers.

positional arguments:
  values          one or more numbers

optional arguments:
  --squared, -sq  when present square each number first

See Using the argparseDecorator for more details and examples.