'How to implement --version using python click?

I want to implement mycommand --version using python click. I have something like this working but it feels kinda clunky.

@click.group(invoke_without_command=True, no_args_is_help=True)
@click.pass_context
@click.option('--version', 'version')
def cli(ctx, version):
    if version:
        ctx.echo(f'{sys.argv[0]} {__version__}')
        ctx.exit()


Solution 1:[1]

As it turns out, click has a builtin decorator click.version_option to accomplish this. The code now becomes:

@click.group()
@click.version_option(__version__)
@click.pass_context
def cli(ctx):
    pass

Solution 2:[2]

You can use click.version_option decorator to implement --version option.

If your setup.py like this and have version click will read it automatically.

from setuptools import setup

setup(
    name='application',
    version='0.1',
    py_modules=['application'],
    install_requires=[
        'Click',
    ],
)

The click.version_option option without any argument will read version from setup.py it.

@click.group(invoke_without_command=True, no_args_is_help=True)
@click.pass_context
@click.version_option()
def cli(ctx):
   ...

Run and Result

$ application --version 
application, version 0.1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 melvio
Solution 2