Search code examples
pythonversionpython-click

How to Add Another Name Option for Python click.version_option?


My question is exactly the same as in How to add option name to the Version option in Click

I have the code, and I am able to print out the version of my library using the command "py main.py --version"

See: https://click.palletsprojects.com/en/8.1.x/api/#click.version_option

@click.version_option(version=version)
def main():
  pass

However, I would like to add another name option "-V", how can I do this? The documentation and codebase doesn't seem to have this option to add another name option like for the --help argument. (See: https://click.palletsprojects.com/en/8.1.x/api/#click.Context.help_option_names)

I have tried to add the "-v" name option in the param_decls, however I get the following error:

enter image description here

Neither of these work either, since positional arguments can't come after keyword arguments (first line), and I'm not sure why the second line doesn't work:

@click.version_option(version=version, "--version", "-V")
@click.version_option("--version", "-V", version=version)

Please refer to the answer provided by @aaossa below! :D


Solution

  • You should be able to define additional option names using the positional argument param_decls ("One or more option names." according to the docs)

    Here's an example:

    import click
    
    version = "0.0.1"
    
    @click.version_option(version, "--version", "-V")
    @click.command()
    def main():
      pass
    
    if __name__ == '__main__':
      main()