Skip to content

Click Should Support Mutually Exclusive Options #2252

@saroad2

Description

@saroad2

Description

More often than none you want to add few options to a CMD such that at most one of them can be set with a value. This ability can be achieved by setting a group of mutually exclusive options.

Suggested API

Here's a suggested API for this ability

import click

@click.command()
@click.mutually_exclusive(
    click.option("-a", type=int, help="This is a"),
    click.option("-b", type=str, help="This is b"),
    click.option("-c", is_flag=True, default=False, help="This is c"),
    required=True,
)
def my_command(a, b, c):
    click.echo(f"{a=}, {b=}, {c=}")


if __name__ == "main":
   my_command()

In this example we define three mutually exclusive options: -a, -b and -c. With setting required=True we determine that at least one of them should be set (default is False).

The following should be printed:

>> my-command -a 5
a=5, b=None, c=False
>> my-command -b hello
a=None, b=hello, c=False
>> my-command -c
a=None, b=None, c=True
>> my-command -a 5 -b hello
Error: The following options cannot be both set: "-a", "-b"

Even though this ability has been suggested multiple times over the years (see #257, #509, #1137), it was rejected every time. I do believe that this is something Click users should really benefit from. If you choose to approve this suggestion, I will try to implement it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions