options.md
This file
Path
docs/options.md
504 lines · 14.5 KiB · Markdown
Last changed by
Document option no option pattern better (#3103)Rowlando13before adoption06f52a4
History of this fileTake it
Convert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 1–133why, 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 Decorator2627Click expects you to pass at least two positional arguments to the option decorator. They are option name and function argument name.2829```{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```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.4445```{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```5758More formally, Click will try to infer the function argument name by: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.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.6566```{eval-rst}67.. list-table:: Examples68 :widths: 15 1069 :header-rows: 17071 * - Decorator Arguments72 - Function Name73 * - ``"-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 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`.9293```{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 Options133Fix option multiple docs (#3086)Rowlando13before adoption2ed395b
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 underlying 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
lines 157–197why, one step back157158As 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:162163```{eval-rst}164.. click:example::165166 @click.command()167 @click.option('--item', type=(str, int))168 def putitem(item):169 name, id = item170 click.echo(f"name={name} id={id}")171172173And on the command line:174175.. click:run::176177 invoke(putitem, args=['--item', 'peter', '1338'])178```179180By using a tuple literal as type, `nargs` gets automatically set to the181length of the tuple and the {class}`click.Tuple` type is automatically182used. The above example is thus equivalent to this:183184```{eval-rst}185.. click:example::186187 @click.command()188 @click.option('--item', nargs=2, type=click.Tuple([str, int]))189 def putitem(item):190 name, id = item191 click.echo(f"name={name} id={id}")192```193194(multiple-options)=195196## Multiple Options197Fix option multiple docs (#3086)Rowlando13before adoption2ed395b
line 198why, one step back198The 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.Convert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 199–205why, one step back199200```{eval-rst}201.. click:example::202203 @click.command()204 @click.option('--message', '-m', multiple=True)205 def commit(message):Fix option multiple docs (#3086)Rowlando13before adoption2ed395b
lines 206–208why, one step back206 click.echo(message)207 for m in message:208 click.echo(m)Convert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 209–259why, one step back209210.. click:run::211212 invoke(commit, args=['-m', 'foo', '-m', 'bar', '-m', 'here'])213```214215## Counting216217To 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.218219```{eval-rst}220.. click:example::221222 @click.command()223 @click.option('-v', '--verbose', count=True)224 def log(verbose):225 click.echo(f"Verbosity: {verbose}")226227.. click:run::228229 invoke(log, args=[])230 invoke(log, args=['-vvv'])231```232233(option-boolean-flag)=234235## Boolean236237Boolean 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.238239```{eval-rst}240.. click:example::241242 import sys243244 @click.command()245 @click.option('--shout', is_flag=True)246 def info(shout):247 rv = sys.platform248 if shout:249 rv = rv.upper() + '!!!!111'250 click.echo(rv)251252253.. click:run::254255 invoke(info)256 invoke(info, args=['--shout'])257258```259Document option no option pattern better (#3103)Rowlando13before adoption06f52a4
line 260why, one step back260To implement this more explicitly, pass in on-option `/` off-option. Click will automatically set `is_flag=True`.Convert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 261–280why, one step back261262```{eval-rst}263.. click:example::264265 import sys266267 @click.command()268 @click.option('--shout/--no-shout', default=False)269 def info(shout):270 rv = sys.platform271 if shout:272 rv = rv.upper() + '!!!!111'273 click.echo(rv)274275.. click:run::276277 invoke(info)278 invoke(info, args=['--shout'])279 invoke(info, args=['--no-shout'])280```Document option no option pattern better (#3103)Rowlando13before adoption06f52a4
lines 281–286why, one step back281282Use cases for this more explicit pattern include:283284* 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.285* Shell scripts sometimes want to be explicit even when it's the default286* Shell aliases can set a flag, then an invocation can add a negation of the flagConvert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 287–298why, one step back287288If 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.289290```{eval-rst}291.. click:example::292293 @click.command()294 @click.option('/debug;/no-debug')295 def log(debug):296 click.echo(f"debug={debug}")297```298Fix version added and version changed in options docs. (#2957)Rowlando13before adoption497d1b6
lines 299–300why, one step back299```{versionchanged} 6.0300```Convert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 301–323why, one step back301302If you want to define an alias for the second option only, then you will need to use leading whitespace to disambiguate the format string.303304```{eval-rst}305.. click:example::306307 import sys308309 @click.command()310 @click.option('--shout/--no-shout', ' /-N', default=False)311 def info(shout):312 rv = sys.platform313 if shout:314 rv = rv.upper() + '!!!!111'315 click.echo(rv)316317.. click:run::318319 invoke(info, args=['--help'])320```321322## Flag Value323Merge branch 'main' into stableDavid Lordbefore adoption81a482f
line 324why, one step back324To 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:Convert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 325–344why, one step back325326```{eval-rst}327.. click:example::328329 import sys330331 @click.command()332 @click.option('--upper', 'transformation', flag_value='upper', default=True)333 @click.option('--lower', 'transformation', flag_value='lower')334 def info(transformation):335 click.echo(getattr(sys.platform, transformation)())336337.. click:run::338339 invoke(info, args=['--help'])340 invoke(info, args=['--upper'])341 invoke(info, args=['--lower'])342 invoke(info)343```344Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 345–364why, one step back345````{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.347348But 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`.349350Which means, in example above, this option:351352```python353@click.option('--upper', 'transformation', flag_value='upper', default=True)354```355356is equivalent to:357358```python359@click.option('--upper', 'transformation', flag_value='upper', default='upper')360```361362Because 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.363````364Convert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 365–397why, one step back365## Values from Environment Variables366367To pass in a value in from a specific environment variable use `envvar`.368369```{eval-rst}370.. click:example::371372 @click.command()373 @click.option('--username', envvar='USERNAME')374 def greet(username):375 click.echo(f"Hello {username}!")376377.. click:run::378379 invoke(greet, env={'USERNAME': 'john'})380```381382If a list is passed to `envvar`, the first environment variable found is picked.383384```{eval-rst}385.. click:example::386387 @click.command()388 @click.option('--username', envvar=['ALT_USERNAME', 'USERNAME'])389 def greet(username):390 click.echo(f"Hello {username}!")391392.. click:run::393394 invoke(greet, env={'ALT_USERNAME': 'Bill', 'USERNAME': 'john'})395396```397Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d
lines 398–415why, one step back398Variable names are:399 - [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.401402For 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.403404The 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.405406Here are the rules used to parse environment variable values for flag options:407 - `true`, `1`, `yes`, `on`, `t`, `y` are interpreted as activating the flag408 - `false`, `0`, `no`, `off`, `f`, `n` are interpreted as deactivating the flag409 - The presence of the environment variable without value is interpreted as deactivating the flag410 - 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 flag413 - 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 above414 - Any other value is interpreted as deactivating the flag415Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 416–417why, one step back416```{caution}417For 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 418why, one step back418Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 419–420why, one step back419So 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.420```Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d
lines 421–423why, one step back421422Once 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.423Convert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 424–487why, one step back424## Multiple Options from Environment Values425426As 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 than430`1`, Click will invoke the {meth}`ParamType.split_envvar_value` method to431perform the splitting.432433The default implementation for all types is to split on whitespace. The434exceptions to this rule are the {class}`File` and {class}`Path` types435which both split according to the operating system's path splitting rules.436On Unix systems like Linux and OS X, the splitting happens on437every colon (`:`), and for Windows, splitting on every semicolon (`;`).438439```{eval-rst}440.. click:example::441442 @click.command()443 @click.option('paths', '--path', envvar='PATHS', multiple=True,444 type=click.Path())445 def perform(paths):446 for path in paths:447 click.echo(path)448449 if __name__ == '__main__':450 perform()451452.. click:run::453454 import os455 invoke(perform, env={"PATHS": f"./foo/bar{os.path.pathsep}./test"})456```457458## Other Prefix Characters459460Click 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.462463```{eval-rst}464.. click:example::465466 @click.command()467 @click.option('+w/-w')468 def chmod(w):469 click.echo(f"writable={w}")470471.. click:run::472473 invoke(chmod, args=['+w'])474 invoke(chmod, args=['-w'])475```476477There are special considerations for using `/` as prefix character, see {ref}`option-boolean-flag` for more.478479(optional-value)=480481## Optional Value482483Providing the value to an option can be made optional, in which case484providing only the option's flag without a value will either show a485prompt or use its `flag_value`.486487Setting `is_flag=False, flag_value=value` tells Click that the optionFixed the description of `is_flag=False, flag_value=value` (#2938)Rowlando13before adoptionbf7e691
lines 488–489why, one step back488can still be passed a value, but if only the flag is given, the489value will be `flag_value`.Convert options docs to md. (#2924)Rowlando13before adoption937c68d
lines 490–504why, one step back490491```{eval-rst}492.. click:example::493494 @click.command()495 @click.option("--name", is_flag=False, flag_value="Flag", default="Default")496 def hello(name):497 click.echo(f"Hello, {name}!")498499.. click:run::500501 invoke(hello, args=[])502 invoke(hello, args=["--name", "Value"])503 invoke(hello, args=["--name"])504```