python click: determine whether argument comes from default or from user
Asked Answered
B

1

5

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?

Batha answered 20/2, 2023 at 17:39 Comment(0)
R
6

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
Richter answered 21/2, 2023 at 17:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.