halloleo
halloleo

Reputation: 10384

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)?

Upvotes: 16

Views: 6051

Answers (2)

jch
jch

Reputation: 296

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. 

Upvotes: 28

Stephen Rauch
Stephen Rauch

Reputation: 49794

You can pretty easily define your own function for that like:

Code

def click_option(*args, **kwargs):
    return click.option(*args, show_default=True, **kwargs)

Or if you want to override show_default in individual option decorators:

def click_option(*args, **kwargs):
    if not 'show_default' in kwargs:
        kwargs.update({'show_default': True})
    return click.option(*args, **kwargs)

Test Code:

import click

def click_option(*args, **kwargs):
    if not 'show_default' in kwargs:
        kwargs.update({'show_default': True})
    return click.option(*args, **kwargs)

@click.command()
@click_option('--an-option', default='The Default')
def cli(an_option):
    """An Awesome CLI"""

if __name__ == "__main__":
    cli(['--help'])

Results:

Usage: test.py [OPTIONS]

  An Awesome CLI

Options:
  --an-option TEXT  [default: The Default]
  --help            Show this message and exit.

Upvotes: 3

Related Questions