Step 4: Many positional arguments

Step 4: Many positional arguments

Some scripts may get a variable number of values. Here we update our calculator so that it takes an arbitrary number of positional values.

Note that the field type has changed: instead of float, it is now a Sequence[float].

The parameter declaration changed as well: we now use the append1() static method of Param, which works by taking a parser of a given type, here float, to collect the values of a parameter of type Sequence[float].

Code

"""
Calculator tutorial, step 4
"""

from dataclasses import dataclass
from typing import Sequence

from typing_extensions import Annotated

from configpile import Config, Param, Positional, parsers


@dataclass(frozen=True)
class Calc(Config):
    """
    Command-line tool that sums an arbitrary number of floating point values
    """

    #: Values to sum
    values: Annotated[
        Sequence[float],
        Param.append1(
            parsers.float_parser,
            positional=Positional.ZERO_OR_MORE,
            short_flag_name=None,
            long_flag_name=None,
        ),
    ]


c = Calc.from_command_line_()
print(sum(c.values))

Executions

$ python ../../examples/calculator4.py --help
usage: ../../examples/calculator4.py values

Command-line tool that sums an arbitrary number of floating point values

optional arguments:
  values  Values to sum
$ python ../../examples/calculator4.py 1 2 3 4
10.0