Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ Add support for optional values of CLI Options #1063

Open
wants to merge 8 commits into
base: master
Choose a base branch
from

Conversation

MatteoBouvier
Copy link

Click allows to make cli option values optional, using a default value when not provided (https://click.palletsprojects.com/en/stable/options/#optional-value).

This feature is not currently supported by Typer but there is interest from people (including myself) : cf #873, #608.
My use case was creating a --doc option for displaying a detailed documentation of a command, in english by default but in another language if passing a language name such as --doc fr.

To stick to the type annotation philosophy of Typer, this PR defines Options with optional values (with type T) by annotating them as bool | T :

def main(doc: Annotated[bool | str, typer.Option()] = "en"):
    if doc:
        print_doc(language=doc)

    # code ...
  • when not passing --doc, the doc parameter gets a value of False
  • when passing --doc <value> as usual, the doc parameter gets the value
  • when passing only --doc with no value, the doc parameter gets the default value "en"

The help message for the Options is rendered as:

╭─ Options ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ --doc             BOOLEAN|TEXT  [default: False (en)]                                                                                                              │
│ --help                          Show this message and exit.                                                                                                        │
╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯


note : This PR does not implement type unions for Options, only bool | T is parsed

Copy link

Copy link

Copy link

Copy link

@MatteoBouvier MatteoBouvier marked this pull request as draft November 26, 2024 16:32
@svlandeg svlandeg added the feature New feature, enhancement or request label Nov 26, 2024
Copy link

Copy link

@MatteoBouvier MatteoBouvier marked this pull request as ready for review November 26, 2024 22:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature New feature, enhancement or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants