Skip to main content

Strongly typed tool configuration classes for argument parsing.

Project description

Config Classes (cfgclasses)

CI/CD CI - Test
Package PyPI - Version PyPI - Downloads PyPI - Python Version
Meta code style - Black types - Mypy linting - pylint License - MIT

Strongly typed tool configuration classes for argument parsing.

Config classes are representations of a python tools CLI configuration options built on dataclasses. This allows individual tools to focus on specifying their configuration structure without the overhead of interacting with argparse and the typeless Namespace it returns.

See the documnentation for full user guides and API references.

Installation

pip install cfgclasses

Features

  • Simple class definitions using dataclasses
  • Nested config and tool submodes reduce code repetition
  • Mutually exclusive groups support
  • Validation functions for reliable verification of config
  • Argument transformations reducing repetition of common patterns (e.g. reading contents of a file)

Example Usage

The following shows a simple script setup using a Config class.

import dataclasses
import sys
from cfgclasses import arg, optional, parse_args
from pathlib import Path
from typing import Optional

@dataclasses.dataclass
class Config:
    # Simple options are required on the CLI
    intopt: int = arg("A simple integer field")
    inpath: Path = arg("A required Path field")

    # Optional fields default to None when not specified
    outpath: Optional[Path] = optional("An optional Path field")

    # Can specify custom default or default_factory values
    stropt: str = arg("A string field with a default", default="X")

    # The authors preference is to put run modes on the config classes.
    # This is entirely optional, and main() methods that take in the Config
    # object as their only arg is a perfectly sensible alternative.
    def run(self) -> None:
        """Main entry point of this script."""
        ...

if __name__ == '__main__':
    config = parse_args(Config, sys.argv[1:], prog="example")
    config.run()

The -h output from this script is:

usage: example [-h] --intopt INTOPT --inpath INPATH [--outpath OUTPATH] [--stropt STROPT]

options:
  -h, --help         show this help message and exit

  --intopt INTOPT    A simple integer field
  --inpath INPATH    A required Path field
  --outpath OUTPATH  An optional Path field
  --stropt STROPT    A string field with a default

This same script implemented in argparse would look like this:

import argparse
import sys
from pathlib import Path

def _parse_args(argv: list[str]):
    parser = argparse.ArgumentParser(prog="example")
    # In argparse options default to None unless you specified they're required.
    # Help messages are optional in argparse, but required in cfgclasses.
    parser.add_argument("--intopt", type=int, help="A simple integer field", required=True)
    parser.add_arugment("--inpath", type=Path, help="A required Path field", required=True)

    # Optional fields are the default in argparse, so type is actually Optional[Path]
    parser.add_argument("--outpath", type=Path, help="An optional Path field")

    # Defaults work the same, but there's no default_factory in argparse
    parser.add_argument("--stropt", default=X", help="A string field with a default")

def main(args: argparse.Namespace) -> None:
    """Main entry point of this script."""
    # Note: args here is relatively typeless - if one of the argument types is
    # changed (e.g. from str to Path) mypy will not pick up on this error.
    ...

if __name__ == '__main__':
    args = _parse_args(sys.argv[1:])
    main(args)

For further examples see the examples subdirectory.

License

CFG-Classes is distributed under the terms of the MIT license.

Contribution

See the contribution page.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

cfgclasses-2.4.0.tar.gz (18.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

cfgclasses-2.4.0-py3-none-any.whl (21.7 kB view details)

Uploaded Python 3

File details

Details for the file cfgclasses-2.4.0.tar.gz.

File metadata

  • Download URL: cfgclasses-2.4.0.tar.gz
  • Upload date:
  • Size: 18.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for cfgclasses-2.4.0.tar.gz
Algorithm Hash digest
SHA256 b0fd6ab4b52351bdc7def18d130941f0656dee471d89db49a0c5a26132ddf302
MD5 b7d34410f8803d0e76ac7ef7f14e6e1e
BLAKE2b-256 59d4fe5bde8d1039377815638c3fd3cc44a6aebe4948acd233a5a1afd69520e5

See more details on using hashes here.

File details

Details for the file cfgclasses-2.4.0-py3-none-any.whl.

File metadata

  • Download URL: cfgclasses-2.4.0-py3-none-any.whl
  • Upload date:
  • Size: 21.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for cfgclasses-2.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 b19c3c7e3d3793e1b408cfc6dc8ea18d6459a30fd3fe7060162d1d589f2cfd0b
MD5 37ab4f85039b33afc6bc4a2b547d9992
BLAKE2b-256 bd7b90c99367ba8aaceac65f1501373775df458f228f34f30707a2db2ab5b72c

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page