pythonpython-3.xpython-click

How to use a renamed variable for a click option?


I want to use click to specify an option, but I want to access the value in a differently named variable.

So here is what I have

@click.command()
@click.option(
    "--all",
    is_flag=True,
    help="This will use all of it.",
)
def mycode(all):
    ...

But this would override the built-in function all. So in order to avoid that I am looking for a way so a different variable is used for the main code, i.e.

@click.command()
@click.option(
    "--all",
    is_flag=True,
    alias="use_all"
    help="This will use all of it.",
)
def mycode(use_all):
    ...

But the documentation on click.option seems very sparse/misses everything/I am looking at the wrong thing?

So how to do it?


Solution

  • I found a workaround by using multiple option names & putting the one we want in the variable name as the first one.

    import click
    
    
    @click.command()
    @click.option(
        "--use-all",
        "--all",
        is_flag=True,
        help="This will use all of it."
    )
    def mycode(use_all):
        print(use_all)
    
    

    Which works as expected & generates this help text:

    Usage: so_test.py [OPTIONS]
    
    Options:
      --use-all, --all  This will use all of it.
      --help            Show this message and exit.
    

    It's not ideal obviously. I think we may be able to add it by defining our own Option class & passing cls=CustomOptionClass in click.option - but I don't see any documentation about how one would go about doing that.