pythonpython-click

How do I know if flag was passed by the user or has default value?


Sample code:

import click

@click.command
@click.option('-f/-F', 'var', default=True)
def main(var):
    click.echo(var)

main()

Inside main() function, how can I check if var parameter got True value by default, or it was passed by the user?

What I want to achieve: I will have few flags. When the user does not pass any of the flags, I want them all to be True. When the user passes at least one of the flags, only the passed flags should be True, the other flags False.


Solution

  • As I haven't really used click - maybe there's some functionality to handle this but as a workaround, I'd set the default value to None and check against if the value if its None when command is called. Something like this:

    import click
    
    @click.command
    @click.option('-f/-F', 'var', default=None)
    def main(var):
        if var is None:
           var = True
           print("No Value Provided - default to True")
        click.echo(var)
    
    main()