Debian Codegraph @

docs/options.md

raw
1 (options)=
2
3 # Options
4
5 ```{eval-rst}
6 .. currentmodule:: click
7 ```
8
9 Adding options to commands can be accomplished with the {func}`option`
10 decorator. At runtime the decorator invokes the {class}`Option` class. Options
11 in Click are distinct from {ref}`positional arguments <arguments>`.
12
13 Useful and often used kwargs are:
14
15 - `default`: Passes a default.
16 - `help`: Sets help message.
17 - `nargs`: Sets the number of arguments.
18 - `required`: Makes option required.
19 - `type`: Sets {ref}`parameter type <parameter-types>`
20
21 ```{contents}
22 :depth: 2
23 :local: true
24 ```
25
26 ## Option Decorator
27
28 The {func}`option()` decorator is usually passed two positional arguments: the
29 option name and the decorated function argument name.
30
31 ```{eval-rst}
32 .. click:example::
33
34 @click.command()
35 @click.option('--string-to-echo', 'string_to_echo')
36 def echo(string_to_echo):
37 click.echo(string_to_echo)
38
39
40 .. click:run::
41
42 invoke(echo, args=['--help'])
43 ```
44
45 However, if the decorated function argument name is not passed in, then Click
46 will try to infer it. A simple way to name the option so that Click will infer
47 it correctly is by taking the function argument, adding two dashes to the front
48 and converting underscores to dashes.
49
50 ```{eval-rst}
51 .. click:example::
52
53 @click.command()
54 @click.option('--string-to-echo')
55 def echo(string_to_echo):
56 click.echo(string_to_echo)
57
58 .. click:run::
59
60 invoke(echo, args=['--string-to-echo', 'Hi!'])
61 ```
62
63 More formally, Click will try to infer the decorated function argument name as
64 follows:
65
66 1. If a positional argument is a valid [Python identifier](https://docs.python.org/3/reference/lexical_analysis.html#identifiers) (and thus does not have dashes), it is chosen.
67 2. If multiple positional arguments are prefixed with `--`, the first one
68 declared is chosen.
69 3. Otherwise, the first positional argument prefixed with `-` is chosen.
70
71 To get the argument name, the chosen positional argument is converted to lower
72 case, a leading `-` or `--` is removed if found, and any remaining `-`
73 characters are replaced with `_`.
74
75 ```{eval-rst}
76 .. list-table:: Examples
77 :widths: 15 15
78 :header-rows: 1
79
80 * - Decorator Arguments
81 - Inferred Argument Name
82 * - ``"-f", "--foo-bar"``
83 - foo_bar
84 * - ``"-x"``
85 - x
86 * - ``"-f", "--filename", "dest"``
87 - dest
88 * - ``"--CamelCase"``
89 - camelcase
90 * - ``"-f", "-fb"``
91 - f
92 * - ``"--f", "--foo-bar"``
93 - f
94 * - ``"---f"``
95 - _f
96 ```
97
98 ## Basic Example
99
100 A simple {class}`click.Option` takes one option name. By default, it's assumed
101 that the decorated function argument is not required and the expected type is
102 `str`. If the decorated function takes a positional argument but the option is
103 not passed with the command, then `None` is passed.
104
105 ```{eval-rst}
106 .. click:example::
107
108 @click.command()
109 @click.option('--text')
110 def print_this(text):
111 click.echo(text)
112
113
114 .. click:run::
115
116 invoke(print_this, args=['--text=this'])
117
118 invoke(print_this, args=[])
119
120
121 .. click:run::
122
123 invoke(print_this, args=['--help'])
124
125 ```
126
127 ## Setting a Default
128
129 Instead of setting the `type`, you may set a default and Click will try to infer
130 the type.
131
132 ```{eval-rst}
133 .. click:example::
134
135 @click.command()
136 @click.option('--n', default=1)
137 def dots(n):
138 click.echo('.' * n)
139
140 .. click:run::
141
142 invoke(dots, args=['--help'])
143 ```
144
145 ## Multi Value Options
146
147 To make an option take multiple values, pass in `nargs`. Note you may pass in
148 any positive integer, but not -1. The values are passed to the decorated
149 function as a tuple.
150
151 ```{eval-rst}
152 .. click:example::
153
154 @click.command()
155 @click.option('--pos', nargs=2, type=float)
156 def findme(pos):
157 a, b = pos
158 click.echo(f"{a} / {b}")
159
160 .. click:run::
161
162 invoke(findme, args=['--pos', '2.0', '3.0'])
163
164 ```
165
166 (tuple-type)=
167
168 ## Multi Value Options as Tuples
169
170 ```{versionadded} 4.0
171 ```
172
173 By setting `nargs` to a specific number, each item in
174 the resulting tuple is of the same type. Alternatively, you might want to use
175 different types for different indexes in
176 the tuple. For this you can directly specify a tuple as `type`:
177
178 ```{eval-rst}
179 .. click:example::
180
181 @click.command()
182 @click.option('--item', type=(str, int))
183 def putitem(item):
184 name, id = item
185 click.echo(f"name={name} id={id}")
186
187
188 And on the command line:
189
190 .. click:run::
191
192 invoke(putitem, args=['--item', 'peter', '1338'])
193 ```
194
195 By using a tuple literal as the `type`, `nargs` gets automatically set to the
196 length of the tuple and the {class}`click.Tuple` type is automatically
197 used. The above example is thus equivalent to this:
198
199 ```{eval-rst}
200 .. click:example::
201
202 @click.command()
203 @click.option('--item', nargs=2, type=click.Tuple([str, int]))
204 def putitem(item):
205 name, id = item
206 click.echo(f"name={name} id={id}")
207 ```
208
209 (multiple-options)=
210
211 ## Multiple Options
212
213 The multiple options format allows options to take an arbitrary number of
214 arguments (which is called variadic). The arguments are passed to the decorated
215 function as a tuple. If set, `default` must be a list or tuple. Setting a string
216 as `default` will be interpreted as a list of characters.
217
218 ```{eval-rst}
219 .. click:example::
220
221 @click.command()
222 @click.option('--message', '-m', multiple=True)
223 def commit(message):
224 click.echo(message)
225 for m in message:
226 click.echo(m)
227
228 .. click:run::
229
230 invoke(commit, args=['-m', 'foo', '-m', 'bar', '-m', 'here'])
231 ```
232
233 ## Counting
234
235 To count the occurrence of an option, set `count=True`. If the option is not
236 passed on the command line, then the count is 0. Counting is commonly used for
237 verbosity.
238
239 ```{eval-rst}
240 .. click:example::
241
242 @click.command()
243 @click.option('-v', '--verbose', count=True)
244 def log(verbose):
245 click.echo(f"Verbosity: {verbose}")
246
247 .. click:run::
248
249 invoke(log, args=[])
250 invoke(log, args=['-vvv'])
251 ```
252
253 (option-boolean-flag)=
254
255 ## Boolean
256
257 Boolean options (boolean flags) take the values `True` or `False`. The simplest
258 case sets the default value to `False` if the flag is not passed, and `True` if
259 it is.
260
261 ```{eval-rst}
262 .. click:example::
263
264 import sys
265
266 @click.command()
267 @click.option('--shout', is_flag=True)
268 def info(shout):
269 rv = sys.platform
270 if shout:
271 rv = rv.upper() + '!!!!111'
272 click.echo(rv)
273
274
275 .. click:run::
276
277 invoke(info)
278 invoke(info, args=['--shout'])
279
280 ```
281
282 To implement this more explicitly, declare `--{on-option}/--{off-option}`. Click
283 will automatically set `is_flag=True`.
284
285 ```{eval-rst}
286 .. click:example::
287
288 import sys
289
290 @click.command()
291 @click.option('--shout/--no-shout', default=False)
292 def info(shout):
293 rv = sys.platform
294 if shout:
295 rv = rv.upper() + '!!!!111'
296 click.echo(rv)
297
298 .. click:run::
299
300 invoke(info)
301 invoke(info, args=['--shout'])
302 invoke(info, args=['--no-shout'])
303 ```
304
305 Use cases for this more explicit pattern include:
306
307 * The default can be dynamic so the user can explicitly specify the option with
308 either on or off option, or pass in no option to use the dynamic default.
309 * Shell scripts sometimes want to be explicit even when it's the default
310 * Shell aliases can set a flag, then an invocation can add a negation of the
311 flag
312
313 If a forward slash(`/`) is contained in your option name already, you can split
314 the parameters using `;`. In Windows `/` is commonly used as the prefix
315 character.
316
317 ```{eval-rst}
318 .. click:example::
319
320 @click.command()
321 @click.option('/debug;/no-debug')
322 def log(debug):
323 click.echo(f"debug={debug}")
324 ```
325
326 ```{versionchanged} 6.0
327 ```
328
329 If you want to define an alias for the second option only, then you will need to
330 use leading whitespace to disambiguate the format string.
331
332 ```{eval-rst}
333 .. click:example::
334
335 import sys
336
337 @click.command()
338 @click.option('--shout/--no-shout', ' /-N', default=False)
339 def info(shout):
340 rv = sys.platform
341 if shout:
342 rv = rv.upper() + '!!!!111'
343 click.echo(rv)
344
345 .. click:run::
346
347 invoke(info, args=['--help'])
348 ```
349
350 ## Flag Value
351
352 To have a flag pass a value to the decorated function set `flag_value`. This
353 automatically sets `is_flag=True`. To mark the flag as default, set
354 `default=True`. Setting flag values can be used to create patterns like this:
355
356 ```{eval-rst}
357 .. click:example::
358
359 import sys
360
361 @click.command()
362 @click.option('--upper', 'transformation', flag_value='upper', default=True)
363 @click.option('--lower', 'transformation', flag_value='lower')
364 def info(transformation):
365 click.echo(getattr(sys.platform, transformation)())
366
367 .. click:run::
368
369 invoke(info, args=['--help'])
370 invoke(info, args=['--upper'])
371 invoke(info, args=['--lower'])
372 invoke(info)
373 ```
374
375 ### How `default` and `flag_value` interact
376
377 The `default` value is given to the underlying function
378 as-is. So if you set `default=None`, the function receives
379 `None`. Same for any other type.
380
381 But there is a special case for **non-boolean** flags: if a
382 flag has a non-boolean `flag_value` (like a string or a
383 class), then `default=True` is interpreted as *the flag
384 should be activated by default*. The function receives the
385 `flag_value`, not the Python `True`.
386
387 Which means, in the example above, this option:
388
389 ```python
390 @click.option('--upper', 'transformation', flag_value='upper', default=True)
391 ```
392
393 is equivalent to:
394
395 ```python
396 @click.option('--upper', 'transformation', flag_value='upper', default='upper')
397 ```
398
399 Because the two are equivalent, it is recommended to always
400 use the second form and set `default` to the actual value
401 you want. This makes code more explicit and predictable.
402
403 This special case does **not** apply to boolean flags (where
404 `flag_value` is `True` or `False`). For boolean flags,
405 `default=True` is the literal Python value `True`.
406
407 The tables below show the value received by the function for
408 each combination of `default`, `flag_value`, and whether
409 the flag was passed on the command line.
410
411 #### Boolean flags (`is_flag=True`, boolean `flag_value`)
412
413 These are flags where `flag_value` is `True` or `False`.
414 The `default` value is always passed through literally
415 without any special substitution.
416
417 | `default` | `flag_value` | Not passed | `--flag` passed |
418 |-----------|--------------|------------|-----------------|
419 | *(unset)* | *(unset)* | `False` | `True` |
420 | `True` | *(unset)* | `True` | `True` |
421 | `False` | *(unset)* | `False` | `True` |
422 | `None` | *(unset)* | `None` | `True` |
423 | `True` | `True` | `True` | `True` |
424 | `True` | `False` | `True` | `False` |
425 | `False` | `True` | `False` | `True` |
426 | `False` | `False` | `False` | `False` |
427 | `None` | `True` | `None` | `True` |
428 | `None` | `False` | `None` | `False` |
429
430 ````{tip}
431 For a negative flag that defaults to off, prefer the
432 explicit pair form `--with-xyz/--without-xyz` over the
433 single-flag `flag_value=False, default=True`:
434
435 ```python
436 @click.option('--with-xyz/--without-xyz', 'enable_xyz', default=True)
437 ```
438 ````
439
440 #### Boolean flag pairs (`--flag/--no-flag`)
441
442 These use secondary option names to provide both an on and
443 off switch. The `default` value is always literal.
444
445 | `default` | Not passed | `--flag` | `--no-flag` |
446 |-----------|------------|----------|-------------|
447 | *(unset)* | `False` | `True` | `False` |
448 | `True` | `True` | `True` | `False` |
449 | `False` | `False` | `True` | `False` |
450 | `None` | `None` | `True` | `False` |
451
452 #### Non-boolean feature switches (`flag_value` is a string, class, etc.)
453
454 For these flags, `default=True` is a **special case**: it
455 means "activate this flag by default" and resolves to the
456 `flag_value`. All other `default` values are passed through
457 literally.
458
459 | `default` | `flag_value` | Not passed | `--flag` passed |
460 |------------|--------------|-------------|-----------------|
461 | *(unset)* | `"upper"` | `None` | `"upper"` |
462 | `True` | `"upper"` | `"upper"`¹ | `"upper"` |
463 | `"lower"` | `"upper"` | `"lower"` | `"upper"` |
464 | `None` | `"upper"` | `None` | `"upper"` |
465
466 ```{hint}
467 ¹: `default=True` is substituted with `flag_value`.
468 ```
469
470 #### Feature switch groups (multiple flags sharing one variable)
471
472 When multiple `flag_value` options target the same parameter
473 name, `default=True` on one of them marks it as the default
474 choice.
475
476 | Definition | Not passed | `--upper` | `--lower` |
477 |--------------------------------------------------------|------------|-----------|-----------|
478 | `--upper` with `flag_value='upper'`, `default=True` | `"upper"` | `"upper"` | `"lower"` |
479 | `--upper` with `flag_value='upper'`, `default='upper'` | `"upper"` | `"upper"` | `"lower"` |
480 | Both without `default` | `None` | `"upper"` | `"lower"` |
481
482 ## Values from Environment Variables
483
484 To pass in a value from a specific environment variable use `envvar`.
485
486 ```{eval-rst}
487 .. click:example::
488
489 @click.command()
490 @click.option('--username', envvar='USERNAME')
491 def greet(username):
492 click.echo(f"Hello {username}!")
493
494 .. click:run::
495
496 invoke(greet, env={'USERNAME': 'john'})
497 ```
498
499 If a list is passed to `envvar`, the first environment variable found is picked.
500
501 ```{eval-rst}
502 .. click:example::
503
504 @click.command()
505 @click.option('--username', envvar=['ALT_USERNAME', 'USERNAME'])
506 def greet(username):
507 click.echo(f"Hello {username}!")
508
509 .. click:run::
510
511 invoke(greet, env={'ALT_USERNAME': 'Bill', 'USERNAME': 'john'})
512
513 ```
514
515 Variable names are:
516 - [Case-insensitive on Windows but not on other platforms](https://github.com/python/cpython/blob/aa9eb5f757ceff461e6e996f12c89e5d9b583b01/Lib/os.py#L777-L789).
517 - Not stripped of whitespace and should match the exact name provided to the
518 `envvar` argument.
519
520 For flag options, there are two concepts to consider: the activation of the flag
521 driven by the environment variable, and the value of the flag if it is
522 activated.
523
524 The values read from environment variables are always strings and will require
525 extra processing. We need to transform these strings into boolean values that
526 will determine if the flag is activated or not.
527
528 Here are the rules used to parse environment variable values for flag options:
529 - `true`, `1`, `yes`, `on`, `t`, `y` are interpreted as activating the flag
530 - `false`, `0`, `no`, `off`, `f`, `n` are interpreted as deactivating the
531 flag
532 - The presence of the environment variable without value is interpreted as
533 deactivating the flag
534 - Empty strings are interpreted as deactivating the flag
535 - Values are case-insensitive, so the `True`, `TRUE`, `tRuE` strings are all
536 interpreted as activating the flag
537 - Values are stripped of leading and trailing whitespace before being
538 interpreted, so the `" True "` string is transformed to `"true"` and thus
539 activates the flag
540 - If the flag option has a `flag_value` argument, passing that value in the
541 environment variable will activate the flag, in addition to all the cases
542 described above
543 - Any other value is interpreted as deactivating the flag
544
545 ```{caution}
546 For boolean flags with a pair of values, the only recognized environment variable is the one provided to the `envvar` argument.
547
548 So an option defined as `--flag\--no-flag`, with a `envvar="FLAG"` parameter, there is no magical `NO_FLAG=<anything>` variable that is recognized. Only the `FLAG=<anything>` environment variable is recognized.
549 ```
550
551 If the flag is activated, its value is set to `flag_value`. Otherwise, the value
552 defaults to `None`.
553
554 ## Multiple Options from Environment Values
555
556 As options can accept multiple values, pulling in such values from
557 environment variables (which are strings) is a bit more complex. Click handles
558 this by deferring customization of the behavior to the `type`. For both
559 `multiple` and `nargs` with values other than
560 `1`, Click will invoke the {meth}`ParamType.split_envvar_value` method to
561 perform the splitting.
562
563 The default implementation for all types is to split on whitespace. The
564 exceptions to this rule are the {class}`File` and {class}`Path` types
565 which both split according to the operating system's path splitting rules.
566 On Unix systems like Linux and OS X, the splitting happens on
567 every colon (`:`), and for Windows, splitting on every semicolon (`;`).
568
569 ```{eval-rst}
570 .. click:example::
571
572 @click.command()
573 @click.option('paths', '--path', envvar='PATHS', multiple=True,
574 type=click.Path())
575 def perform(paths):
576 for path in paths:
577 click.echo(path)
578
579 if __name__ == '__main__':
580 perform()
581
582 .. click:run::
583
584 import os
585 invoke(perform, env={"PATHS": f"./foo/bar{os.path.pathsep}./test"})
586 ```
587
588 ## Other Prefix Characters
589
590 Click can deal with prefix characters besides `-` for options, including `/` and
591 `+`, as well as others. Note that alternative prefix characters are generally
592 used very sparingly if at all within POSIX.
593
594 ```{eval-rst}
595 .. click:example::
596
597 @click.command()
598 @click.option('+w/-w')
599 def chmod(w):
600 click.echo(f"writable={w}")
601
602 .. click:run::
603
604 invoke(chmod, args=['+w'])
605 invoke(chmod, args=['-w'])
606 ```
607
608 There are special considerations for using `/` as prefix character. See
609 {ref}`option-boolean-flag` for more.
610
611 (optional-value)=
612
613 ## Optional Value
614
615 Providing the value to an option can be made optional, in which case
616 providing only the option's flag without a value will either show a
617 prompt or use its `flag_value`.
618
619 Setting `is_flag=False, flag_value=value` tells Click that the option
620 can still be passed a value, but if only the flag is given, the
621 value will be `flag_value`.
622
623 ```{eval-rst}
624 .. click:example::
625
626 @click.command()
627 @click.option("--name", is_flag=False, flag_value="Flag", default="Default")
628 def hello(name):
629 click.echo(f"Hello, {name}!")
630
631 .. click:run::
632
633 invoke(hello, args=[])
634 invoke(hello, args=["--name", "Value"])
635 invoke(hello, args=["--name"])
636 ```