Skip to content

argparse

add_model(parser, model)

Add a pydantic model to an argparse ArgumentParser.

Parameters:

Name Type Description Default
parser ArgumentParser

The ArgumentParser instance.

required
model type[BaseModel]

The pydantic model declaring the cli options.

required
Source code in m/cli/engine/argparse.py
def add_model(
    parser: argparse.ArgumentParser,
    model: type[BaseModel],
) -> None:
    """Add a pydantic model to an argparse ArgumentParser.

    Args:
        parser: The ArgumentParser instance.
        model: The pydantic model declaring the cli options.
    """
    parser.description = cleandoc(model.__doc__ or '')
    parser.formatter_class = argparse.RawTextHelpFormatter
    for name, field in model.model_fields.items():
        arg_inputs = _parse_field(name, field)
        parser.add_argument(*arg_inputs.args, **arg_inputs.kwargs)

command(*, help, model, name=None)

Apply a decorator to the run function to make it into a command.

Parameters:

Name Type Description Default
name str | None

The command name.

None
help str

A short description of the command.

required
model type[BaseModel]

A pydantic model to describe the cli arguments.

required

Returns:

Type Description
partial[partial[int]]

A transformed run function aware of the arguments model.

Source code in m/cli/engine/argparse.py
def command(
    *,
    help: str,  # noqa: WPS125
    model: type[BaseModel],
    name: str | None = None,
) -> partial[partial[int]]:
    """Apply a decorator to the `run` function to make it into a command.

    Args:
        name: The command name.
        help: A short description of the command.
        model: A pydantic model to describe the cli arguments.

    Returns:
        A transformed run function aware of the arguments model.
    """
    # m no longer uses the name argument but we keep it for now
    if name:  # pragma: no cover
        warn('`name` is no longer needed, please remove it', DeprecationWarning)
    return partial(_handle_decorated_func, CommandInputs(help, model))