python click: argument coming from default or user

Question:

How to tell whether an argument in click coming from the user or it’s 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?

Asked By: Osman Mamun

||

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
Answered By: python_user
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.