Click Option Group
click-option-group is a Click-extension package that provides the functionality for creating option groups in Click-based command-line interfaces. It allows for logical structuring of CLI options and defining specific behaviors and relationships among grouped options, such as mutually exclusive or required option sets. The package is actively maintained, with its current version being 0.5.9, and receives regular updates.
Warnings
- breaking As of v0.5.2, all arguments to the `optgroup` decorator, except for `name`, must be passed as keyword-only arguments. Positional arguments for `cls`, `help`, or `attrs` will raise an error.
- gotcha Mixing `optgroup.option()` and `click.option()` decorators on the same command is not supported and will raise an exception. All options intended to be part of an `optgroup` must use `optgroup.option()`.
- compatibility Version `0.5.3` specifically bumped the Click dependency to `<9`, indicating potential incompatibility with Click 9.x and later. Users on Click 9.x may encounter issues.
- gotcha The `optgroup` decorator does not support `click.argument()` directly. Arguments must be handled separately outside of an option group.
- gotcha Calling `optgroup.option()` without a preceding `optgroup.group()` (or `optgroup()`) declaration for the current command will result in an exception.
Install
-
pip install click-option-group
Imports
- optgroup
from click_option_group import optgroup
- RequiredAnyOptionGroup
from click_option_group import RequiredAnyOptionGroup
- AllOptionGroup
from click_option_group import AllOptionGroup
- RequiredAllOptionGroup
from click_option_group import RequiredAllOptionGroup
- MutuallyExclusiveOptionGroup
from click_option_group import MutuallyExclusiveOptionGroup
- RequiredMutuallyExclusiveOptionGroup
from click_option_group import RequiredMutuallyExclusiveOptionGroup
Quickstart
import click
from click_option_group import optgroup, RequiredMutuallyExclusiveOptionGroup
@click.command()
@optgroup.group('Server configuration', help='The configuration of some server connection')
@optgroup.option('-h', '--host', default='localhost', help='Server host name')
@optgroup.option('-p', '--port', type=int, default=8888, help='Server port')
@optgroup.option('-n', '--attempts', type=int, default=3, help='The number of connection attempts')
@optgroup.option('-t', '--timeout', type=int, default=5, help='The server response timeout')
@optgroup.group('Input data sources', cls=RequiredMutuallyExclusiveOptionGroup, help='The sources of the input data')
@optgroup.option('--tsv-file', type=click.Path(), help='CSV/TSV input data file')
@optgroup.option('--json-file', type=click.Path(), help='JSON input data file')
@click.option('--debug/--no-debug', default=False, help='Debug flag')
def cli(**params):
click.echo(f"Running with parameters: {params}")
if __name__ == '__main__':
cli()