Skip to content
Myr

📝 Update optional CLI argument section in tutorial with `Annotated` (#983)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by gkeuccsr · committed by GitHub · parent 8b90ef8 · Browse files · 3 files+7 added−23 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
  • Co-authored-by: svlandeg <svlandeg@github.com>
  • Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>

Diff stats

3 files+7 added−23 removed

  • other:+7 added−23 removed

3 files+7 added−23 removed

modified:docs/tutorial/arguments/optional.md+3 added-9 removed
107 unmodified lines
108## Make an optional *CLI argument*109110Now, finally what we came for, an optional *CLI argument*.111112To make a *CLI argument* optional, use `typer.Argument()` and pass a different "default" as the first parameter to `typer.Argument()`, for example `None`:112To make a *CLI argument* optional, use `typer.Argument()` and make sure to provide a "default" value, for example `"World"`:113114{* docs_src/arguments/optional/tutorial002_an.py hl[7] *}114{* docs_src/arguments/optional/tutorial002_an.py hl[5] *}115116Now we have:117118```Python119name: Annotated[Optional[str], typer.Argument()] = None119name: Annotated[str, typer.Argument()] = "World"120```121122Because we are using `typer.Argument()` **Typer** will know that this is a *CLI argument* (no matter if *required* or *optional*).123124/// tip125126By using `Optional` your editor will be able to know that the value *could* be `None`, and will be able to warn you if you do something assuming it is a `str` that would break if it was `None`.127128///129124Check the help:125126<div class="termy">127
108 unmodified lines
modified:docs_src/arguments/optional/tutorial002_an.py+2 added-7 removed
1from typing import Optional21import typer2from typing_extensions import Annotated347def main(name: Annotated[Optional[str], typer.Argument()] = None):8 if name is None:9 print("Hello World!")10 else:11 print(f"Hello {name}")5def main(name: Annotated[str, typer.Argument()] = "World"):6 print(f"Hello {name}!")789if __name__ == "__main__":10 typer.run(main)
modified:docs_src/arguments/optional/tutorial002.py+2 added-7 removed
1from typing import Optional21import typer236def main(name: Optional[str] = typer.Argument(default=None)):7 if name is None:8 print("Hello World!")9 else:10 print(f"Hello {name}")4def main(name: str = typer.Argument(default="World")):5 print(f"Hello {name}!")678if __name__ == "__main__":9 typer.run(main)