Search code examples
pythoncommand-line-interfacepython-click

How to tell Click to always show option defaults


In Python's Click package I can define a default for an option:

@click.option("--count", default=1, help="Number of greetings.")

and I can specify that the default should be shown in the help:

@click.option("--count", default=1, help="Number of greetings.", show_default=True)

If I have many options

@click.option("--count-a", default=1, help="...")
@click.option("--count-b", default=2, help="...")
@click.option("--count-c", default=4, help="...")
.
.
.

how can I tell Click generically to always show defaults in the help (without explicitly adding show_default=True to the parameter list of each individual option)?


Solution

  • The probably most suited way to do that is by changing the context settings in the @click.command decorator. Like this:

    @click.command("cli", context_settings={'show_default': True})
    @click.option("-x")
    @click.option("-y", default="Custom Y")
    @click.option("-z", default="Custom Z", help="Value of Z.")
    def cli(x, y, z):
        """Test changing context settings"""
        return "OK"
    
    if __name__ == '__main__':
        cli()
    

    This prints the following:

    Usage: test.py [OPTIONS]
    
      Test changing context settings
    
    Options:
      -x TEXT
      -y TEXT  [default: Custom Y]
      -z TEXT  Value of Z.  [default: Custom Z]
      --help   Show this message and exit.