Skip to content
Myr

options.md

This file

Path

docs/options.md

800 lines · 25.1 KiB · Markdown

Last changed by

docs: fix flag-pair separator and small typos in options guide (#3510)Kevin Deldyckebefore adoption8240d25

History of this file

Take it

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

lines 1–9why, one step back
1(options)=
23# Options45```{eval-rst}6.. currentmodule:: click7```89Adding options to commands can be accomplished with the {func}`option`

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 10–11why, one step back
10decorator. At runtime the decorator invokes the {class}`Option` class. Options
11in Click are distinct from {ref}`positional arguments <arguments>`.

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

lines 12–27why, one step back
12
13Useful and often used kwargs are:1415- `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>`2021```{contents}22:depth: 223:local: true24```2526## Option Decorator27

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 28–29why, one step back
28The {func}`option()` decorator is usually passed two positional arguments: the
29option name and the decorated function argument name.

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

lines 30–44why, one step back
30
31```{eval-rst}32.. click:example::3334 @click.command()35 @click.option('--string-to-echo', 'string_to_echo')36 def echo(string_to_echo):37 click.echo(string_to_echo)383940.. click:run::4142 invoke(echo, args=['--help'])43```44

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 45–48why, one step back
45However, if the decorated function argument name is not passed in, then Click
46will try to infer it. A simple way to name the option so that Click will infer47it correctly is by taking the function argument, adding two dashes to the front48and converting underscores to dashes.

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

lines 49–62why, one step back
49
50```{eval-rst}51.. click:example::5253 @click.command()54 @click.option('--string-to-echo')55 def echo(string_to_echo):56 click.echo(string_to_echo)5758.. click:run::5960 invoke(echo, args=['--string-to-echo', 'Hi!'])61```62

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 63–64why, one step back
63More formally, Click will try to infer the decorated function argument name as
64follows:

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

line 65why, one step back
65

revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9

line 66why, one step back
661. 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.

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 67–68why, one step back
672. If multiple positional arguments are prefixed with `--`, the first one
68 declared is chosen.

revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9

line 69why, one step back
693. Otherwise, the first positional argument prefixed with `-` is chosen.

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

line 70why, one step back
70

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 71–73why, one step back
71To get the argument name, the chosen positional argument is converted to lower
72case, a leading `-` or `--` is removed if found, and any remaining `-`73characters are replaced with `_`.

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

lines 74–76why, one step back
74
75```{eval-rst}76.. list-table:: Examples

revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9

line 77why, one step back
77 :widths: 15 15

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

lines 78–80why, one step back
78 :header-rows: 1
7980 * - Decorator Arguments

revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9

line 81why, one step back
81 - Inferred Argument Name

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

lines 82–99why, one step back
82 * - ``"-f", "--foo-bar"``
83 - foo_bar84 * - ``"-x"``85 - x86 * - ``"-f", "--filename", "dest"``87 - dest88 * - ``"--CamelCase"``89 - camelcase90 * - ``"-f", "-fb"``91 - f92 * - ``"--f", "--foo-bar"``93 - f94 * - ``"---f"``95 - _f96```9798## Basic Example99

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 100–103why, one step back
100A simple {class}`click.Option` takes one option name. By default, it's assumed
101that the decorated function argument is not required and the expected type is102`str`. If the decorated function takes a positional argument but the option is103not passed with the command, then `None` is passed.

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

lines 104–128why, one step back
104
105```{eval-rst}106.. click:example::107108 @click.command()109 @click.option('--text')110 def print_this(text):111 click.echo(text)112113114.. click:run::115116 invoke(print_this, args=['--text=this'])117118 invoke(print_this, args=[])119120121.. click:run::122123 invoke(print_this, args=['--help'])124125```126127## Setting a Default128

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 129–130why, one step back
129Instead of setting the `type`, you may set a default and Click will try to infer
130the type.

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

lines 131–146why, one step back
131
132```{eval-rst}133.. click:example::134135 @click.command()136 @click.option('--n', default=1)137 def dots(n):138 click.echo('.' * n)139140.. click:run::141142 invoke(dots, args=['--help'])143```144145## Multi Value Options146

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 147–149why, one step back
147To make an option take multiple values, pass in `nargs`. Note you may pass in
148any positive integer, but not -1. The values are passed to the decorated149function as a tuple.

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

lines 150–169why, one step back
150
151```{eval-rst}152.. click:example::153154 @click.command()155 @click.option('--pos', nargs=2, type=float)156 def findme(pos):157 a, b = pos158 click.echo(f"{a} / {b}")159160.. click:run::161162 invoke(findme, args=['--pos', '2.0', '3.0'])163164```165166(tuple-type)=167168## Multi Value Options as Tuples169

Fix version added and version changed in options docs. (#2957)Rowlando13before adoption497d1b6

lines 170–171why, one step back
170```{versionadded} 4.0
171```

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

line 172why, one step back
172

revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9

line 173why, one step back
173By setting `nargs` to a specific number, each item in

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 174–175why, one step back
174the resulting tuple is of the same type. Alternatively, you might want to use
175different types for different indexes in

revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9

line 176why, one step back
176the tuple. For this you can directly specify a tuple as `type`:

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

lines 177–194why, one step back
177
178```{eval-rst}179.. click:example::180181 @click.command()182 @click.option('--item', type=(str, int))183 def putitem(item):184 name, id = item185 click.echo(f"name={name} id={id}")186187188And on the command line:189190.. click:run::191192 invoke(putitem, args=['--item', 'peter', '1338'])193```194

revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9

line 195why, one step back
195By using a tuple literal as the `type`, `nargs` gets automatically set to the

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

lines 196–212why, one step back
196length of the tuple and the {class}`click.Tuple` type is automatically
197used. The above example is thus equivalent to this:198199```{eval-rst}200.. click:example::201202 @click.command()203 @click.option('--item', nargs=2, type=click.Tuple([str, int]))204 def putitem(item):205 name, id = item206 click.echo(f"name={name} id={id}")207```208209(multiple-options)=210211## Multiple Options212

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 213–216why, one step back
213The multiple options format allows options to take an arbitrary number of
214arguments (which is called variadic). The arguments are passed to the decorated215function as a tuple. If set, `default` must be a list or tuple. Setting a string216as `default` will be interpreted as a list of characters.

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

lines 217–223why, one step back
217
218```{eval-rst}219.. click:example::220221 @click.command()222 @click.option('--message', '-m', multiple=True)223 def commit(message):

Fix option multiple docs (#3086)Rowlando13before adoption2ed395b

lines 224–226why, one step back
224 click.echo(message)
225 for m in message:226 click.echo(m)

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

lines 227–232why, one step back
227
228.. click:run::229230 invoke(commit, args=['-m', 'foo', '-m', 'bar', '-m', 'here'])231```232

Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a

lines 233–274why, one step back
233## Combining short options
234235Short options made of a single character can be combined into one argument: `-abc` is equivalent to `-a -b -c`. This is the standard POSIX behavior for short option stacking, and it is the reason a repeated flag like `-vvv` works with the [Counting](#counting) feature.236237```{eval-rst}238.. click:example::239240 @click.command()241 @click.option('-a', is_flag=True)242 @click.option('-b', is_flag=True)243 @click.option('-c', is_flag=True)244 def cli(a, b, c):245 click.echo(f"a={a} b={b} c={c}")246247.. click:run::248249 invoke(cli, args=['-a', '-b', '-c'])250 invoke(cli, args=['-abc'])251```252253If the last option in the combination takes a value, the value can either follow as the next argument or be attached directly:254255```{eval-rst}256.. click:example::257258 @click.command()259 @click.option('-v', is_flag=True)260 @click.option('-n', type=int)261 def cli(v, n):262 click.echo(f"v={v} n={n}")263264.. click:run::265266 invoke(cli, args=['-v', '-n', '5'])267 invoke(cli, args=['-vn', '5'])268 invoke(cli, args=['-vn5'])269```270271```{note}272Multi-character short option names are not supported. An argument like `-dbg` is interpreted as the combination of `-d`, `-b`, and `-g`, so Click reports `No such option: -d` if `-d` is not declared. For longer option names, use a long option with the `--` prefix (like `--debug`).273```274

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

lines 275–276why, one step back
275## Counting
276

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 277–279why, one step back
277To count the occurrence of an option, set `count=True`. If the option is not
278passed on the command line, then the count is 0. Counting is commonly used for279verbosity.

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

lines 280–298why, one step back
280
281```{eval-rst}282.. click:example::283284 @click.command()285 @click.option('-v', '--verbose', count=True)286 def log(verbose):287 click.echo(f"Verbosity: {verbose}")288289.. click:run::290291 invoke(log, args=[])292 invoke(log, args=['-vvv'])293```294295(option-boolean-flag)=296297## Boolean298

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 299–301why, one step back
299Boolean options (boolean flags) take the values `True` or `False`. The simplest
300case sets the default value to `False` if the flag is not passed, and `True` if301it is.

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

lines 302–323why, one step back
302
303```{eval-rst}304.. click:example::305306 import sys307308 @click.command()309 @click.option('--shout', is_flag=True)310 def info(shout):311 rv = sys.platform312 if shout:313 rv = rv.upper() + '!!!!111'314 click.echo(rv)315316317.. click:run::318319 invoke(info)320 invoke(info, args=['--shout'])321322```323

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 324–325why, one step back
324To implement this more explicitly, declare `--{on-option}/--{off-option}`. Click
325will automatically set `is_flag=True`.

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

lines 326–345why, one step back
326
327```{eval-rst}328.. click:example::329330 import sys331332 @click.command()333 @click.option('--shout/--no-shout', default=False)334 def info(shout):335 rv = sys.platform336 if shout:337 rv = rv.upper() + '!!!!111'338 click.echo(rv)339340.. click:run::341342 invoke(info)343 invoke(info, args=['--shout'])344 invoke(info, args=['--no-shout'])345```

Document option no option pattern better (#3103)Rowlando13before adoption06f52a4

lines 346–348why, one step back
346
347Use cases for this more explicit pattern include:348

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 349–350why, one step back
349* The default can be dynamic so the user can explicitly specify the option with
350 either on or off option, or pass in no option to use the dynamic default.

Document option no option pattern better (#3103)Rowlando13before adoption06f52a4

line 351why, one step back
351* Shell scripts sometimes want to be explicit even when it's the default

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 352–353why, one step back
352* Shell aliases can set a flag, then an invocation can add a negation of the
353 flag

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

line 354why, one step back
354

docs: fix flag-pair separator and small typos in options guide (#3510)Kevin Deldyckebefore adoption8240d25

line 355why, one step back
355If a forward slash (`/`) is contained in your option name already, you can split

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 356–357why, one step back
356the parameters using `;`. In Windows `/` is commonly used as the prefix
357character.

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

lines 358–367why, one step back
358
359```{eval-rst}360.. click:example::361362 @click.command()363 @click.option('/debug;/no-debug')364 def log(debug):365 click.echo(f"debug={debug}")366```367

Fix version added and version changed in options docs. (#2957)Rowlando13before adoption497d1b6

lines 368–369why, one step back
368```{versionchanged} 6.0
369```

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

line 370why, one step back
370

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 371–372why, one step back
371If you want to define an alias for the second option only, then you will need to
372use leading whitespace to disambiguate the format string.

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

lines 373–393why, one step back
373
374```{eval-rst}375.. click:example::376377 import sys378379 @click.command()380 @click.option('--shout/--no-shout', ' /-N', default=False)381 def info(shout):382 rv = sys.platform383 if shout:384 rv = rv.upper() + '!!!!111'385 click.echo(rv)386387.. click:run::388389 invoke(info, args=['--help'])390```391392## Flag Value393

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 394–396why, one step back
394To have a flag pass a value to the decorated function set `flag_value`. This
395automatically sets `is_flag=True`. To mark the flag as default, set396`default=True`. Setting flag values can be used to create patterns like this:

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

lines 397–416why, one step back
397
398```{eval-rst}399.. click:example::400401 import sys402403 @click.command()404 @click.option('--upper', 'transformation', flag_value='upper', default=True)405 @click.option('--lower', 'transformation', flag_value='lower')406 def info(transformation):407 click.echo(getattr(sys.platform, transformation)())408409.. click:run::410411 invoke(info, args=['--help'])412 invoke(info, args=['--upper'])413 invoke(info, args=['--lower'])414 invoke(info)415```416

Reconcile default value passing and default activation (#3239)Rowlando13before adoption8c95c73

line 417why, one step back
417### How `default` and `flag_value` interact

Merge branch 'main' into stableDavid Lordbefore adoption81a482f

line 418why, one step back
418

Reconcile default value passing and default activation (#3239)Rowlando13before adoption8c95c73

lines 419–421why, one step back
419The `default` value is given to the underlying function
420as-is. So if you set `default=None`, the function receives421`None`. Same for any other type.

Merge branch 'main' into stableDavid Lordbefore adoption81a482f

line 422why, one step back
422

Reconcile default value passing and default activation (#3239)Rowlando13before adoption8c95c73

lines 423–427why, one step back
423But there is a special case for **non-boolean** flags: if a
424flag has a non-boolean `flag_value` (like a string or a425class), then `default=True` is interpreted as *the flag426should be activated by default*. The function receives the427`flag_value`, not the Python `True`.

Merge branch 'main' into stableDavid Lordbefore adoption81a482f

line 428why, one step back
428

Reconcile default value passing and default activation (#3239)Rowlando13before adoption8c95c73

lines 429–430why, one step back
429Which means, in the example above, this option:
430

Merge branch 'main' into stableDavid Lordbefore adoption81a482f

lines 431–440why, one step back
431```python
432@click.option('--upper', 'transformation', flag_value='upper', default=True)433```434435is equivalent to:436437```python438@click.option('--upper', 'transformation', flag_value='upper', default='upper')439```440

Reconcile default value passing and default activation (#3239)Rowlando13before adoption8c95c73

lines 441–479why, one step back
441Because the two are equivalent, it is recommended to always
442use the second form and set `default` to the actual value443you want. This makes code more explicit and predictable.444445This special case does **not** apply to boolean flags (where446`flag_value` is `True` or `False`). For boolean flags,447`default=True` is the literal Python value `True`.448449The tables below show the value received by the function for450each combination of `default`, `flag_value`, and whether451the flag was passed on the command line.452453#### Boolean flags (`is_flag=True`, boolean `flag_value`)454455These are flags where `flag_value` is `True` or `False`.456The `default` value is always passed through literally457without any special substitution.458459| `default` | `flag_value` | Not passed | `--flag` passed |460|-----------|--------------|------------|-----------------|461| *(unset)* | *(unset)* | `False` | `True` |462| `True` | *(unset)* | `True` | `True` |463| `False` | *(unset)* | `False` | `True` |464| `None` | *(unset)* | `None` | `True` |465| `True` | `True` | `True` | `True` |466| `True` | `False` | `True` | `False` |467| `False` | `True` | `False` | `True` |468| `False` | `False` | `False` | `False` |469| `None` | `True` | `None` | `True` |470| `None` | `False` | `None` | `False` |471472````{tip}473For a negative flag that defaults to off, prefer the474explicit pair form `--with-xyz/--without-xyz` over the475single-flag `flag_value=False, default=True`:476477```python478@click.option('--with-xyz/--without-xyz', 'enable_xyz', default=True)479```

Merge branch 'main' into stableDavid Lordbefore adoption81a482f

line 480why, one step back
480````

Reconcile default value passing and default activation (#3239)Rowlando13before adoption8c95c73

lines 481–513why, one step back
481
482#### Boolean flag pairs (`--flag/--no-flag`)483484These use secondary option names to provide both an on and485off switch. The `default` value is always literal.486487| `default` | Not passed | `--flag` | `--no-flag` |488|-----------|------------|----------|-------------|489| *(unset)* | `False` | `True` | `False` |490| `True` | `True` | `True` | `False` |491| `False` | `False` | `True` | `False` |492| `None` | `None` | `True` | `False` |493494#### Non-boolean feature switches (`flag_value` is a string, class, etc.)495496For these flags, `default=True` is a **special case**: it497means "activate this flag by default" and resolves to the498`flag_value`. All other `default` values are passed through499literally.500501| `default` | `flag_value` | Not passed | `--flag` passed |502|------------|--------------|-------------|-----------------|503| *(unset)* | `"upper"` | `None` | `"upper"` |504| `True` | `"upper"` | `"upper"`¹ | `"upper"` |505| `"lower"` | `"upper"` | `"lower"` | `"upper"` |506| `None` | `"upper"` | `None` | `"upper"` |507508```{hint}509¹: `default=True` is substituted with `flag_value`.510```511512#### Feature switch groups (multiple flags sharing one variable)513

Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a

lines 514–518why, one step back
514Several `flag_value` options can target the same parameter name to form a
515feature switch group. The user picks one flag on the command line, and the516function receives the corresponding `flag_value`. When the user picks none,517Click falls back to whichever option claims the slot under the arbitration518rules described below.

Reconcile default value passing and default activation (#3239)Rowlando13before adoption8c95c73

line 519why, one step back
519

Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a

lines 520–526why, one step back
520##### Non-boolean groups
521522For non-boolean `flag_value` (strings, enum members, classes, ...), place523`default=True` on the option that should win when no flag is passed. The524substitution rule above resolves it to that option's `flag_value`. Any other525explicit `default` is passed through literally.526

Reconcile default value passing and default activation (#3239)Rowlando13before adoption8c95c73

lines 527–530why, one step back
527| Definition | Not passed | `--upper` | `--lower` |
528|--------------------------------------------------------|------------|-----------|-----------|529| `--upper` with `flag_value='upper'`, `default=True` | `"upper"` | `"upper"` | `"lower"` |530| `--upper` with `flag_value='upper'`, `default='upper'` | `"upper"` | `"upper"` | `"lower"` |

Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a

lines 531–565why, one step back
531| `--upper` with `flag_value='upper'`, `default=None` | `None` | `"upper"` | `"lower"` |
532| Neither option carries a `default` | `None` | `"upper"` | `"lower"` |533534The third row is the three-state pattern: the function receives `None` when no535flag is passed, distinguishable from either explicit choice.536537##### Boolean groups538539When `flag_value` is `True` or `False`, the substitution rule does not apply:540`default=True` is the literal Python `True`. To make one flag in an541enable/disable pair the default, set its `default=True` explicitly:542543```python544@click.option("--without-xyz", "enable_xyz", flag_value=False)545@click.option("--with-xyz", "enable_xyz", flag_value=True, default=True)546```547548| Definition | Not passed | `--with-xyz` | `--without-xyz` |549|---------------------------------------------------------|------------|--------------|-----------------|550| `--with-xyz` with `flag_value=True`, `default=True` | `True` | `True` | `False` |551| `--without-xyz` with `flag_value=False`, `default=False`| `False` | `True` | `False` |552| `--with-xyz` with `flag_value=True`, `default=None` | `None` | `True` | `False` |553| Neither option carries a `default` | `False` | `True` | `False` |554555```{tip}556For most enable/disable cases, the pair form `--with-xyz/--without-xyz` is557shorter and equivalent. The multi-flag group form is useful when the on and off558flags need distinct names without a shared stem, or when each flag needs its559own help text.560```561562##### Arbitration rules563564When several options in a group resolve their values simultaneously, only one565wins the parameter slot. The full arbitration policy (source precedence,

change log and doc fixes (#3495)David Lordbefore adoption67921d5

line 566why, one step back
566explicit-beats-auto tie-break, last-declared fallback) is enumerated under

Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a

lines 567–622why, one step back
567[Option value resolution](#option-value-resolution).
568569## Option value resolution570571This section enumerates the rules Click applies when computing the value572delivered to the decorated function for every option. Rules are listed in the573order they fire during the parsing pipeline.574575### Type inference576577Without an explicit `type=`, Click infers the parameter type at construction:5785791. If `flag_value` is `True` or `False`, the type is {class}`BoolParamType`.5802. If `flag_value` is an `int`, `float`, or `str`, the type is the matching581 basic type.5823. If `flag_value` is any other Python object (a class, an enum member, a583 `frozenset`, ...), the type is {data}`UNPROCESSED` so the value passes584 through unchanged.5854. Otherwise, the type is inferred from `default` if set, falling back to586 {class}`StringParamType` when neither hint is available.587588### `default` interpretation589590The literal value passed as `default=` is interpreted differently depending on591whether the option is a flag and what `flag_value` it carries:5925931. `default=UNSET` (the absence sentinel) is treated as if `default` was not594 passed at all. It does not count as "the user picked nothing", and it does595 not count as an explicit default for arbitration purposes.5962. For a bare boolean flag (no `flag_value`, or `flag_value` of `True` or597 `False`), an unset `default` auto-derives to `False`.5983. For a non-boolean flag with a `flag_value`, `default=True` is substituted599 with `flag_value`. This is the "activate this flag by default" shorthand.600 Any non-`True` `default` is passed through literally.6014. For a boolean flag with `flag_value` set, `default=True` is the literal602 Python `True`. The substitution from rule 3 does not apply.6035. `default=None` is always a real explicit value, distinct from `UNSET`604 absence.6056. Any other `default` is delivered to the function unchanged after conversion606 through the parameter's type.607608### Value sources609610Click resolves the value of every option from the following611sources, in order of decreasing precedence:6126131. **command line input** ({attr}`ParameterSource.COMMANDLINE`),6142. **environment variable** named in `envvar=` or derived from `auto_envvar_prefix`615 ({attr}`ParameterSource.ENVIRONMENT`),6163. **`default_map` entry** matching the parameter name on the active {class}`Context`617 ({attr}`ParameterSource.DEFAULT_MAP`),6184. **parameter default** ({attr}`ParameterSource.DEFAULT`).619620The first source that produces a value wins. Environment variables and621`default_map` entries set to `Sentinel.UNSET` are skipped, so they fall through622to the next source rather than supplying `UNSET` to the function.

change log and doc fixes (#3495)David Lordbefore adoption67921d5

lines 623–628why, one step back
623
624If after the four sources above no explicit value was found (or only a625`default_map`/`default` value was) and the option declares `prompt=`, Click626prompts the user for one. The resulting value is recorded as627{attr}`ParameterSource.PROMPT`, which ranks above every source listed above628for arbitration purposes (see [Slot arbitration](#slot-arbitration)).

Merge Main into Stable (#3442)Rowlando13before adoptioncd4674a

lines 629–644why, one step back
629
630### Slot arbitration631632Several options can target the same `name` to form a feature switch group. When633they do, only one option's value reaches the function. Arbitration applies634these rules, in order:6356361. **By source.** Whichever option resolved its value from the most explicit637 source wins, regardless of decorator order. Any command-line input beats any638 default, an environment variable beats a `default_map` entry, and so on.6392. **Within the default tier, explicit beats auto-derived.** An option that640 received an explicit `default=` keyword wins over one whose default came641 from `default` interpretation.6423. **Otherwise, last declared wins.** When all options in the group resolved643 from the same source and tier (all auto-derived defaults, or all explicit644 defaults), the option declared last in the source code keeps the slot.

Merge branch 'main' into stableDavid Lordbefore adoption81a482f

line 645why, one step back
645

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

lines 646–647why, one step back
646## Values from Environment Variables
647

revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9

line 648why, one step back
648To pass in a value from a specific environment variable use `envvar`.

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

lines 649–678why, one step back
649
650```{eval-rst}651.. click:example::652653 @click.command()654 @click.option('--username', envvar='USERNAME')655 def greet(username):656 click.echo(f"Hello {username}!")657658.. click:run::659660 invoke(greet, env={'USERNAME': 'john'})661```662663If a list is passed to `envvar`, the first environment variable found is picked.664665```{eval-rst}666.. click:example::667668 @click.command()669 @click.option('--username', envvar=['ALT_USERNAME', 'USERNAME'])670 def greet(username):671 click.echo(f"Hello {username}!")672673.. click:run::674675 invoke(greet, env={'ALT_USERNAME': 'Bill', 'USERNAME': 'john'})676677```678

Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d

lines 679–680why, one step back
679Variable names are:
680 - [Case-insensitive on Windows but not on other platforms](https://github.com/python/cpython/blob/aa9eb5f757ceff461e6e996f12c89e5d9b583b01/Lib/os.py#L777-L789).

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 681–682why, one step back
681 - Not stripped of whitespace and should match the exact name provided to the
682 `envvar` argument.

Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d

line 683why, one step back
683

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 684–686why, one step back
684For flag options, there are two concepts to consider: the activation of the flag
685driven by the environment variable, and the value of the flag if it is686activated.

Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d

line 687why, one step back
687

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 688–690why, one step back
688The values read from environment variables are always strings and will require
689extra processing. We need to transform these strings into boolean values that690will determine if the flag is activated or not.

Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d

lines 691–693why, one step back
691
692Here are the rules used to parse environment variable values for flag options:693 - `true`, `1`, `yes`, `on`, `t`, `y` are interpreted as activating the flag

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 694–697why, one step back
694 - `false`, `0`, `no`, `off`, `f`, `n` are interpreted as deactivating the
695 flag696 - The presence of the environment variable without value is interpreted as697 deactivating the flag

Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d

line 698why, one step back
698 - Empty strings are interpreted as deactivating the flag

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 699–706why, one step back
699 - Values are case-insensitive, so the `True`, `TRUE`, `tRuE` strings are all
700 interpreted as activating the flag701 - Values are stripped of leading and trailing whitespace before being702 interpreted, so the `" True "` string is transformed to `"true"` and thus703 activates the flag704 - If the flag option has a `flag_value` argument, passing that value in the705 environment variable will activate the flag, in addition to all the cases706 described above

Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d

lines 707–708why, one step back
707 - Any other value is interpreted as deactivating the flag
708

Merge branch 'main' into stableDavid Lordbefore adoption81a482f

lines 709–710why, one step back
709```{caution}
710For boolean flags with a pair of values, the only recognized environment variable is the one provided to the `envvar` argument.

Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d

line 711why, one step back
711

docs: fix flag-pair separator and small typos in options guide (#3510)Kevin Deldyckebefore adoption8240d25

line 712why, one step back
712So an option defined as `--flag/--no-flag`, with an `envvar="FLAG"` parameter, there is no magical `NO_FLAG=<anything>` variable that is recognized. Only the `FLAG=<anything>` environment variable is recognized.

Merge branch 'main' into stableDavid Lordbefore adoption81a482f

line 713why, one step back
713```

Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d

line 714why, one step back
714

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 715–716why, one step back
715If the flag is activated, its value is set to `flag_value`. Otherwise, the value
716defaults to `None`.

Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d

line 717why, one step back
717

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

lines 718–720why, one step back
718## Multiple Options from Environment Values
719720As options can accept multiple values, pulling in such values from

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 721–723why, one step back
721environment variables (which are strings) is a bit more complex. Click handles
722this by deferring customization of the behavior to the `type`. For both723`multiple` and `nargs` with values other than

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

lines 724–753why, one step back
724`1`, Click will invoke the {meth}`ParamType.split_envvar_value` method to
725perform the splitting.726727The default implementation for all types is to split on whitespace. The728exceptions to this rule are the {class}`File` and {class}`Path` types729which both split according to the operating system's path splitting rules.730On Unix systems like Linux and OS X, the splitting happens on731every colon (`:`), and for Windows, splitting on every semicolon (`;`).732733```{eval-rst}734.. click:example::735736 @click.command()737 @click.option('paths', '--path', envvar='PATHS', multiple=True,738 type=click.Path())739 def perform(paths):740 for path in paths:741 click.echo(path)742743 if __name__ == '__main__':744 perform()745746.. click:run::747748 import os749 invoke(perform, env={"PATHS": f"./foo/bar{os.path.pathsep}./test"})750```751752## Other Prefix Characters753

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 754–756why, one step back
754Click can deal with prefix characters besides `-` for options, including `/` and
755`+`, as well as others. Note that alternative prefix characters are generally756used very sparingly if at all within POSIX.

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

lines 757–771why, one step back
757
758```{eval-rst}759.. click:example::760761 @click.command()762 @click.option('+w/-w')763 def chmod(w):764 click.echo(f"writable={w}")765766.. click:run::767768 invoke(chmod, args=['+w'])769 invoke(chmod, args=['-w'])770```771

Apply format guidelines to commits since latest 8.3.2 release (#3343)Rowlando13before adoptionf1f191e

lines 772–773why, one step back
772There are special considerations for using `/` as prefix character. See
773{ref}`option-boolean-flag` for more.

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

lines 774–783why, one step back
774
775(optional-value)=776777## Optional Value778779Providing the value to an option can be made optional, in which case780providing only the option's flag without a value will either show a781prompt or use its `flag_value`.782783Setting `is_flag=False, flag_value=value` tells Click that the option

Fixed the description of `is_flag=False, flag_value=value` (#2938)Rowlando13before adoptionbf7e691

lines 784–785why, one step back
784can still be passed a value, but if only the flag is given, the
785value will be `flag_value`.

Convert options docs to md. (#2924)Rowlando13before adoption937c68d

lines 786–800why, one step back
786
787```{eval-rst}788.. click:example::789790 @click.command()791 @click.option("--name", is_flag=False, flag_value="Flag", default="Default")792 def hello(name):793 click.echo(f"Hello, {name}!")794795.. click:run::796797 invoke(hello, args=[])798 invoke(hello, args=["--name", "Value"])799 invoke(hello, args=["--name"])800```