Is it possible to define an option's default value to another argument in click?
What I'd like would be something like:
@click.command()
@click.argument('project')
@click.option('--version', default=project)
def main(project, version):
...
If the option --version
is empty, it would automatically take project
's value. Is something like this possible?
You could try setting version to None. If the user sets it, it will be overridden, but if they do not you set it to project within the main function.
@click.command()
@click.argument('project')
@click.option('--version', default=None)
def main(project, version):
if version is None:
version = project
print("proj", project, "vers", version)
if __name__ == "__main__":
main()
Example usage:
$ python3 clicktest.py 1
proj 1 vers 1
$ python3 clicktest.py 1 --version 2
proj 1 vers 2
To do this in the decorators, you can take advantage of the callback
option, which accepts (context, param, value)
:
import click
@click.command()
@click.argument('project')
@click.option('--version', default=None,
callback=lambda c, p, v: v if v else c.params['project'])
def main(project, version):
print("proj", project, "vers", version)
if __name__ == "__main__":
main()