10

I'm wondering how to override destination variable for the click.option (Click lib). For example in such piece of code

import click

@click.command()
@click.option('--output', default='data')
def generate_data(output_folder):
    print(output_folder)

So I want to use --output flag but pass its value to output_folder argument, kinda this: @click.option('--output', default='data', dest='output_folder')? Is there is such an ability in click? I know that argparse allow such a behaviour.

1 Answer 1

14

Yes, see the section in the click documentation on parameter names, which covers both options and arguments.

If a parameter is not given a name without dashes, a name is generated automatically by taking the longest argument and converting all dashes to underscores. For an option with ('-f', '--foo-bar'), the parameter name is foo_bar. For an option with ('-x',), the parameter is x. For an option with ('-f', '--filename', 'dest'), the parameter is called dest.

Here's your example:

from __future__ import print_function
import click

@click.command()
@click.option('--output', 'data')
def generate_data(data):
    print(data)

if __name__ == '__main__':
    generate_data()

Running it:

$ python2.7 stack_overflow.py --output some_output
some_output
Sign up to request clarification or add additional context in comments.

2 Comments

Keep in mind that for Arguments this won't work, and instead throws an Exception: TypeError: Arguments take exactly one parameter declaration, got 2.
For Arguments you can put the desired variable name as the first argument, and what you want the user to see (in uppercase) as the metavar keyword argument. e.g. click.argument('foo_var', metavar='FOO')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.