Skip to content

Commit 26c7b41

Browse files
committed
clarify with non-Optional typing
1 parent 014882c commit 26c7b41

3 files changed

Lines changed: 13 additions & 17 deletions

File tree

docs/tutorial/arguments/optional.md

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ name: str
113113

114114
Now, finally what we came for, an optional *CLI argument*.
115115

116-
To make a *CLI argument* optional, use `typer.Argument()` and make sure to provide a "default" value, for example `None`:
116+
To make a *CLI argument* optional, use `typer.Argument()` and make sure to provide a "default" value, for example `"World"`:
117117

118118
```Python hl_lines="7"
119119
{!../docs_src/arguments/optional/tutorial002_an.py!}
@@ -122,14 +122,20 @@ To make a *CLI argument* optional, use `typer.Argument()` and make sure to provi
122122
Now we have:
123123

124124
```Python
125-
name: Annotated[Optional[str], typer.Argument()] = None
125+
name: Annotated[str, typer.Argument()] = "World"
126126
```
127127

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

130130
/// tip
131131

132-
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`.
132+
If you want the default value to be `None`, you have to additionally declare the parameter to be of type `Optional`, which will tell your editor that the value of this parameter can be `None`:
133+
134+
```Python
135+
name: Annotated[Optional[str], typer.Argument()] = None
136+
```
137+
138+
Your editor can then warn you if you do something assuming it is a `str` that would break if it was `None`.
133139

134140
///
135141

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)