Skip to content

Commit 563e63e

Browse files
gkeuccsrsvlandegtiangolo
authored
📝 Update optional CLI argument section in tutorial with Annotated (#983)
Co-authored-by: Sofie Van Landeghem <[email protected]> Co-authored-by: svlandeg <[email protected]> Co-authored-by: Sebastián RamĂ­rez <[email protected]>
1 parent 8b90ef8 commit 563e63e

File tree

3 files changed

+7
-23
lines changed

3 files changed

+7
-23
lines changed

‎docs/tutorial/arguments/optional.md

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -109,24 +109,18 @@ name: str
109109

110110
Now, finally what we came for, an optional *CLI argument*.
111111

112-
To make a *CLI argument* optional, use `typer.Argument()` and pass a different "default" as the first parameter to `typer.Argument()`, for example `None`:
112+
To make a *CLI argument* optional, use `typer.Argument()` and make sure to provide a "default" value, for example `"World"`:
113113

114-
{* docs_src/arguments/optional/tutorial002_an.py hl[7] *}
114+
{* docs_src/arguments/optional/tutorial002_an.py hl[5] *}
115115

116116
Now we have:
117117

118118
```Python
119-
name: Annotated[Optional[str], typer.Argument()] = None
119+
name: Annotated[str, typer.Argument()] = "World"
120120
```
121121

122122
Because we are using `typer.Argument()` **Typer** will know that this is a *CLI argument* (no matter if *required* or *optional*).
123123

124-
/// tip
125-
126-
By 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`.
127-
128-
///
129-
130124
Check the help:
131125

132126
<div class="termy">

‎docs_src/arguments/optional/tutorial002.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,8 @@
1-
from typing import Optional
2-
31
import typer
42

53

6-
def main(name: Optional[str] = typer.Argument(default=None)):
7-
if name is None:
8-
print("Hello World!")
9-
else:
10-
print(f"Hello {name}")
4+
def main(name: str = typer.Argument(default="World")):
5+
print(f"Hello {name}!")
116

127

138
if __name__ == "__main__":

‎docs_src/arguments/optional/tutorial002_an.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,9 @@
1-
from typing import Optional
2-
31
import typer
42
from typing_extensions import Annotated
53

64

7-
def main(name: Annotated[Optional[str], typer.Argument()] = None):
8-
if name is None:
9-
print("Hello World!")
10-
else:
11-
print(f"Hello {name}")
5+
def main(name: Annotated[str, typer.Argument()] = "World"):
6+
print(f"Hello {name}!")
127

138

149
if __name__ == "__main__":

0 commit comments

Comments
 (0)