Python Click - Prompt and Callback not working together for click.option

45 views Asked by At

I'm building a CLI application using the Python Click library. I want to prompt the user for certain options if they are left blank. Other options might be required based on values provided for previous options. To handle this logic, I added a callback function to some parameters, but I noticed that when an option has prompt=True and callback=callback_function, the option value is always None.

For example:

import click


def callback_fn(ctx, param, value):
    print(value)


@click.command()
@click.option(
    "--option_a",
    default="",
    required=False,
    callback=callback_fn,
    prompt=True,
)
def run(option_a):
    print(f"Option A: {option_a}")


if __name__ == "__main__":
    run()

When I run the application with no options passed, it prompts me for a value for option_a:

Option a []:

and I enter

something

The program then finishes with output:

Option a []: something
Callback: something
Callback: None
Option A: None

It seems the callback is called twice, the first time with the correct value, and the second time with "None". When it gets into the actual program, the second value has overridden the first.

It works as expected if I remove the callback.

If I set required=True, the program fails with

Error: Missing option '--option_a'.

Is this expected behavior? Does anyone know how I can get it to work how I want it to?

0

There are 0 answers