Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python click: determine whether argument comes from default or from user

How to tell whether an argument in click is coming from the user or is the default value?

For example:

import click

@click.command()
@click.option('--value', default=1, help='a value.')
def hello(value):
    print(value)

if __name__ == "__main__":
    hello()

Now if I run python script.py --value 1, the value is now coming from the user input as opposed to the default value (which is set to 1). Is there any way to discern where this value is coming from?

like image 898
Osman Mamun Avatar asked Jul 30 '26 20:07

Osman Mamun


1 Answers

You can use Context.get_parameter_source to get what you want. This returns an enum of 4 possible values (or None if the value does not exist), you can then use them to decide what you want to do.

COMMANDLINE - The value was provided by the command line args.
ENVIRONMENT - The value was provided with an environment variable.
DEFAULT - Used the default specified by the parameter.
DEFAULT_MAP - Used a default provided by :attr:`Context.default_map`.
PROMPT - Used a prompt to confirm a default or provide a value.
import click
from click.core import ParameterSource

@click.command()
@click.option('--value', default=1, help='a value.')
def hello(value):
    parameter_source = click.get_current_context().get_parameter_source('value')

    if parameter_source == ParameterSource.DEFAULT:
        print('default value')

    elif parameter_source == ParameterSource.COMMANDLINE:
        print('from command line')

    # other conditions go here
    print(value)

if __name__ == "__main__":
    hello()

In this case, the value is taken from default and can be seen in the output below.

Output

default value
1
like image 155
python_user Avatar answered Aug 02 '26 11:08

python_user



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!