Manage a configuration with validation and command line options#

In this tutorial, we show how to:

  • describe the options of a tool in specifications that give their types and defaults,

  • load and validate a user configuration, with values like lists of floats,

  • add your own validation function,

  • let the command line options override the user configuration and the defaults,

  • export the specifications to the documentation.

This is the xoa.cfgm module, which extends configobj, and that xoa uses for its own options and its naming specifications. The concepts are explained in the Config management with xoa.cfgm guide. See also: Write your own naming specifications.

Initialisations#

import pathlib
import tempfile
from argparse import ArgumentParser
from pprint import pprint

import numpy as np
from validate import VdtTypeError

from xoa import cfgm

The specifications#

They are written as lines of a configuration file: the sections are in brackets, and each option has a validation function, its parameters and a comment that serves as a help. The floats function is the plural form of float: it validates a list of floats, here with n=2 values. In a library, the specifications are typically in a static file that sits next to the module.

specs = """
[logger] # logging system
level=option(debug,info,error,default=info) # logging level
name=string(default=root) # logger name
[domain]
xlim=floats(n=2, default=list(-20,0)) # min and max longitudes
ylim=floats(n=2, default=list(40,50)) # min and max latitudes
[plot]
figsize=figsize(default=list(6,4)) # figure size in inches
"""
CFGM = cfgm.ConfigManager(specs.strip().splitlines())
pprint(CFGM.defaults.dict())
{'domain': {'xlim': [-20.0, 0.0], 'ylim': [40.0, 50.0]},
 'logger': {'level': 'info', 'name': 'root'},
 'plot': {'figsize': (6.0, 4.0)}}

Load and validate a configuration#

The user configuration only holds what differs from the defaults. It is validated, which converts the strings, and completed with the defaults.

user_lines = ["[logger]", "name=xoa", "[domain]", "xlim=-10,0"]
cfg = CFGM.load(user_lines)
pprint(cfg.dict())
{'domain': {'xlim': [-10.0, 0.0], 'ylim': [40.0, 50.0]},
 'logger': {'level': 'info', 'name': 'xoa'},
 'plot': {'figsize': (6.0, 4.0)}}

A value that is not acceptable raises an explicit error.

try:
    CFGM.load(["[logger]", "level=verbose"])
except cfgm.XoaValidateError as exc:
    print(exc)
Config value error: [logger] level: the value "verbose" is unacceptable.

Add a validation function#

The available functions are listed with xoa.cfgm.print_validation_functions(), which accepts a pattern.

figsize(value, default=(6, 6), min=0, max=20)
    Validation function of a figure size (xsize,ysize)
figsize_list(value, default=(6, 6), min=0, max=20)
    Validation function of a figure size (xsize,ysize)
figsizes(value, default=(6, 6), min=0, max=20)
    Validation function of a figure size (xsize,ysize)

A new function is registered with xoa.cfgm.register_validation_functions(). Here it converts an angle to degrees within [0, 360), or to radians.

def is_angle(value, radians=False):
    """Validate an angle with optional conversion to radians"""
    try:
        value = float(value) % 360.0
    except Exception:
        raise VdtTypeError("Invalid angle")
    return float(np.radians(value)) if radians else value


cfgm.register_validation_functions(angle=is_angle)
print(cfgm.get_validator().check("angle(radians=True)", 180 + 360))
3.141592653589793

The command line#

The arg_parse() method adds one option to a parser for each option of the specifications, like --logger-level. The command line takes precedence over the user configuration, which takes precedence over the defaults. Here the command line sets the level, the file sets the name, and the defaults give the rest.

cfgfile = pathlib.Path(tempfile.mkdtemp()) / "config.cfg"
cfgfile.write_text("\n".join(user_lines))

parser = ArgumentParser(description="My script")
parser.add_argument("ncfile", help="netcdf file")
cfg, args = CFGM.arg_parse(
    parser=parser,
    getargs=True,
    args=["--logger-level", "error", "myfile.nc"],
    cfgfile=str(cfgfile),
)
print(args.ncfile)
pprint(cfg.dict())
myfile.nc
{'domain': {'xlim': [-10.0, 0.0], 'ylim': [40.0, 50.0]},
 'logger': {'level': 'error', 'name': 'xoa'},
 'plot': {'figsize': (6.0, 4.0)}}

The parser knows the options, grouped by section, and has also a --long-help and a --short-help options in addition to --help.

usage: python /home/docs/checkouts/xoa/checkouts/develop/tutorials/config/plot_cfgm.py
       [-h] [--long-help] [--short-help] [--cfgfile CFGFILE]
       [--logger-level LOGGER_LEVEL] [--logger-name LOGGER_NAME]
       [--domain-xlim DOMAIN_XLIM] [--domain-ylim DOMAIN_YLIM]
       [--plot-figsize PLOT_FIGSIZE]
       ncfile

My script

positional arguments:
  ncfile                netcdf file

options:
  -h, --help            show a reduced help and exit
  --long-help           show an extended help and exit
  --short-help          show a very reduced help and exit
  --cfgfile CFGFILE     user configuration file that overrides defaults

logger:
  logging system

  --logger-level LOGGER_LEVEL
                        logging level. [default: info]
  --logger-name LOGGER_NAME
                        logger name. [default: root]

domain:
  --domain-xlim DOMAIN_XLIM
                        min and max longitudes. [default: -20.0,0.0]
  --domain-ylim DOMAIN_YLIM
                        min and max latitudes. [default: 40.0,50.0]

plot:
  --plot-figsize PLOT_FIGSIZE
                        figure size in inches. [default: 6.0,4.0]

Document the options#

The specifications are exported as Sphinx declarations of sections and options, to build the documentation of the options of a tool, like Configuration does for xoa. The xoa.cfgm module is also a Sphinx extension that does it at build time, see the Config management with xoa.cfgm guide.

print(CFGM.to_rst())
.. confsec:: [logger]

    Logging system

    .. confopt:: [logger] level

        | default: ``info``
        | possible choices: ``debug, info, error``

        Logging level

    .. confopt:: [logger] name

        | default: ``root``
        | type: :func:`string <configobj.validate.is_string>`

        Logger name

.. confsec:: [domain]



    .. confopt:: [domain] xlim

        | default: ``-20, 0``
        | type: :func:`floats <configobj.validate.is_float>`
        | n: ``2``

        Min and max longitudes

    .. confopt:: [domain] ylim

        | default: ``40, 50``
        | type: :func:`floats <configobj.validate.is_float>`
        | n: ``2``

        Min and max latitudes

.. confsec:: [plot]



    .. confopt:: [plot] figsize

        | default: ``6, 4``
        | type: :func:`figsize <xoa.cfgm.is_figsize>`

        Figure size in inches

Total running time of the script: (0 minutes 0.009 seconds)

Gallery generated by Sphinx-Gallery