Search code examples
pythonpython-click

Type and default input value of a Click.option in --help option


How do I make Click show the default input value of a @click.option() in its help text, so that it gets printed when the program is called with --help?


Solution

  • Pass show_default=True in the click.option decorator when defining an option. This will display default value in the help when the program is called with --help option. For example -

    #hello.py
    import click
    
    @click.command()
    @click.option('--count', default=1, help='Number of greetings.', show_default=True)
    @click.option('--name', prompt='Your name',
                  help='The person to greet.')
    def hello(count, name):
        """<insert text that you want to display in help screen> e.g: Simple program that greets NAME for a total of COUNT times."""
        for x in range(count):
            click.echo('Hello %s!' % name)
    
    if __name__ == '__main__':
        hello()
    

    Now you can see the help screen generated by running python hello.py --help as

    $ python hello.py --help
    Usage: hello.py [OPTIONS]
    
      <insert text that you want to display in help screen> e.g: Simple program that greets NAME for a total of COUNT times.
    
    Options:
      --count INTEGER  Number of greetings.  [default: 1]
      --name TEXT      The person to greet.
      --help           Show this message and exit.
    

    Hence you can see that the default value of the count option is displayed in the help text of the program. (Reference : https://github.com/pallets/click/issues/243)