File: default.md

package info (click to toggle)
typer 0.19.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,688 kB
  • sloc: python: 16,702; javascript: 280; sh: 28; makefile: 27
file content (102 lines) | stat: -rw-r--r-- 2,219 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# CLI Arguments with Default

We can also use the same `typer.Argument()` to set a default value.

That way the *CLI argument* will be optional *and also* have a default value.

## An optional *CLI argument* with a default

We can also use `typer.Argument()` to make a *CLI argument* have a default value other than `None`:

{* docs_src/arguments/default/tutorial001_an.py hl[5] *}

/// tip

Because now the value will be a `str` passed by the user or the default value of `"Wade Wilson"` which is also a `str`, we know the value will never be `None`, so we don't have to (and shouldn't) use `Optional[str]`.

Have in mind that the `Optional[something]` tells Python that a value "could be `None`". But the use of `Optional` doesn't affect Typer in any way, e.g. it doesn't tell Typer if a value is required or not.

///

Check it:

<div class="termy">

```console
// Check the help
$ python main.py --help

// Notice the [default: Wade Wilson] ✨
Usage: main.py [OPTIONS] [NAME]

Arguments:
  [NAME]  [default: Wade Wilson]

Options:
  --help                Show this message and exit.

// With no optional CLI argument
$ python main.py

Hello Wade Wilson

// With one CLI argument
$ python main.py Camila

Hello Camila
```

</div>

## Dynamic default value

And we can even make the default value be dynamically generated by passing a function as the `default_factory` argument:

{* docs_src/arguments/default/tutorial002_an.py hl[7:8,11] *}

In this case, we created the function `get_name` that will just return a random `str` each time.

And we pass it as the first function argument to `typer.Argument()`.

/// tip

The word "factory" in `default_factory` is just a fancy way of saying "function that will create the default value".

///

Check it:

<div class="termy">

```console
// Check the help
$ python main.py --help

Usage: main.py [OPTIONS] [NAME]

Arguments:
  [NAME]  [default: (dynamic)]

Options:
  --help                Show this message and exit.

// Try it several times, it will use a random default each time
$ python main.py

Hello Deadpool

$ python main.py

Hello Hiro

$ python main.py

Hello Rick

// Now pass a value for the CLI argument
$ python main.py Camila

Hello Camila
```

</div>