Python Click - Retrieve options using params regardless of order execution during callback

Viewed 22

I'm having some trouble with my callback function. In the rest of the foo function, I use both the foo and type variable, but am unable to retrieve the type variable since the order of execution matters as shown below. Is there any way to disregard the order of execution, or is there a different way to go about it?

Click option

@click.option('-f', '--foo', callback=validate_foo)
@click.option('-t', '--type')
def validate_foo(ctx, param, foo):
     type = ctx.params.get('type')
     click.echo(f'type: {type}')

Output:

python test.py -t typetest -f footest command
type: typetest

python test.py -f footest -t typetest command
type: None

Thank you!

1 Answers

What you need is an eager param.

From the documentation:

An eager parameter is a parameter that is handled before others

So this way, you will force the type param to be parsed before everything else and it won't matter if it was physically written infront or after your foo param.

Here is a little working example:

import click
    
    
def validate_foo(ctx, param, value):
    type = ctx.params.get('type')
    click.echo(f'type: {type}')
    return value


@click.command()
@click.option('-f', '--foo', callback=validate_foo)
@click.option('-t', '--type', is_eager=True)
def test(foo, type):
    print(foo)
    print(type)
Related