Skip to content

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
Contributor

Copy link
Contributor

Copy link
Contributor

Copy link
Contributor

@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
Contributor

Copy link
Contributor

@MatteoBouvier MatteoBouvier marked this pull request as ready for review November 26, 2024 22:36
@github-actions github-actions bot added the conflicts Automatically generated when a PR has a merge conflict label Sep 1, 2025
Copy link
Contributor

github-actions bot commented Sep 1, 2025

This pull request has a merge conflict that needs to be resolved.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
conflicts Automatically generated when a PR has a merge conflict feature New feature, enhancement or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants