7

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?

4
  • Is you code not working? Commented Oct 2, 2019 at 12:57
  • 1
    Yes, this is entirely possible, however you can't then use variables from functions in your @click.option - you'd need to define project before @click.option. Commented Oct 2, 2019 at 12:58
  • @YashKrishan no the code is not working Commented Oct 2, 2019 at 13:00
  • Is there an error? If yes, share it Commented Oct 2, 2019 at 13:01

1 Answer 1

6

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()
Sign up to request clarification or add additional context in comments.

1 Comment

Yes but I would like a solution where everything is in the Click decorators and not inside the function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.