option-decorators.md
This file
Path
docs/option-decorators.md
88 lines · 2.4 KiB · Markdown
Last changed by
Pre-8.5.0 release changelog and doc fixes (#3697)Rowlando13before adoption00e592c
History of this fileTake it
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889# Options Shortcut Decorators
```{currentmodule} click```
For convenience commonly used combinations of options arguments are available as their own decorators.
```{contents}---depth: 2local: true---```
## Password Option
Click supports hidden prompts and asking for confirmation. This is useful for password input:
```{eval-rst}.. click:example::
import codecs
@click.command() @click.option( "--password", prompt=True, hide_input=True, confirmation_prompt=True ) def encode(password): click.echo(f"encoded: {codecs.encode(password, 'rot13')}")
.. click:run::
invoke(encode, input=['secret', 'secret'])```
Because this combination of parameters is quite common, this can also bereplaced with the {func}`password_option` decorator:
```python @click.command() @click.password_option() def encrypt(password): click.echo(f"encoded: to {codecs.encode(password, 'rot13')}")```
## Confirmation Option
For dangerous operations, it's very useful to be able to ask a user for confirmation. This can be done by adding aboolean `--yes` flag and asking for confirmation if the user did not provide it and to fail in a callback:
```{eval-rst}.. click:example::
def abort_if_false(ctx, param, value): if not value: ctx.abort()
@click.command() @click.option('--yes', is_flag=True, callback=abort_if_false, expose_value=False, prompt='Are you sure you want to drop the db?') def dropdb(): click.echo('Dropped all tables!')
And what it looks like on the command line:
.. click:run::
invoke(dropdb, input=['n']) invoke(dropdb, args=['--yes'])
Because this combination of parameters is quite common, this can also bereplaced with the :func:`confirmation_option` decorator:
.. click:example::
@click.command() @click.confirmation_option(prompt='Are you sure you want to drop the db?') def dropdb(): click.echo('Dropped all tables!')```
## Version Option
{func}`version_option` adds a `--version` option which immediately prints the version number and exits the program.
The message and values it can show are intentionally limited, and its feature set is frozen. If you need values it does not expose, such as the Python version or git metadata, use {func}`custom_version_option` and produce the output yourself in a callback.