mlsimkit.common.cli – CLI Framework

The mlsimkit.common.cli module offers a convenient way to create rich command-line interfaces (CLIs) for Python applications with automated options generation and YAML configuration loading. It leverages the power of the Click library and seamlessly integrates with Pydantic models, allowing developers to define and validate command-line options based on their data models.

The key components of this framework include:

  • Command decorators for creating entry points and grouping commands

  • Utilities for converting Pydantic models into Click options

  • Click-compatible parameter types for handling various data types

  • Opinionated custom Click classes for top-level program, commands and sub-command behaviors.

Example:

from pydantic import BaseModel

class MySettings(BaseModel):
    level: int
    mode: bool

import click
import mlsimkit

@mlsimkit.cli.program("tool", version="1.0", use_config_file=True)
@mlsimkit.cli.options(MySettings, dest='settings')
@click.option("--normal-option")
def cli(ctx: click.Context, settings: MySettings):
    click.echo(settings.dict())

if __name__ == "__main__":
    cli()
% python3 mycli.py --help
Usage: mycli.py [OPTIONS] COMMAND [ARGS]...

Options:
  --version             Show the version and exit.
  --level INTEGER       [required]
  --mode / --no-mode    [required]
  --normal-option TEXT
  --help                Show this message and exit.

See options() for more API usage examples or follow the quickstart user guide.

Command Decorators

program

Decorator to turn a function into a program.

group

A parent command for grouping of sub-commands.

options

Decorator to define Click command options using Pydantic schemas.

options_from_schema

Decorator to generate Click options for all fields in a Pydantic model.

options_from_schema_shorthand

Decorator to generate a Click option from a Pydantic model using shorthand notation.

Option Types

NamedEnum

Enum that constructs members based on string names.

ListParamType

A Click parameter that parses a delimited list of values.

ShorthandParamType

Click Parameter type for a Pydantic model that accepts shorthand notation.

ResourcePath

A Click option type that resolves paths from the provided search paths, including paths from importlib.resources.

Command Classes

BaseCommand

A Click command that handles instantiating Pydantic models from flattened CLI params.

BaseGroup

A Click group that handles instantiating Pydantic models from flattened CLI params.