pythonpython-click

How does Python Click library handle options that are flags and True by default?


I just stumbled upon a piece of code that defines a click option as such:

@click.option(
    "-s",
    "--status",
    default=True,
    is_flag=True,
    help="Show status",
)

Does this means that the status is True, unless the -s is supplied, in which case it will become False?


Solution

  • For options that are both a flag and defaulted to True, specifying the option on the command line will set that option to False; while not specifying will give the default True.

    Test Code:

    import click    
    
    @click.command()
    @click.option(
        "-s",
        "--status",
        default=True,
        is_flag=True,
        help="Show status",
    )
    def main(status):
        click.echo('status: {}'.format(status))
    
    
    if __name__ == "__main__":
        commands = (
            '',
            '-s',
            '--status',
            '--help',
        )
    
        import sys, time
    
        time.sleep(1)
        print('Click Version: {}'.format(click.__version__))
        print('Python Version: {}'.format(sys.version))
        for command in commands:
            try:
                time.sleep(0.1)
                print('-----------')
                print('> ' + command)
                time.sleep(0.1)
                main(command.split())
    
            except BaseException as exc:
                if str(exc) != '0' and \
                        not isinstance(exc, (click.ClickException, SystemExit)):
                    raise
    

    Results:

    Click Version: 6.7
    Python Version: 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
    -----------
    > 
    status: True
    -----------
    > -s
    status: False
    -----------
    > --status
    status: False
    -----------
    > --help
    Usage: test.py [OPTIONS]
    
    Options:
      -s, --status  Show status
      --help        Show this message and exit.