option-decorators.md
This file
Path
docs/option-decorators.md
86 lines · 2.1 KiB · Markdown
Last changed by
Move Option-decorators doc from reST to MyST (#3063)Rowlando13before adoption29a68ca
History of this fileTake it
Move Option-decorators doc from reST to MyST (#3063)Rowlando13before adoption29a68ca
lines 1–86why, one step back1# Options Shortcut Decorators23```{currentmodule} click4```56For convenience commonly used combinations of options arguments are available as their own decorators.78```{contents}9---10depth: 211local: true12---13```1415## Password Option1617Click supports hidden prompts and asking for confirmation. This is useful for password input:1819```{eval-rst}20.. click:example::2122 import codecs2324 @click.command()25 @click.option(26 "--password", prompt=True, hide_input=True,27 confirmation_prompt=True28 )29 def encode(password):30 click.echo(f"encoded: {codecs.encode(password, 'rot13')}")3132.. click:run::3334 invoke(encode, input=['secret', 'secret'])35```3637Because this combination of parameters is quite common, this can also be38replaced with the {func}`password_option` decorator:3940```python41 @click.command()42 @click.password_option()43 def encrypt(password):44 click.echo(f"encoded: to {codecs.encode(password, 'rot13')}")45```4647## Confirmation Option4849For dangerous operations, it's very useful to be able to ask a user for confirmation. This can be done by adding a50boolean `--yes` flag and asking for confirmation if the user did not provide it and to fail in a callback:5152```{eval-rst}53.. click:example::5455 def abort_if_false(ctx, param, value):56 if not value:57 ctx.abort()5859 @click.command()60 @click.option('--yes', is_flag=True, callback=abort_if_false,61 expose_value=False,62 prompt='Are you sure you want to drop the db?')63 def dropdb():64 click.echo('Dropped all tables!')6566And what it looks like on the command line:6768.. click:run::6970 invoke(dropdb, input=['n'])71 invoke(dropdb, args=['--yes'])7273Because this combination of parameters is quite common, this can also be74replaced with the :func:`confirmation_option` decorator:7576.. click:example::7778 @click.command()79 @click.confirmation_option(prompt='Are you sure you want to drop the db?')80 def dropdb():81 click.echo('Dropped all tables!')82```8384## Version Option8586{func}`version_option` adds a `--version` option which immediately prints the version number and exits the program.