How to set default value of option to another argument in Python Click?
Asked Answered
F

1

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?

Fung answered 2/10, 2019 at 12:55 Comment(4)
Is you code not working?Apteryx
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.Sunless
@YashKrishan no the code is not workingFung
Is there an error? If yes, share itApteryx
A
5

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()
Auxiliary answered 2/10, 2019 at 13:8 Comment(1)
Yes but I would like a solution where everything is in the Click decorators and not inside the functionFung

© 2022 - 2024 — McMap. All rights reserved.