Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case Insensitive choices in python click

I have a python-click CLI with subcommand test. The option choices in function test accepts V1 or V2 (uppercase).

@click.command(name='test')
@click.option('-c', '--choices', type=click.Choice(['V1', 'V2']), default='V1')
def test(choices):
    print(choices)

If a user accidentally types v1 (lowercase) instead of V1 (uppercase) then I get an error from click library.

Error: Invalid value for "-c" / "--choices": invalid choice: v1. (choose from V1, V2)

How can I have a case insensitive click.Choice implementation so that even if I type v1 (lowercase) I get V1 (uppercase) in the function?

like image 986
Jose Thomas Avatar asked May 05 '26 08:05

Jose Thomas


1 Answers

The Choice option has a case_sensitive boolean parameter that can be used to allow mixed case choice acceptance like:

@click.option('-c', '--choices', type=click.Choice(['V1', 'V2'], case_sensitive=False))

Test Code:

import click

@click.command(name='test')
@click.option('-c', '--choices', type=click.Choice(['V1', 'V2'], case_sensitive=False))
def test(choices):
    click.echo(f'Choices: {choices}')


if __name__ == "__main__":
    commands = (
        '',
        '-c v1',
        '-c V1',
        '-c V2',
        '--help',
    )

    import sys, time
    time.sleep(1)
    print('Click Version: {}'.format(click.__version__))
    print('Python Version: {}'.format(sys.version))
    for cmd in commands:
        try:
            time.sleep(0.1)
            print('-----------')
            print('> ' + cmd)
            time.sleep(0.1)
            test(cmd.split())

        except BaseException as exc:
            if str(exc) != '0' and \
                    not isinstance(exc, (click.ClickException, SystemExit)):
                raise

Test Results:

Click Version: 7.1.2
Python Version: 3.8.10 (tags/v3.8.10:3d8993a, May  3 2021, 11:48:03) [MSC v.1928 64 bit (AMD64)]
-----------
> 
Choices: V1
-----------
> -c v1
Choices: V1
-----------
> -c V1
Choices: V1
-----------
> -c V2
Choices: V2
-----------
> --help
Usage: test_code.py [OPTIONS]

Options:
  -c, --choices [V1|V2]
  --help                 Show this message and exit.
like image 68
Stephen Rauch Avatar answered May 06 '26 22:05

Stephen Rauch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!