Step 2: Reuse defaults, short flags

Step 2: Reuse defaults, short flags

In this step:

  • We reused the float_parser float parser instead of defining our own.

  • We added short versions of the command-line flags, -x and -y. Each parameter can correspond to a short flag (should be composed of an hyphen following by a single letter or digit) and/or a long flag (should start with two hyphens, following by a lower-case name in kebab case. By default, short_flag_name is not set (i.e. is None), and long_flag_name is set to configpile.arg.Derived.KEBAB_CASE, which means it is derived from the field name.

Code

"""
Calculator tutorial, step 2
"""
from dataclasses import dataclass

from typing_extensions import Annotated

from configpile import Config, Param, parsers


@dataclass(frozen=True)
class Calc(Config):
    """
    Command-line tool that sums two floating point numbers
    """

    #: First argument
    x: Annotated[float, Param.store(parsers.float_parser, short_flag_name="-x")]

    #: Second argument
    y: Annotated[float, Param.store(parsers.float_parser, short_flag_name="-y")]


c = Calc.from_command_line_()
print(f"{c.x} + {c.y} = {c.x+c.y}")

Executions

$ python ../../examples/calculator2.py --help
usage: ../../examples/calculator2.py [-x X] [-y Y]

Command-line tool that sums two floating point numbers

required arguments:
  -x X, --x X  First argument
  -y Y, --y Y  Second argument
$ python ../../examples/calculator2.py -x 1 -y 2
1.0 + 2.0 = 3.0