Can I give a click option another name?
Asked Answered
G

1

19

I use click like this:

import click

@click.command(name='foo')
@click.option('--bar', required=True)
def do_something(bar):
    print(bar)

So the name of the option and the name of the function parameter is the same. When it is not the same (e.g. when you want --id instead of --bar), I get:

TypeError: do_something() got an unexpected keyword argument 'id'

I don't want the parameter to be called id because that is a Python function. I don't want the CLI parameter to be called different, because it would be more cumbersome / less intuitive. How can I fix it?

Galloot answered 17/1, 2018 at 9:46 Comment(0)
P
24

You just need to add a non-option (doesn't start with -) argument in the click.option decorator. Click will use this as the name of the parameter to the function. This allows you to use Python keywords as option names.

Here is an example which uses id_ inside the function:

import click

@click.command(name='foo')
@click.option('--id', 'id_', required=True)
def do_something(id_):
    print(id_)

There is an official example here in the --from option.

Pudendum answered 17/1, 2018 at 9:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.