Skip to content
Myr

revise 'Options' documentation (#3192)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Rowlando13 · committed by GitHub · parents bb7be1f, 94715df · Browse files · 1 file+33 added−37 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+33 added−37 removed

  • other:+33 added−37 removed

1 file+33 added−37 removed

modified:docs/options.md+33 added-37 removed
22 unmodified lines
23```2425## Option Decorator2627Click expects you to pass at least two positional arguments to the option decorator. They are option name and function argument name.27The {func}`option()` decorator is usually passed two positional arguments: the option name and the decorated function argument name.2829```{eval-rst}30.. click:example::31
7 unmodified lines
3940 invoke(echo, args=['--help'])41```4243However, if you don't pass in the function argument name, then Click will try to infer it. A simple way to name your option is by taking the function argument, adding two dashes to the front and converting underscores to dashes. In this case, Click will infer the function argument name correctly so you can add only the option name.43However, 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.4445```{eval-rst}46.. click:example::47
6 unmodified lines
5455 invoke(echo, args=['--string-to-echo', 'Hi!'])56```5758More formally, Click will try to infer the function argument name by:58More formally, Click will try to infer the decorated function argument name as follows:59601. If a positional argument name does not have a prefix, it is chosen.612. If a positional argument name starts with with two dashes, the first one given is chosen.623. The first positional argument prefixed with one dash is chosen otherwise.601. 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.6364The chosen positional argument is converted to lower case, up to two dashes are removed from the beginning, and other dashes are converted to underscores to get the function argument name.64To 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 `_`.6566```{eval-rst}67.. list-table:: Examples68 :widths: 15 1068 :widths: 15 1569 :header-rows: 17071 * - Decorator Arguments72 - Function Name72 - Inferred Argument Name73 * - ``"-f", "--foo-bar"``74 - foo_bar75 * - ``"-x"``76 - x
10 unmodified lines
87```8889## Basic Example9091A simple {class}`click.Option` takes one argument. This will assume the argument is not required. If the decorated function takes an positional argument then None is passed it. This will also assume the type is `str`.91A 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.9293```{eval-rst}94.. click:example::95
34 unmodified lines
130```131132## Multi Value Options133134To 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 underlying function as a tuple.134To 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.135136```{eval-rst}137.. click:example::138
15 unmodified lines
154155```{versionadded} 4.0156```157158As you can see that by using `nargs` set to a specific number each item in159the resulting tuple is of the same type. This might not be what you want.160Commonly you might want to use different types for different indexes in161the tuple. For this you can directly specify a tuple as type:158By 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`:161162```{eval-rst}163.. click:example::164
10 unmodified lines
175176 invoke(putitem, args=['--item', 'peter', '1338'])177```178180By using a tuple literal as type, `nargs` gets automatically set to the179By using a tuple literal as the `type`, `nargs` gets automatically set to the180length of the tuple and the {class}`click.Tuple` type is automatically181used. The above example is thus equivalent to this:182183```{eval-rst}
9 unmodified lines
193(multiple-options)=194195## Multiple Options196198The multiple options format allows options to take an arbitrary number of arguments (which is called variadic). The arguments are passed to the underlying function as a tuple. If set, the default must be a list or tuple. Setting a string as a default will be interpreted as list of characters.197The 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.198199```{eval-rst}200.. click:example::201
10 unmodified lines
212```213214## Counting215217To count the occurrence of an option pass in `count=True`. If the option is not passed in, then the count is 0. Counting is commonly used for verbosity.216To 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.217218```{eval-rst}219.. click:example::220
11 unmodified lines
232(option-boolean-flag)=233234## Boolean235237Boolean options (boolean flags) take the value True or False. The simplest case sets the default value to `False` if the flag is not passed, and `True` if it is.236Boolean 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.237238```{eval-rst}239.. click:example::240
14 unmodified lines
255 invoke(info, args=['--shout'])256257```258260To implement this more explicitly, pass in on-option `/` off-option. Click will automatically set `is_flag=True`.259To implement this more explicitly, declare `--{on-option}/--{off-option}`. Click will automatically set `is_flag=True`.260261```{eval-rst}262.. click:example::263
55 unmodified lines
319```320321## Flag Value322324To have an flag pass a value to the underlying 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:323To 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:324325```{eval-rst}326.. click:example::327
13 unmodified lines
341 invoke(info)342```343344````{note}346The `default` value is given to the underlying 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.345The `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.346348But 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 underlying function receiving the `True` Python value, it will receive the `flag_value`.347But 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`.348349Which means, in example above, this option:350351```python
5 unmodified lines
357```python358@click.option('--upper', 'transformation', flag_value='upper', default='upper')359```360362Because the two are equivalent, it is recommended to always use the second form, and set `default` to the actual value you want to pass. And not use the special `True` case. This makes the code more explicit and predictable.361Because 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.362````363364## Values from Environment Variables365367To pass in a value in from a specific environment variable use `envvar`.366To pass in a value from a specific environment variable use `envvar`.367368```{eval-rst}369.. click:example::370
24 unmodified lines
395```396397Variable names are:398 - [Case-insensitive on Windows but not on other platforms](https://github.com/python/cpython/blob/aa9eb5f757ceff461e6e996f12c89e5d9b583b01/Lib/os.py#L777-L789).400 - Not stripped of whitespaces and should match the exact name provided to the `envvar` argument.399 - Not stripped of whitespace and should match the exact name provided to the `envvar` argument.400402For flag options, there is two concepts to consider: the activation of the flag driven by the environment variable, and the value of the flag if it is activated.401For 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.402404The environment variable need to be interpreted, because values read from them are always strings. We need to transform these strings into boolean values that will determine if the flag is activated or not.403The 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.404405Here 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 flag411 - Values are case-insensitive, so the `True`, `TRUE`, `tRuE` strings are all activating the flag412 - Values are stripped of leading and trailing whitespaces before being interpreted, so the `" True "` string is transformed to `"true"` and so activates the flag410 - 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 flag412 - 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 flag414415```{caution}
1 unmodified line
417418So 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```420422Once the status of the flag has been determine to be activated or not, the `flag_value` is used as the value of the flag if it is activated. If the flag is not activated, the value of the flag is set to `None` by default.421If the flag is activated, its value is set to `flag_value`. Otherwise, the value defaults to `None`.422423## Multiple Options from Environment Values424425As options can accept multiple values, pulling in such values from427environment variables (which are strings) is a bit more complex. The way428Click solves this is by leaving it up to the type to customize this429behavior. For both `multiple` and `nargs` with values other than426environment 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 than427`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. The
22 unmodified lines
453```454455## Other Prefix Characters456460Click can deal with prefix characters besides `-` for options. Click can use461`/`, `+` as well as others. Note that alternative prefix characters are generally used very sparingly if at all within POSIX.457Click 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.458459```{eval-rst}460.. click:example::461
7 unmodified lines
469 invoke(chmod, args=['+w'])470 invoke(chmod, args=['-w'])471```472477There are special considerations for using `/` as prefix character, see {ref}`option-boolean-flag` for more.473There are special considerations for using `/` as prefix character. See {ref}`option-boolean-flag` for more.474475(optional-value)=476477## Optional Value
23 unmodified lines