Skip to main content

click-option-group

PyPI version Build status Coverage Status Supported Python versions License

click-option-group is a Click-extension package that adds option groups missing in Click.

Aim and Motivation

Click is a package for creating powerful and beautiful command line interfaces (CLI) in Python, but it has no the functionality for creating option groups.

Option groups are convenient mechanism for logical structuring CLI, also it allows you to set the specific behavior and set the relationship among grouped options (mutually exclusive options for example). Moreover, argparse stdlib package contains this functionality out of the box.

At the same time, many Click users need this functionality. You can read interesting discussions about it in the following issues:

The aim of this package is to provide group options with extensible functionality using canonical and clean API (Click-like API as far as possible).

Quickstart

Installing

Install and update using pip:

$ pip install click-option-group

A Simple Example

Here is a simple example how to use option groups in your Click-based CLI. Just use optgroup for declaring option groups by decorating your command function in Click-like API style.

# app.py

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=30, 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.File(), help='CSV/TSV input data file')
@optgroup.option('--json-file', type=click.File(), help='JSON input data file')
@click.option('--debug/--no-debug', default=False, help='Debug flag')
def cli(**params):
    print(params)

if __name__ == '__main__':
    cli()
$ python app.py --help
Usage: app.py [OPTIONS]

Options:
  Server configuration:           The configuration of some server connection
    -h, --host TEXT               Server host name
    -p, --port INTEGER            Server port
    -n, --attempts INTEGER        The number of connection attempts
    -t, --timeout INTEGER         The server response timeout
  Input data sources: [mutually_exclusive, required]
                                  The sources of the input data
    --tsv-file FILENAME           CSV/TSV input data file
    --json-file FILENAME          JSON input data file
  --debug / --no-debug            Debug flag
  --help                          Show this message and exit.

How It Works

Firstly, we declare the group:

@optgroup.group('Server configuration', help='The configuration of some server connection')

Also we can declare groups just using optgroup():

@optgroup('Server configuration', help='The configuration of some server connection')

Secondly, we declare the grouped options below:

@optgroup.option('-h', '--host', default='localhost', help='Server host name')
@optgroup.option('-p', '--port', type=int, default=8888, help='Server port')

Checking Declarations

The important point: do not mix optgroup.option and click.option decorators!

click-option-group checks the decorators order and raises the exception if optgroup.option and click.option are mixed.

The following code is incorrect:

@optgroup.group('My group')
@click.option('--hello')  # ERROR
@optgroup.option('--foo')
@click.option('--spam')  # ERROR
@optgroup.option('--bar')

The correct code looks like:

@click.option('--hello')
@optgroup.group('My group')
@optgroup.option('--foo')
@optgroup.option('--bar')
@click.option('--spam')

If we try to use optgroup.option without optgroup.grpup()/optgroup() declaration it also will raise the exception.

The following code is incorrect:

@click.command()
@click.option('--hello')
@optgroup.option('--foo')  # ERROR: Missing declaration of the option group
@optgroup.option('--bar')  # ERROR: Missing declaration of the option group
@click.option('--spam')
def cli(**params):
    pass

If we declare only option group without the options it will raise warning.

@click.command()
@click.option('--hello')
@optgroup.group('My group')  # WARN: The empty option group
@click.option('--spam')
def cli(**params):
    pass

API Features

Besides optgroup based decorators the package offers another way to declare grouped options using OptionGroup based class objects directly. We can use the instances of these classes and use its option method as decorator for declaring and adding options to the group.

Here is an example how it looks:

import click
from click_option_group import OptionGroup, MutuallyExclusiveOptionGroup

server_config = OptionGroup('Server configuration', help='The configuration of some server connection')
input_sources = MutuallyExclusiveOptionGroup('Input data sources', required=True, help='The sources of the input data')

@click.command()
@server_config.option('-h', '--host', default='localhost', help='Server host name')
@server_config.option('-p', '--port', type=int, default=8888, help='Server port')
@input_sources.option('--tsv-file', type=click.File(), help='CSV/TSV input data file')
@input_sources.option('--json-file', type=click.File(), help='JSON input data file')
@click.option('--debug/--no-debug', default=False, help='Debug flag')
def cli(**params):
    print(params)

if __name__ == '__main__':
    cli()

In this case initially we create group objects and then we use option method for declaring options.

As well as in above example we cannot mix option and click.option decorators. The following code is incorrect and will raise the exception:

@server_config.option('-h', '--host', default='localhost', help='Server host name')
@click.option('--foo')  # ERROR
@server_config.option('-p', '--port', type=int, default=8888, help='Server port')
@input_sources.option('--tsv-file', type=click.File(), help='CSV/TSV input data file')
@click.option('--bar')  # ERROR
@input_sources.option('--json-file', type=click.File(), help='JSON input data file')

Behavior and Relationship among Options

The groups are useful to define the specific behavior and relationship among grouped options.

click-option-groups offers two main classes: OptionGroup and GroupedOption.

OptionGroup and GroupedOption classes contain the main functionality for support option groups. They do not contain the specific behavior or relationship among grouped options.

The specific behavior can be implemented by using the inheritance, mainly, in OptionGroup sub classes. click-option-groups offers some useful OptionGroup based classes out of the box:

  • RequiredAnyOptionGroup -- At least one option from the group must be set.
  • RequiredAllOptionGroup -- All options from the group must be set.
  • MutuallyExclusiveOptionGroup -- Only one or none option from the group must be set
  • RequiredMutuallyExclusiveOptionGroup -- Only one required option from the group must be set

OptionGroup based class can be specified via cls argument in optgroup()/optgroup.group() decorator or can be used directly when the second method is used.

If you want to implement some complex behavior you can create a sub class of GroupedOption class and use your GroupedOption based class via cls argument in optgroup.option/OptionGroup.option decorator method.

Limitations

The package does not support nested option groups. This is intentional. Nested option groups complicate the implementation, API and CLI and most often it is not necessary.

Metadata

Release files for click-option-group 0.2.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for click-option-group 0.2.2
File Size Uploaded
click-option-group-0.2.2.tar.gz 10.5 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for click-option-group 0.2.2
File Interpreter ABI Platform
click_option_group-0.2.2-py3-none-any.whl Python 3 none any Details

Total release size: 22.0 kB

Release files / click-option-group-0.2.2.tar.gz

Download URL click-option-group-0.2.2.tar.gz
Size 10.5 kB
Tags Source
SHA-256 checksum
How to use checksums
b667259e962edc397c8d0c35852c85e3891b4baa51f25f473b0be9127cc1b50e
BLAKE2b-256 checksum
How to use checksums
a9878784597feeb12ee9f0a4baec231c72d977f9aa615989430f0a60d1713776
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.1.1 pkginfo/1.5.0.1 requests/2.22.0 setuptools/40.8.0 requests-toolbelt/0.9.1 tqdm/4.40.0 CPython/3.6.6

Release files / click_option_group-0.2.2-py3-none-any.whl

Download URL click_option_group-0.2.2-py3-none-any.whl
Size 11.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d13beee55ee73161b5d8811b75c55665128f0d82f2c8381dd144161945955238
BLAKE2b-256 checksum
How to use checksums
8e04e77a40f0f2605fd7c5e46e5f8c96eb1b118b670a845b9c56bf3705a27e3c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.1.1 pkginfo/1.5.0.1 requests/2.22.0 setuptools/40.8.0 requests-toolbelt/0.9.1 tqdm/4.40.0 CPython/3.6.6

Release history Release notifications | RSS feed

0.5.9

2 release files

0.5.8

2 release files

0.5.7

2 release files

0.5.6

2 release files

0.5.5

2 release files

0.5.4

2 release files

0.5.3

2 release files

0.5.2

2 release files

0.5.1

2 release files

0.5.0

2 release files

0.4.0

2 release files

0.3.1

2 release files

0.3.0

2 release files

0.2.3

2 release files

This release

0.2.2 This release

2 release files

0.2.1

2 release files

0.2.0

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page