Skip to content
Myr

options.md

This file

Path

docs/options.md

800 lines · 25.1 KiB · Markdown

Last changed by

Merge stable into main (#3521)Rowlando13before adoption1a994ad

History of this file

Take it

Show it rendered

1(options)=23# Options45```{eval-rst}6.. currentmodule:: click7```89Adding options to commands can be accomplished with the {func}`option`10decorator. At runtime the decorator invokes the {class}`Option` class. Options11in Click are distinct from {ref}`positional arguments <arguments>`.1213Useful 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 Decorator2728The {func}`option()` decorator is usually passed two positional arguments: the29option name and the decorated function argument name.3031```{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```4445However, if the decorated function argument name is not passed in, then Click46will 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.4950```{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```6263More formally, Click will try to infer the decorated function argument name as64follows:65661. 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.672. If multiple positional arguments are prefixed with `--`, the first one68  declared is chosen.693. Otherwise, the first positional argument prefixed with `-` is chosen.7071To get the argument name, the chosen positional argument is converted to lower72case, a leading `-` or `--` is removed if found, and any remaining `-`73characters are replaced with `_`.7475```{eval-rst}76.. list-table:: Examples77    :widths: 15 1578    :header-rows: 17980    * - Decorator Arguments81      - Inferred Argument Name82    * - ``"-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 Example99100A simple {class}`click.Option` takes one option name. By default, it's assumed101that 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.104105```{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 Default128129Instead of setting the `type`, you may set a default and Click will try to infer130the type.131132```{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 Options146147To make an option take multiple values, pass in `nargs`. Note you may pass in148any positive integer, but not -1. The values are passed to the decorated149function as a tuple.150151```{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 Tuples169170```{versionadded} 4.0171```172173By setting `nargs` to a specific number, each item in174the resulting tuple is of the same type. Alternatively, you might want to use175different types for different indexes in176the tuple. For this you can directly specify a tuple as `type`:177178```{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```194195By using a tuple literal as the `type`, `nargs` gets automatically set to the196length of the tuple and the {class}`click.Tuple` type is automatically197used. 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 Options212213The multiple options format allows options to take an arbitrary number of214arguments (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.217218```{eval-rst}219.. click:example::220221    @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)227228.. click:run::229230    invoke(commit, args=['-m', 'foo', '-m', 'bar', '-m', 'here'])231```232233## Combining short options234235Short 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```274275## Counting276277To count the occurrence of an option, set `count=True`. If the option is not278passed on the command line, then the count is 0. Counting is commonly used for279verbosity.280281```{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## Boolean298299Boolean options (boolean flags) take the values `True` or `False`. The simplest300case sets the default value to `False` if the flag is not passed, and `True` if301it is.302303```{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```323324To implement this more explicitly, declare `--{on-option}/--{off-option}`. Click325will automatically set `is_flag=True`.326327```{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```346347Use cases for this more explicit pattern include:348349* The default can be dynamic so the user can explicitly specify the option with350  either on or off option, or pass in no option to use the dynamic default.351* Shell scripts sometimes want to be explicit even when it's the default352* Shell aliases can set a flag, then an invocation can add a negation of the353  flag354355If a forward slash (`/`) is contained in your option name already, you can split356the parameters using `;`. In Windows `/` is commonly used as the prefix357character.358359```{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```367368```{versionchanged} 6.0369```370371If you want to define an alias for the second option only, then you will need to372use leading whitespace to disambiguate the format string.373374```{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 Value393394To have a flag pass a value to the decorated function set `flag_value`. This395automatically sets `is_flag=True`. To mark the flag as default, set396`default=True`. Setting flag values can be used to create patterns like this:397398```{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```416417### How `default` and `flag_value` interact418419The `default` value is given to the underlying function420as-is. So if you set `default=None`, the function receives421`None`. Same for any other type.422423But there is a special case for **non-boolean** flags: if a424flag 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`.428429Which means, in the example above, this option:430431```python432@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```440441Because the two are equivalent, it is recommended to always442use 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```480````481482#### 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)513514Several `flag_value` options can target the same parameter name to form a515feature 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.519520##### Non-boolean groups521522For 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.526527| 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"` |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,566explicit-beats-auto tie-break, last-declared fallback) is enumerated under567[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.623624If 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)).629630### 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.645646## Values from Environment Variables647648To pass in a value from a specific environment variable use `envvar`.649650```{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```678679Variable names are:680 - [Case-insensitive on Windows but not on other platforms](https://github.com/python/cpython/blob/aa9eb5f757ceff461e6e996f12c89e5d9b583b01/Lib/os.py#L777-L789).681 - Not stripped of whitespace and should match the exact name provided to the682   `envvar` argument.683684For flag options, there are two concepts to consider: the activation of the flag685driven by the environment variable, and the value of the flag if it is686activated.687688The values read from environment variables are always strings and will require689extra processing. We need to transform these strings into boolean values that690will determine if the flag is activated or not.691692Here are the rules used to parse environment variable values for flag options:693   - `true`, `1`, `yes`, `on`, `t`, `y` are interpreted as activating the flag694   - `false`, `0`, `no`, `off`, `f`, `n` are interpreted as deactivating the695     flag696   - The presence of the environment variable without value is interpreted as697     deactivating the flag698   - Empty strings are interpreted as deactivating the flag699   - Values are case-insensitive, so the `True`, `TRUE`, `tRuE` strings are all700     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 above707   - Any other value is interpreted as deactivating the flag708709```{caution}710For boolean flags with a pair of values, the only recognized environment variable is the one provided to the `envvar` argument.711712So 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.713```714715If the flag is activated, its value is set to `flag_value`. Otherwise, the value716defaults to `None`.717718## Multiple Options from Environment Values719720As options can accept multiple values, pulling in such values from721environment variables (which are strings) is a bit more complex. Click handles722this by deferring customization of the behavior to the `type`. For both723`multiple` and `nargs` with values other than724`1`, Click will invoke the {meth}`ParamType.split_envvar_value` method to725perform 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 Characters753754Click can deal with prefix characters besides `-` for options, including `/` and755`+`, as well as others. Note that alternative prefix characters are generally756used very sparingly if at all within POSIX.757758```{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```771772There are special considerations for using `/` as prefix character. See773{ref}`option-boolean-flag` for more.774775(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 option784can still be passed a value, but if only the flag is given, the785value will be `flag_value`.786787```{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```