Rename python click argument
Asked Answered
G

2

7

I have this chunk of code:

import click

@click.option('--delete_thing', help="Delete some things columns.", default=False)
def cmd_do_this(delete_thing=False):
    print "I deleted the thing."

I would like to rename the option variable in --delete-thing. But python does not allow dashes in variable names. Is there a way to write this kind of code?

import click

@click.option('--delete-thing', help="Delete some things columns.", default=False, store_variable=delete_thing)
    def cmd_do_this(delete_thing=False):
        print "I deleted the thing."

So delete_thing will be set to the value of delete-thing

Guidry answered 19/10, 2016 at 13:26 Comment(0)
G
4

By default, click will intelligently map intra-option commandline hyphens to underscores so your code should work as-is. This is used in the click documentation, e.g., in the Choice example. If --delete-thing is intended to be a boolean option, you may also want to make it a boolean argument.

Gorgoneion answered 19/10, 2016 at 15:27 Comment(1)
And it's true! Though I understood the take home message, your second link probably points to the wrong page.Guidry
U
7

As gbe's answer says, click will automatically convert - in the cli parameters to _ for the python function parameters.

But you can also explicitly name the python variable to whatever you want. In this example, it converts --delete-thing to new_var_name:

import click

@click.command()
@click.option('--delete-thing', 'new_var_name')

def cmd_do_this(new_var_name):
    print(f"I deleted the thing: {new_var_name}")
Unorthodox answered 25/1, 2022 at 21:29 Comment(0)
G
4

By default, click will intelligently map intra-option commandline hyphens to underscores so your code should work as-is. This is used in the click documentation, e.g., in the Choice example. If --delete-thing is intended to be a boolean option, you may also want to make it a boolean argument.

Gorgoneion answered 19/10, 2016 at 15:27 Comment(1)
And it's true! Though I understood the take home message, your second link probably points to the wrong page.Guidry

© 2022 - 2024 — McMap. All rights reserved.