options.md
This file
Path
docs/options.md
500 lines · 14.5 KiB · Markdown
Last changed by
revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9
History of this fileTake it
Convert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 1–26why, one step back1(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. Options in Click are distinct from {ref}`positional arguments <arguments>`.1112Useful and often used kwargs are:1314- `default`: Passes a default.15- `help`: Sets help message.16- `nargs`: Sets the number of arguments.17- `required`: Makes option required.18- `type`: Sets {ref}`parameter type <parameter-types>`1920```{contents}21:depth: 222:local: true23```2425## Option Decorator26revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9
line 27why, one step back27The {func}`option()` decorator is usually passed two positional arguments: the option name and the decorated function argument name.Convert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 28–42why, one step back2829```{eval-rst}30.. click:example::3132 @click.command()33 @click.option('--string-to-echo', 'string_to_echo')34 def echo(string_to_echo):35 click.echo(string_to_echo)363738.. click:run::3940 invoke(echo, args=['--help'])41```42revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9
line 43why, one step back43However, if the decorated function argument name is not passed in, then Click will try to infer it. A simple way to name the option so that Click will infer it correctly is by taking the function argument, adding two dashes to the front and converting underscores to dashes.Convert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 44–57why, one step back4445```{eval-rst}46.. click:example::4748 @click.command()49 @click.option('--string-to-echo')50 def echo(string_to_echo):51 click.echo(string_to_echo)5253.. click:run::5455 invoke(echo, args=['--string-to-echo', 'Hi!'])56```57revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9
line 58why, one step back58More formally, Click will try to infer the decorated function argument name as follows:Convert options docs to md. (#2924)Rowlando13before adoption937c68d
line 59why, one step back59revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9
lines 60–62why, one step back601. 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.612. If multiple positional arguments are prefixed with `--`, the first one declared is chosen.623. Otherwise, the first positional argument prefixed with `-` is chosen.Convert options docs to md. (#2924)Rowlando13before adoption937c68d
line 63why, one step back63revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9
line 64why, one step back64To get the argument name, the chosen positional argument is converted to lower case, a leading `-` or `--` is removed if found, and any remaining `-` characters are replaced with `_`.Convert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 65–67why, one step back6566```{eval-rst}67.. list-table:: Examplesrevise 'Options' documentation (#3192)Rowlando13before adoption81efdc9
line 68why, one step back68 :widths: 15 15Convert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 69–71why, one step back69 :header-rows: 17071 * - Decorator Argumentsrevise 'Options' documentation (#3192)Rowlando13before adoption81efdc9
line 72why, one step back72 - Inferred Argument NameConvert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 73–90why, one step back73 * - ``"-f", "--foo-bar"``74 - foo_bar75 * - ``"-x"``76 - x77 * - ``"-f", "--filename", "dest"``78 - dest79 * - ``"--CamelCase"``80 - camelcase81 * - ``"-f", "-fb"``82 - f83 * - ``"--f", "--foo-bar"``84 - f85 * - ``"---f"``86 - _f87```8889## Basic Example90revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9
line 91why, one step back91A simple {class}`click.Option` takes one option name. By default, it's assumed that the decorated function argument is not required and the expected type is `str`. If the decorated function takes a positional argument but the option is not passed with the command, then `None` is passed.Convert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 92–133why, one step back9293```{eval-rst}94.. click:example::9596 @click.command()97 @click.option('--text')98 def print_this(text):99 click.echo(text)100101102.. click:run::103104 invoke(print_this, args=['--text=this'])105106 invoke(print_this, args=[])107108109.. click:run::110111 invoke(print_this, args=['--help'])112113```114115## Setting a Default116117Instead of setting the `type`, you may set a default and Click will try to infer the type.118119```{eval-rst}120.. click:example::121122 @click.command()123 @click.option('--n', default=1)124 def dots(n):125 click.echo('.' * n)126127.. click:run::128129 invoke(dots, args=['--help'])130```131132## Multi Value Options133revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9
line 134why, one step back134To make an option take multiple values, pass in `nargs`. Note you may pass in any positive integer, but not -1. The values are passed to the decorated function as a tuple.Convert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 135–154why, one step back135136```{eval-rst}137.. click:example::138139 @click.command()140 @click.option('--pos', nargs=2, type=float)141 def findme(pos):142 a, b = pos143 click.echo(f"{a} / {b}")144145.. click:run::146147 invoke(findme, args=['--pos', '2.0', '3.0'])148149```150151(tuple-type)=152153## Multi Value Options as Tuples154Fix version added and version changed in options docs. (#2957)Rowlando13before adoption497d1b6
lines 155–156why, one step back155```{versionadded} 4.0156```Convert options docs to md. (#2924)Rowlando13before adoption937c68d
line 157why, one step back157revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9
lines 158–160why, one step back158By setting `nargs` to a specific number, each item in159the resulting tuple is of the same type. Alternatively, you might want to use different types for different indexes in160the tuple. For this you can directly specify a tuple as `type`:Convert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 161–178why, one step back161162```{eval-rst}163.. click:example::164165 @click.command()166 @click.option('--item', type=(str, int))167 def putitem(item):168 name, id = item169 click.echo(f"name={name} id={id}")170171172And on the command line:173174.. click:run::175176 invoke(putitem, args=['--item', 'peter', '1338'])177```178revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9
line 179why, one step back179By using a tuple literal as the `type`, `nargs` gets automatically set to theConvert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 180–196why, one step back180length of the tuple and the {class}`click.Tuple` type is automatically181used. The above example is thus equivalent to this:182183```{eval-rst}184.. click:example::185186 @click.command()187 @click.option('--item', nargs=2, type=click.Tuple([str, int]))188 def putitem(item):189 name, id = item190 click.echo(f"name={name} id={id}")191```192193(multiple-options)=194195## Multiple Options196revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9
line 197why, one step back197The multiple options format allows options to take an arbitrary number of arguments (which is called variadic). The arguments are passed to the decorated function as a tuple. If set, `default` must be a list or tuple. Setting a string as `default` will be interpreted as a list of characters.Convert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 198–204why, one step back198199```{eval-rst}200.. click:example::201202 @click.command()203 @click.option('--message', '-m', multiple=True)204 def commit(message):Fix option multiple docs (#3086)Rowlando13before adoption2ed395b
lines 205–207why, one step back205 click.echo(message)206 for m in message:207 click.echo(m)Convert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 208–215why, one step back208209.. click:run::210211 invoke(commit, args=['-m', 'foo', '-m', 'bar', '-m', 'here'])212```213214## Counting215revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9
line 216why, one step back216To count the occurrence of an option, set `count=True`. If the option is not passed on the command line, then the count is 0. Counting is commonly used for verbosity.Convert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 217–235why, one step back217218```{eval-rst}219.. click:example::220221 @click.command()222 @click.option('-v', '--verbose', count=True)223 def log(verbose):224 click.echo(f"Verbosity: {verbose}")225226.. click:run::227228 invoke(log, args=[])229 invoke(log, args=['-vvv'])230```231232(option-boolean-flag)=233234## Boolean235revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9
line 236why, one step back236Boolean options (boolean flags) take the values `True` or `False`. The simplest case sets the default value to `False` if the flag is not passed, and `True` if it is.Convert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 237–258why, one step back237238```{eval-rst}239.. click:example::240241 import sys242243 @click.command()244 @click.option('--shout', is_flag=True)245 def info(shout):246 rv = sys.platform247 if shout:248 rv = rv.upper() + '!!!!111'249 click.echo(rv)250251252.. click:run::253254 invoke(info)255 invoke(info, args=['--shout'])256257```258revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9
line 259why, one step back259To implement this more explicitly, declare `--{on-option}/--{off-option}`. Click will automatically set `is_flag=True`.Convert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 260–279why, one step back260261```{eval-rst}262.. click:example::263264 import sys265266 @click.command()267 @click.option('--shout/--no-shout', default=False)268 def info(shout):269 rv = sys.platform270 if shout:271 rv = rv.upper() + '!!!!111'272 click.echo(rv)273274.. click:run::275276 invoke(info)277 invoke(info, args=['--shout'])278 invoke(info, args=['--no-shout'])279```Document option no option pattern better (#3103)Rowlando13before adoption06f52a4
lines 280–285why, one step back280281Use cases for this more explicit pattern include:282283* The default can be dynamic so the user can explicitly specify the option with either on or off option, or pass in no option to use the dynamic default.284* Shell scripts sometimes want to be explicit even when it's the default285* Shell aliases can set a flag, then an invocation can add a negation of the flagConvert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 286–297why, one step back286287If a forward slash(`/`) is contained in your option name already, you can split the parameters using `;`. In Windows `/` is commonly used as the prefix character.288289```{eval-rst}290.. click:example::291292 @click.command()293 @click.option('/debug;/no-debug')294 def log(debug):295 click.echo(f"debug={debug}")296```297Fix version added and version changed in options docs. (#2957)Rowlando13before adoption497d1b6
lines 298–299why, one step back298```{versionchanged} 6.0299```Convert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 300–322why, one step back300301If you want to define an alias for the second option only, then you will need to use leading whitespace to disambiguate the format string.302303```{eval-rst}304.. click:example::305306 import sys307308 @click.command()309 @click.option('--shout/--no-shout', ' /-N', default=False)310 def info(shout):311 rv = sys.platform312 if shout:313 rv = rv.upper() + '!!!!111'314 click.echo(rv)315316.. click:run::317318 invoke(info, args=['--help'])319```320321## Flag Value322revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9
line 323why, one step back323To have a flag pass a value to the decorated function set `flag_value`. This automatically sets `is_flag=True`. To mark the flag as default, set `default=True`. Setting flag values can be used to create patterns like this:Convert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 324–343why, one step back324325```{eval-rst}326.. click:example::327328 import sys329330 @click.command()331 @click.option('--upper', 'transformation', flag_value='upper', default=True)332 @click.option('--lower', 'transformation', flag_value='lower')333 def info(transformation):334 click.echo(getattr(sys.platform, transformation)())335336.. click:run::337338 invoke(info, args=['--help'])339 invoke(info, args=['--upper'])340 invoke(info, args=['--lower'])341 invoke(info)342```343Merge branch 'main' into stableDavid Lordbefore adoption81a482f
line 344why, one step back344````{note}revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9
line 345why, one step back345The `default` value is given to the decorated function as-is. So if you set `default=None`, the value passed to the function is the `None` Python value. Same for any other type.Merge branch 'main' into stableDavid Lordbefore adoption81a482f
line 346why, one step back346revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9
line 347why, one step back347But there is a special case for flags. If a flag has a `flag_value`, then setting `default=True` is interpreted as *the flag should be activated by default*. So instead of the decorated function receiving the `True` Python value, it will receive the `flag_value`.Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 348–360why, one step back348349Which means, in example above, this option:350351```python352@click.option('--upper', 'transformation', flag_value='upper', default=True)353```354355is equivalent to:356357```python358@click.option('--upper', 'transformation', flag_value='upper', default='upper')359```360revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9
line 361why, one step back361Because the two are equivalent, it is recommended to always set `default` to the actual value you want to pass and avoid using the special `True` case. This makes the code more explicit and predictable.Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 362–363why, one step back362````363Convert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 364–365why, one step back364## Values from Environment Variables365revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9
line 366why, one step back366To pass in a value from a specific environment variable use `envvar`.Convert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 367–396why, one step back367368```{eval-rst}369.. click:example::370371 @click.command()372 @click.option('--username', envvar='USERNAME')373 def greet(username):374 click.echo(f"Hello {username}!")375376.. click:run::377378 invoke(greet, env={'USERNAME': 'john'})379```380381If a list is passed to `envvar`, the first environment variable found is picked.382383```{eval-rst}384.. click:example::385386 @click.command()387 @click.option('--username', envvar=['ALT_USERNAME', 'USERNAME'])388 def greet(username):389 click.echo(f"Hello {username}!")390391.. click:run::392393 invoke(greet, env={'ALT_USERNAME': 'Bill', 'USERNAME': 'john'})394395```396Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d
lines 397–398why, one step back397Variable names are:398 - [Case-insensitive on Windows but not on other platforms](https://github.com/python/cpython/blob/aa9eb5f757ceff461e6e996f12c89e5d9b583b01/Lib/os.py#L777-L789).revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9
line 399why, one step back399 - Not stripped of whitespace and should match the exact name provided to the `envvar` argument.Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d
line 400why, one step back400revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9
line 401why, one step back401For flag options, there are two concepts to consider: the activation of the flag driven by the environment variable, and the value of the flag if it is activated.Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d
line 402why, one step back402revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9
line 403why, one step back403The values read from environment variables are always strings and will require extra processing. We need to transform these strings into boolean values that will 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 404–409why, one step back404405Here are the rules used to parse environment variable values for flag options:406 - `true`, `1`, `yes`, `on`, `t`, `y` are interpreted as activating the flag407 - `false`, `0`, `no`, `off`, `f`, `n` are interpreted as deactivating the flag408 - The presence of the environment variable without value is interpreted as deactivating the flag409 - Empty strings are interpreted as deactivating the flagrevise 'Options' documentation (#3192)Rowlando13before adoption81efdc9
lines 410–411why, one step back410 - Values are case-insensitive, so the `True`, `TRUE`, `tRuE` strings are all interpreted as activating the flag411 - Values are stripped of leading and trailing whitespace before being interpreted, so the `" True "` string is transformed to `"true"` and thus activates the flagFix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d
lines 412–414why, one step back412 - If the flag option has a `flag_value` argument, passing that value in the environment variable will activate the flag, in addition to all the cases described above413 - Any other value is interpreted as deactivating the flag414Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 415–416why, one step back415```{caution}416For 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 417why, one step back417Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 418–419why, one step back418So 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.419```Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d
line 420why, one step back420revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9
line 421why, one step back421If the flag is activated, its value is set to `flag_value`. Otherwise, the value defaults to `None`.Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d
line 422why, one step back422Convert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 423–425why, one step back423## Multiple Options from Environment Values424425As options can accept multiple values, pulling in such values fromrevise 'Options' documentation (#3192)Rowlando13before adoption81efdc9
line 426why, one step back426environment variables (which are strings) is a bit more complex. Click handles this by deferring customization of the behavior to the `type`. For both `multiple` and `nargs` with values other thanConvert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 427–456why, one step back427`1`, Click will invoke the {meth}`ParamType.split_envvar_value` method to428perform the splitting.429430The default implementation for all types is to split on whitespace. The431exceptions to this rule are the {class}`File` and {class}`Path` types432which both split according to the operating system's path splitting rules.433On Unix systems like Linux and OS X, the splitting happens on434every colon (`:`), and for Windows, splitting on every semicolon (`;`).435436```{eval-rst}437.. click:example::438439 @click.command()440 @click.option('paths', '--path', envvar='PATHS', multiple=True,441 type=click.Path())442 def perform(paths):443 for path in paths:444 click.echo(path)445446 if __name__ == '__main__':447 perform()448449.. click:run::450451 import os452 invoke(perform, env={"PATHS": f"./foo/bar{os.path.pathsep}./test"})453```454455## Other Prefix Characters456revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9
line 457why, one step back457Click can deal with prefix characters besides `-` for options, including `/` and `+`, as well as others. Note that alternative prefix characters are generally used very sparingly if at all within POSIX.Convert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 458–472why, one step back458459```{eval-rst}460.. click:example::461462 @click.command()463 @click.option('+w/-w')464 def chmod(w):465 click.echo(f"writable={w}")466467.. click:run::468469 invoke(chmod, args=['+w'])470 invoke(chmod, args=['-w'])471```472revise 'Options' documentation (#3192)Rowlando13before adoption81efdc9
line 473why, one step back473There are special considerations for using `/` as prefix character. See {ref}`option-boolean-flag` for more.Convert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 474–483why, one step back474475(optional-value)=476477## Optional Value478479Providing the value to an option can be made optional, in which case480providing only the option's flag without a value will either show a481prompt or use its `flag_value`.482483Setting `is_flag=False, flag_value=value` tells Click that the optionFixed the description of `is_flag=False, flag_value=value` (#2938)Rowlando13before adoptionbf7e691
lines 484–485why, one step back484can still be passed a value, but if only the flag is given, the485value will be `flag_value`.Convert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 486–500why, one step back486487```{eval-rst}488.. click:example::489490 @click.command()491 @click.option("--name", is_flag=False, flag_value="Flag", default="Default")492 def hello(name):493 click.echo(f"Hello, {name}!")494495.. click:run::496497 invoke(hello, args=[])498 invoke(hello, args=["--name", "Value"])499 invoke(hello, args=["--name"])500```